#!/usr/bin/perl
#
# Print labels suitable for DLT cartridges in an
# ATL library.  Outputs a Postscript file.
#
# Note that the label size is embedded in the Postscript
# function below, so there didn't seem much point in making
# constants for the perl side of things, as you'd need to
# rewrite everything if the label size (not style) changed.
#
# Also note that this program assumes A4 or Letter paper.
#
# Ian Chard  29/4/03
#

$BARCODE_FONT="code39.ps";
$MARGIN=20;			# margin in mm


if(scalar @ARGV==2)
{
	$start=$end=$ARGV[1];
}
elsif(scalar @ARGV==3)
{
	$start=$ARGV[1];
	$end=$ARGV[2];
}
else
{
	print STDERR "usage: $0 <label prefix> <first number> [<last number>]\n";
	print STDERR "e.g.   $0 AMI 100 200\n";
	print STDERR "And don't forget to pipe the output to lp\n";
	exit 1;
}

$prefix=$ARGV[0];

if($end<$start)
{
	print STDERR "$0: $end is less than $start\n";
	exit 1;
}

#
# Print Postscript header and barcode font.
#

die "can't open $BARCODE_FONT" if(! -f $BARCODE_FONT);
print "%!\n";
system("cat $BARCODE_FONT");

#
# Print the tapelabel definition which we'll call later.
#

print '
/mm {2.83464576 mul} bind def
/label {/Helvetica-Bold findfont 16 scalefont setfont} bind def
/barcode {/Code39 findfont 16 scalefont setfont} bind def

% tapelabel takes 5 operands:
%   9  tape label
%   8  \
%   7  |
%   6  | tape
%   5  | label
%   4  |
%   3  /
%   2  x coordinate
%   1  y coordinate

/tapelabel {
	gsave
	translate

	newpath
	0 0 moveto
	56 mm 0 rlineto
	0 20 mm rlineto
	-56 mm 0 rlineto
	closepath
	stroke

	0.8 mm setlinewidth
	0 2 mm moveto 56 mm 2 mm lineto stroke
	0 6 mm moveto 56 mm 6 mm lineto stroke
	0 14 mm moveto 56 mm 14 mm lineto stroke

	label

	0 1 5 {
		9 mm mul 3 mm add 15 mm moveto show
	} for

	barcode
	5 mm 6 mm moveto dup show
	5 mm 9 mm moveto dup show
	5 mm 10.4 mm moveto show

	grestore
} bind def
';

for($i=$start, $col=$row=0; $i<=$end; $i++)
{
	$label=uc sprintf "%s%-03.3d", $prefix, $i;
	@l=split /(.)/, $label;

	print "(*$label*) ($l[11]) ($l[9]) ($l[7]) ($l[5]) ($l[3]) ($l[1]) ";
	print "$col 56 mm mul $MARGIN add $row 20.5 mm mul $MARGIN add ";
	print "tapelabel\n";

	if(++$row>12)
	{
		$row=0;

		if(++$col>2)
		{
			$col=0;
			print "showpage\n";
		}
	}
}

print "showpage\n" if(!($row==0 && $col==0));

