#!/usr/local/bin/perl

$width = 312;                   # 6.5i with 18pt bars (versitec)
$script_name = ARGV[0];         # save script name

while ($_ = $ARGV[0], /^-/) {
	shift;
    last if /^--$/;
	/^-w/ && do {           # specify output file
		die "$script_name: no arg for -w"
			unless ($ARGV[0]);
		die "$script_name: -w arg not numeric"
			unless ($ARGV[0] =~ /\d+/);
		$width = shift;
		next; };
	/^-t/ && do {           # specify bytes tabs on barcode lines
		++$tags;
		next; };
	#default
	die "$script_name: unknown flag $_";
}

@bpn = (0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4); # bits in a nibble

while (<>) {
	chop;
	$line = $_;
	/^title\s*(.*)$/ && do {        # title line
		print '.Tl "'.$1.'"\n';
		next; };
	/^program(\s+private)?\s+(.*)$/ && do { # process program
		do program($1,$2);
		next; };
	/^data\s+'([^']*)'\s*(.*)$/ && do { # numeric data
		do data($1,$2);
		next; };
	/^string(\s+append)?\s*(.*)$/ && do { # string data
		($append,$text) = ($1,$2);
		$_ = <>;
		die "$script_name: illformed data line at line $.\n"
			unless (/^\d+(\s+\d+)*$/);
		@byt = split;
		unshift(@byt,($append?128:112)+$#byt+1);
		do checksum(0);
		do dumpbar($text,@byt);
		next; };
	/^bytes(\schecksum)?\s*(.*)$/ && do { # generic barcode data
		($checksum,$text) = ($1,$2);
		$_ = <>;
		die "$script_name: illformed data line at line $.\n"
			unless (/^\d+(\s+\d+)*$/);
		@byt = split;
		do checksum(0) if $checksum;
		do dumpbar($text,@byt);
		next; };
	#default
	die "$script_name: no directive at line $.\n";
}
exit 0;

#
# end of main routine
#

sub pad {
	sprintf("%03d",pop(@_));        # pad number to 3 digits with zeros
}

sub checksum {                          # compute checksum with arg
	local($run) = @_;               # being running value and @byt
	local($i);                      # being the array of bytes then
	for $i (@byt) {                 # stuff check sum on front of byt
		$run = $run + $i;
		$run -= 255 if $run > 255;
	}                               # checksum is sum mod 265 with end
					# around carry
	unshift(@byt,do pad($run));
}

sub dumpbar {
	local($i);
	print '.Sb "'.shift(@_)."\"\n"; # start bar code line
	for $i (@_) {
		print ".By ".do pad($i)."\n"; # dump each byte
	}
	print ".Eb",(($tags)?" 1\n":"\n"); # end barcode line
}

sub bytw {                              # width of byt array in bars
	local($width,$i) = (9,0);       # start and stop bar overhead
	for $i (@byt) {
		$width += (16 + $bpn[int($byte/16)] + $bpn[$byte%16]);
	}                               # narrow bar = 2, wide bar = 3
	return $width;
}

sub program {
	local($private,$text) = @_;
	print '.Pg "'.$text."\"\n";     # dump prog name
	@values = ();                   # bytes of code
	@inst_num = ();                 # 41c instruction numbers
	@f_orphs = ();                  # leading orphan bytes
	@b_orphs = ();                  # trailing orphan bytes
	$inst_cnt = 0;
	until ($_=<>,/^end/) {          # read in all of the program
		++$inst_cnt;            # labeling each byte with
		@byt = split;           # instruction number,
		$b_orph = 0;            # leading and trailing
		$f_orph = $#byt+2;      # orphan counts
		for $_ (@byt) {
			push(@value,$_);
			push(@inst_num,$inst_cnt);
			push(@b_orphs,((++$b_orph>$#byt)?0:$b_orph));
			push(@f_orphs,(($f_orph-->$#byt+1)?0:$f_orph));
		}
	}
	$seq_num = 0;                   # sequence numbers
	$running = 0;                   # initial running checksum
	$line_num = 1;                  # number of barcode lines
	while($#value+1) {
		$trial_length = ($#value < 12 ? $#value : 12);
					# assume full line 13 bytes
		$i = $#value;           # save length
		$#value = $trial_length; # pretend that value is that long
		@byt = @value;          # copy the front off
		$#value = $1;           # set length back
	    loop: {
		    unshift(@byt, $seq_num+16*($private?2:1),
					# add seq number and prog type ...
			$f_orphs[0]*16+$b_orphs[$trial_length]);
					# ... and orphan counts
		    do checksum($running);
					# compute checksum
		    if (do bytw() > $width) {   # line to wide shorten by 1
			shift(@byt),shift(@byt),shift(@byt);
					# remove front stuff
			pop(@byt);      # drop last byte
			--$trial_length;
			redo loop;      # and go put on new front stuff
		    }
		}
		$text = sprintf("Line %d (%d - %d)",$line_num++,
		    $inst_num[0],$inst_num[$trial_length]);
					# barcode line label
		do dumpbar($text,@byt); # generate *roff output
		$running = shift(@byt); # save running checksum
		for ($i=0; $i<$trial_length; ++$i) {
		    shift(@value);      # remove this barcode lines
		    shift(@inst_num);   # bytes and labels
		    shift(@f_orphs);    # fron arrays
		    shift(@b_orphs);
		}
		$seq_num = ($seq_num==15?0:++$seqnum);
	}                               # inc seq num mod 16
}

sub data {
	local($_,$text) = @_;
	@digits = split(/.*/);          # split into single chars
	@nibbles = ();
	for $_ (@digits) {              # build nibble array
		/\d/ && (push(@nibbles,$_),next);
		/\./ && (push(@nibbles,11),next);
		/\+/ && (push(@nibbles,12),next);
		/-/  && (push(@nibbles,13),next);
		/[eE]/ && (push(@nibbles,14),next);
		/./  &&
		     die "$script_name: illformed numeric data at line $.\n";
	}
	push(@nibbles,10)    if ($#nibbles % 2);  # make number nibbles even
	push(@nibbles,10,10) if ($#nibbles == 1); # must have at least 2 bytes
	@byt = (96+shift(@nibbles));              # generate header
	while ($#nibbles > 0) {
		$_ = shift(@nibbles);             # combine nibbles into bytes
		push(@byt,16*$_+shift(@nibbles));
	}
	do checksum(0);
	do dumpbar($text,@byt);         # dump barcode line
}
