#!/usr/bin/python

import sys
import os

args = sys.argv[1:]
blurb = 'Usage: duplex2up.py <filename> <x0> <y0> <x1> <y1> [<x0> <y0> <x1> <y1>]'

if len(args) < 5:
     print blurb
     sys.exit()

filename = args[0]
x0l = int(args[1])
y0l = int(args[2])
x1l = int(args[3])
y1l = int(args[4])

try: 
     x0r = int(args[5])
     y0r = int(args[6])
     x1r = int(args[7])
     y1r = int(args[8])

except IndexError:
     x0r = x0l
     y0r = y0l
     x1r = x1l
     y1r = y1l

 
margin = 28	# uniform margin of 1cm (28 pts)
offset = 72	# margin needed on the binding edge
x_size = 595	# width of a4 paper
y_size = 842	# height of a4 paper
sqrt2 = 1.41421 # square root of 2
tx = 22*sqrt2 	# x shift needed for duplexing
ty = 421	# y shift needed for duplexing


# calculate the parameters for the first page. parameters for the other
# pages follow simply

scalel = (y_size-(margin+offset))/(sqrt2*(y1l-y0l))
x_shiftl = x_size + scalel*y0l - margin/sqrt2
y_shiftl = (x_size - sqrt2*scalel*(x0l + x1l))/(2*sqrt2)

scaler = (y_size-(margin+offset))/(sqrt2*(y1r-y0r))
x_shiftr = x_size + scaler*y0r - margin/sqrt2
y_shiftr = (x_size - sqrt2*scaler*(x0r + x1r))/(2*sqrt2)

# record all the parameters in an array

page = [[str(scalel),str(x_shiftl),str(y_shiftl)],[str(scaler),str(x_shiftr),str(y_shiftr+ty)],[str(scalel),str(x_shiftl-tx),str(y_shiftl)],[str(scaler),str(x_shiftr-tx),str(y_shiftr+ty)]]

# construct the command to perform the layout

cmd = 'pstops -pa4 \"4:0L@'+page[0][0]+'('+page[0][1]+','+page[0][2]+')+1L@'+page[1][0]+'('+page[1][1]+','+page[1][2]+'),2L@'+page[2][0]+'('+page[2][1]+','+page[2][2]+')+3L@'+page[3][0]+'('+page[3][1]+','+page[3][2]+')\" '+filename+' '+filename.split('.')[0]+'.d2up.ps.2'

try:
     po = os.popen(cmd)
except IOError:
     print 'why?'
     sys.exit()
po.close()

# now we want to fix that annoying bounding box at the beginning of the file

out = file(filename.split('.')[0]+'.d2up.ps',"w")
flag = False
for line in file(filename.split('.')[0]+'.d2up.ps.2'):
     if flag:
          out.write(line)
     else:
          if line.find('BoundingBox: 0 0 612 792') != -1:
               out.write("%%BoundingBox: 0 0 595 842\n")
               flag = True
          else:
               out.write(line)

try:
     po = os.popen("rm "+filename.split('.')[0]+'.d2up.ps.2')
except IOError:
     print "why not?"
     sys.exit()
po.close()

savings = (scalel+scaler)/2
print "Toner use: "+str(savings)



