import string
import getopt
import sys
import re
import os


try:
	xn = string.atoi (sys.argv[1])
	yn = string.atoi (sys.argv[2])
	f = sys.argv[3]
except:
	sys.stderr.write ("usage: python bcard.py XCOUNT YCOUNT CARD-PAGE.EPS")

fstr = open(f).read()
m = re.search ('%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)',
	       fstr)

bbox = tuple (map (string.atoi, m.groups ()))
(llx, lly, urx, ury) = bbox

o = open ('cards.ps' , 'w')

o.write ('45 45
translate\n')

cardh = (ury - lly )
h = cardh * yn
cardw = urx - llx 
w = cardw * xn

crop_off = 5
crop_len = 10

o.write ('''0.1 setlinewidth
%% <CROPLEN> <OFF> <Y-coord> <W> vcrop
/hcrop
{ /w exch def
  /y exch def
  /off exch def
  /croplen exch def
  off neg y moveto
  croplen neg 0 rlineto
  w y moveto
  off 0 rmoveto
  croplen 0 rlineto
  stroke
} def
%% <CROPLEN> <OFF> <X-coord> <H> vcrop
/vcrop
{ /h exch def
  /x exch def
  /off exch def
  /croplen exch def
  x off neg moveto
  0 croplen neg rlineto
  x h moveto
  0 off rmoveto
  0 croplen rlineto
  stroke
} def
''')

for x in range (0, xn + 1):
	o.write (' %f %f %d %d vcrop \n' % (crop_len, crop_off,
					    cardw * x, h)) 
for y in range (0, yn + 1):
	o.write (' %f %f %d %d hcrop \n' % (crop_len, crop_off,
					    cardh * y, w)) 
			
for x in range (0,xn):
	for y in range (0,yn):
		o.write ('save %d %d translate\n' % (x * urx, y * ury))
		o.write ('/showpage { } def\n') 
		o.write ('0 0 moveto\n')
		o.write (fstr)
		o.write ('restore\n')

