#!/usr/bin/perl

# Peter Nermander <m8130@abc.se>, May 2004

# Small script to generate a PostScript file
# to use as a dummy for for example impositions

# Each page will have a box drawn on it and a large
# page number.

# Tried to make it DSC compliant...

sub usage {
    print <<EOHELP;
Usage:
mkpsfile [-m <margin>] <numpages> [<pagesize>]

where
<margin>    is the margin for the box drawn around each page
            (default is 20 points)
<numpages>  is the number of pages to print
<pagesize>  is either a defined page size (e.g. A4, letter etc)
            or the word "custom" followed by width and height
EOHELP
};

# Check switches (mainly look for -m)
while($_=$ARGV[0],/^-/) {
    shift;

    /^-h/ && do {usage; exit;};
    /^-\?/ && do {usage; exit;};
    /^-m/ && do {$margin=shift; next;};

    die "Unknown option $_!\n";
}

# No argument, let's help the user
$pages= shift or do {usage; exit;};

# See of there is a pagesize or assume A4
$size=shift or do {
    $size="A4"; # Default page size
};

if ($size) {
    $size =~ /^[Aa]4/ && do { $pw=595; $ph=842; };
    $size =~ /^[Aa]5/ && do { $pw=420; $ph=595; };
    $size =~ /^[Aa]6/ && do { $pw=298; $ph=420;};
    $size =~ /^[Aa]7/ && do { $pw=210; $ph=298;};
    $size =~ /^[Aa]8/ && do { $pw=147; $ph=210;};

    $size =~ /^letter/ && do { $pw=612; $ph=792;};
    $size =~ /^legal/ && do { $pw=612; $ph=1008;};
# More sizes can be inserted here


# Custom pagesize
    $size =~ /[cC][uU][sS][tT][oO][mM]/ && do {
	$pw=shift or die "Missing width and height for custom pagesize\n"; 
	$ph=shift or die "Missing height for custom pagesize\n";
    };
    ($ph & $pw) or die "Unknown pagesize\n";
};

# Default margin
$margin=20 unless $margin;

# Make text about one sixth of page height
$texth=int($ph/6);


# Print the file header
print <<EOF;
%!PS-Adobe-3.0
%%Title: Testfile $pages pages
%%BoundingBox: 0 0 $pw $ph
%%Pages: $pages
%%EndComments
%%BeginSetup
%%EndSetup
EOF

# Have removed %%PaperSize: from above
# Check if it takes points instead of paper name

# Corners for the box
$x0=$margin;
$y0=$margin;
$x1=$pw-$margin;
$y1=$margin;
$x2=$pw-$margin;
$y2=$ph-$margin;
$x3=$margin;
$y3=$ph-$margin;

# Location of page number
$textx=int($pw/2);
$texty=int($ph/5);

# Do the pages
for ($page=1; $page <= $pages; $page++) {

# Insert %%Page comment, draw box and print page number
print <<EOF;
%%Page: $page $page
1 setlinewidth
$x0 $y0 moveto
$x1 $y1 lineto
$x2 $y2 lineto
$x3 $y3 lineto
$x0 $y0 lineto
stroke

/Helvetica findfont
$texth scalefont
setfont
newpath
$textx $texty moveto
($page) show
showpage
EOF
}

# Insert %%EOF comment to indicate end of file
print "%%EOF\n";

