#! /usr/bin/perl

# combine multiple CrossPad pages into one MetaPost figure with
# multiple colors.

# Copyright 1997,1998 by Jun-ichiro Itoh (original crosspad2ps script)
# Copyright 2003 by Sanjoy Mahajan <sanjoy@mrao.cam.ac.uk>
# Licensed under the GNU GPL

# History:
#    Jan 2003: Rewritten by Sanjoy Mahajan to produce MetaPost output
#  Thu 1/7/04: New options included by David MacKay:
#               -gap
#                 Omission of some points, to make lines smoother.
#               -join      To change the joining symbol from ".." to, say, "--"
#
#  Tue 6/7/04: New feature 'seekcusps' added, which alters the points
#              omitted by -gap if it thinks a cusp has been lost.
#              Allows larger -gap (eg 5) to be used.
#
#  Landscape feature added.  -l
#

sub help {
    print << "EOF";
USAGE:
  Suppose you want to make a figure with two colors, say green for
  the lines and red for the text labels.  On the CrossPad, draw the
  lines on page 1, then switch to page 2 and draw the labels.
  Upload the CrossPad data (using 'padload') to, say, fig.cpd.
  Convert this to a MetaPost figure with:
 
    cpd2mp -c=green:red fig.cpd > fig.mp
 
  'fig.mp' will be a single MetaPost figure with the material from
  p.1 drawn in green and the material from p.2 drawn in red.  To
  generate the EPS file 'fig.1':
  
    mpost fig.mp
 
  Less important details:
 
    If you have three colors, make three CrossPad pages, upload,
    then:
 
      cpd2mp -c black:green:red fig3.cpd > fig3.mp

    assuming fig3.cpd is the uploaded data file.  The default set of
    colors is "black:0.7red:0.5blue:0.7green", and those four colors
    are cycled through in that order, one per page (so if you
    generated five pages, the fifth page's material would show up in
    black).  You can select any number of colors with the -c switch.
    Specify the colors using MetaPost's ordered triple format
    (r,g,b) or the shorthands black, white, red, green, or blue.
    The notation "0.7red" is also legal and means what you might
    expect: (0.7,0,0).

    To change the linewidth, use the -w switch:
      cpd2mp -w 2mm fig.cpd > fig.mp

    If no dimension is specified, postscript points ('bp' to
    MetaPost) are assumed.  The default width is 0.7mm (roughly
    2bp), to match a 'fine' rollerball pen ('extra fine' is 0.5mm I
    think).

    In the MetaPost code, the coordinates are given in bp (big
    points, or PostScript points, which are 72dpi) and then the
    figure is scaled to match the size on the CrossPad, which
    reports positions in pixels of 1/254th of an inch (hence the
    72/254 scale factor at the end of the generated MetaPost code).

    What if you upload many figures into one crosspad data file?
    For example, suppose pages 1-3 are the three colors for figure
    1, and pages 4-5 are the two colors for figure 2.  Then use the
    -s and -e switches:

      cpd2mp -s 1 -e 3 mult.cpd > fig1.mp
      cpd2mp -s 4 -e 5 mult.cpd > fig2.mp

   You can also combine the two figures into one metapost file using
   the --omitend and --figurenumber switches (which of course can be
   abbreviated to -o and -f).  -o tells the program not to output
   the final 'end' that finishes a metapost file.  '-f=2' or '-f 2'
   tells metapost to generate the figure as fig.2 (using
   'beginfig(2)' in the metapost file).  The default figure number
   is 1.  So:

      cpd2mp -s 1 -e 3 -o mult.cpd > fig.mp
      cpd2mp -s 4 -e 5 -f 2 mult.cpd >> fig.mp

   will produce 'fig.mp', which will produce fig.1 (from pages 1-3)
   and fig.2 (from pages 4-5).  DON'T forget to use >> instead of > !

   The 'gap' option omits points from the lines so as to reduce
   pixellation artefacts. If gap>0, its value specifies the Euclidean
   distance that must be moved for the next point on a curve to be included.

      cpd2mp -g 3 > fig.mp

   The 'join' option lets you change the joining symbol between points from
   ".." to say "..tension 3.." or "..." or "--".

      cpd2mp -j "--" 

   To select landscape or upsidedown landscape, use the option --landscape:

      cpd2mp -l 90
   or
      cpd2mp -l 270

   Two advantages to using metapost as an intermediate format
   (rather then generating EPS directly):

     1.  MetaPost calculates the correct bounding box, including the
         pen width.
     2.  In MetaPost splines are easily specified, using the
         .. connector whereas in EPS you have to figure out the
         control points yourself.  And a spline makes a nice smooth
         path (mostly).
EOF
}

use Getopt::Long;

#
# initialize variables
#
$date = `date`;
$date =~ s/\n$//;
$reportto = 'sanjoy@mrao.cam.ac.uk';
$debug = 0;
($startpage, $endpage) = (1, 99999);
$pageoutput = 0;
($xoffset, $yoffset) = (0, 0);
($xscale, $yscale) = (1, 1);
$tmpdir = '/tmp/' . $$ . '.' . time;

$landscape = 0 ; # whether to rotate, and by how much
$omitend = 0;
$gap=0;  # gap required between successive points on a line.
$join="..";  # symbol between points on a curve
$seekcusps = 1 ; # whether to look for cusps that are lost by the "gap" feature and restore them.
$border = 0;
$papersize = 'letter';		# other choices are '6x9', 'a4', 'a5';
%paperdimen = ('letter' => '(8.5in,11in)',
	       '6x9' => '(6in,9in)',
	       'a4' => '(210mm,297mm)',
	       'a5' => '(148.5mm,210mm)');
$pslinewidth = '0.7mm';		# like a 'fine' (in size) rollerball pen
$purge = 1;
$colorlist = 'black:0.7red:0.5blue:0.7green';
$fignum = 1;

$progname = $0;
$progname =~ s/\.pl$//;
$progname =~ s/^.*\///;

$huffman{'110101011111001'} = -16;
$huffman{'110101011110'} = -15;
$huffman{'1100100100'} = -14;
$huffman{'110010011'} = -13;
$huffman{'110101010'} = -12;
$huffman{'11010100'} = -11;
$huffman{'1000100'} = -10;
$huffman{'1010011'} = -9;
$huffman{'1101011'} = -8;
$huffman{'101000'} = -7;
$huffman{'110011'} = -6;
$huffman{'10000'} = -5;
$huffman{'11000'} = -4;
$huffman{'11011'} = -3;
$huffman{'1011'} = -2;
$huffman{'010'} = -1;
$huffman{'00'} = 0;
$huffman{'011'} = 1;
$huffman{'1001'} = 2;
$huffman{'10101'} = 3;
$huffman{'110100'} = 4;
$huffman{'100011'} = 5;
$huffman{'1100101'} = 6;
$huffman{'1010010'} = 7;
$huffman{'11001000'} = 8;
$huffman{'10001010'} = 9;
$huffman{'100010111'} = 10;
$huffman{'100010110'} = 11;
$huffman{'1100100101'} = 12;
$huffman{'11010101110'} = 13;
$huffman{'11010101100'} = 14;
$huffman{'11010101101'} = 15;
$huffman{'1101010111111'} = 16;
$huffman{'11010101111101'} = 18;

# long form covers signed 8bit values
# slow version...
#for ($i = -128; $i < 128; $i++) {
#	$t = unpack('B*', pack('C', $i));
#	$huffman{'110101011111000' . $t} = $i + 5;
#	print '110101011111000' . $t . "=";
#	print $i + 5 . "\n";
#}
$huffman{'110101011111000'} = -998;
# termination
$huffman{'1111111'} = -999;
#$huffman{'111111111111111'} = -999;

#
# parse arguments
#
GetOptions('colors=s' => \$colorlist,
	   'join=s' => \$join,
	   'gap=i' => \$gap,
	   'border' => \$border,
	   'landscape=i' => \$landscape,
	   'omitend' => \$omitend,
	   'width=s' => \$pslinewidth,
	   'debug+' => \$debug,
	   'startpage=i' => \$startpage,
	   'endpage=i' => \$endpage,
	   'page=i' => sub { local($name, $pagenum) = @_;
			     $startpage = $endpage = $pagenum;},
	   'figurenumber=i' => \$fignum,
	   'help' => sub { &help; exit 0; }) || &usage;

if (scalar(@ARGV) != 1) {
	&usage; exit 1;
}

@colors = split /:/ , $colorlist;

if ($pslinewidth =~ /^\d+$/) {	# if all digits (i.e. no units specified),
    $pslinewidth .= 'bp';	# default is PS points (Big Points to MP)
}

$filename = $ARGV[0];
if (! -f $filename) {
	print STDERR "$filename not found\n"; exit 1;
}
while (-e $tmpdir) {
    $tmpdir .= 'x';
}
mkdir($tmpdir, 0755) || die;
&pageinit(0);
&parse($filename);
&joinpages;
system "/bin/rm -fr $tmpdir" if ($purge);

exit 0;

sub pageinit {
	local($page) = @_;
	local($t);

	$currentcolor = $colors[($page-$startpage) % ($#colors + 1)];
	open(OUT, ">> $tmpdir/$page") || die;
	select(OUT);
}

sub pagefinish {
	close(OUT);
}

sub parse {
	local($file) = @_;
	local($buf, $l, $sl, $nl, $x, $y, $len, $vers, $code);
	local(@unknownlen);

	for ($i = 0; $i < 256; $i++) {
		$unknownlen[$i] = -1;
		$unknownstr[$i] = '';
	}
	$unknownlen[0x03] = 0x0b; $unknownstr[0x03] = 'keyword';
	$unknownlen[0x0e] = 0x07;
	$unknownlen[0x35] = 0x06;
	$unknownlen[0x36] = 0x06;
	$unknownlen[0x39] = 0x27;
	$unknownlen[0x3c] = 0x12;
	$unknownlen[0x3d] = 0x10;
	$unknownlen[0x3e] = 0x0a;

	open(IN, "< $file") || die;

	sysread(IN, $buf, 5) || die;
	if (substr($buf, 0, 3) ne pack('C3', 0x01, 0x00, 0xff)) {
		close(IN);
		open(IN, "< $file") || die;
		$len = (stat($file))[7];
	} else {
		# just for debugging...
		$len = (stat($file))[7] - 5;
	}
	print "% file \"$file\" data part length: $len\n" if ($debug);

	$l = 0;
	while ($l + 5 < $len) {
		sysread(IN, $buf, 5);
		($vers, $code) = unpack('N C', $buf);	# correct?
		printf("%% pos=%08x ver=%d code=0x%02x: ", $l, $vers, $code)
			if ($debug);
		if ($vers != 0) {
			print STDERR "unsupported file format version $vers\n";
			close(IN);
			&failure("unexpected input", 0);
		}

		if ($code == 0x06) {
			# original crosspad
			sysread(IN, $buf, $nl = 0x14);
			$t = unpack('x19 C', $buf);
			if ($debug) {
				&printdate(substr($buf, 0, 6));
				print "compress=$t\n";
			}

			# is this correct?
			if ($t == 1) {
				($xoffset, $yoffset) = (20, 22);
				($xscale, $yscale) = (1, 1);
			} elsif ($t == 2) {
				($xoffset, $yoffset) = (20, 2944);
				($xscale, $yscale) = (1, -1);
			}
		} elsif ($code == 0x1d) {
			# crosspad XP
			sysread(IN, $buf, $nl = 0x2b);
			if ($debug) {
				&printdate(substr($buf, 0, 6));
				print "compress=?\n";
			}

			# is this correct?
			# handcrafted offset value, need suggestions
			($xoffset, $yoffset) = (40, 3030);
			($xscale, $yscale) = (1, -1);
			$papersize = '6x9'; # could be 'a5'
		} elsif ($code == 0x0d || $code == 0x0a) {
			sysread(IN, $buf, $nl = 0x0e);
			$t = substr($buf, 6, 8);
			$t =~ s/\000//g;
			if ($debug) {
				&printdate(substr($buf, 0, 6));
				print "\"$t\"\n";
			}
		} elsif ($code == 0x04) {
			sysread(IN, $buf, $nl = 10);
			$t = unpack('x6 N', $buf);
			if ($debug) {
				&printdate(substr($buf, 0, 6));
				print "switch to page $t\n";
			}

			&pagefinish;
			&pageinit($t);
			$pageoutput = 1;
		} elsif ($code == 0x01 || $code == 0x02) {
			sysread(IN, $buf, 12);
			($sl, $x, $y) = unpack('x6 n3', $buf);
			if ($debug) {
				&printdate(substr($buf, 0, 6));
				if ($code == 0x01) {
					print "stroke: ";
				} else {
					print "NEW stroke: ";
				}
				print "len=$sl start=($x, $y)\n";
			}

			sysread(IN, $buf, $sl - 4);
			if ($pageoutput) {
				($curx, $cury) = ($x - $xoffset, $y - $yoffset);
				$curx *= $xscale;
				$cury *= $yscale;
				printf("draw ((0,0)\n");
				($firstx, $firsty) = ($curx, $cury);
				&printstroke($buf);
			}

			$nl = 12 + length($buf);
		} elsif ($code == 0x05) {
			# clock adjust
			sysread(IN, $buf, $nl = 0x0c);
			if ($debug) {
				&printdate(substr($buf, 0, 6));
				print "clock adjusted at ";
				&printdate(substr($buf, 6, 6));
				print "\n";
			}
		} elsif ($code == 0x37) {
			sysread(IN, $buf, $nl = 6);
			if ($debug) {
				&printdate(substr($buf, 0, 6));
				print "page bookmark\n";
			}
		} elsif ($code == 0x3a) {
			sysread(IN, $buf, $nl = 6);
			if ($debug) {
				&printdate(substr($buf, 0, 6));
				print "is last download time\n";
			}
		} elsif (0 <= $unknownlen[$code]) {
			sysread(IN, $buf, $nl = $unknownlen[$code]);
			if ($debug == 1) {
				&printdate(substr($buf, 0, 6));
				print $unknownstr[$code] . "???\n";
			} elsif (1 < $debug) {
				&printdate(substr($buf, 0, 6));
				print $unknownstr[$code] . "???: ";
				for ($i = 6; $i < length($buf); $i++) {
					printf("%02x ", unpack('C',
						substr($buf, $i, 1)));
				}
				print "\n";
			}
		} else {
			printf("unknown code %02x\n", $code);
			die;
		}
		$l += 5;
		$l += $nl;
	}
	&pagefinish;
	close(IN);
}

sub printdate {
	local($datebcd) = @_;
	local(@t);
  
	@t = unpack('C6', $datebcd);
	printf("%02x/%02x/%02x %02x:%02x:%02x  ",
		$t[0], $t[1], $t[2], $t[3], $t[4], $t[5]);
}

# context for this command being invoked: 
#				printf("draw ((0,0)\n");
#				($firstx, $firsty) = ($curx, $cury);
#				&printstroke($buf);

sub printstroke {
	local($stroke) = @_;
	local($r, $trailer, $v);
	local(@t);
	local($i);
	local($maxbits);
	local($cnt);
	local($npoints0, $npoints);
	local($xx)=0; # added DJCM Thu 1/7/04
	local($yy)=0; # added DJCM Thu 1/7/04
	local($px)=0; # added DJCM Thu 1/7/04
	local($py)=0; # added DJCM Thu 1/7/04
	local($buffer)=""; # added DJCM  Tue 6/7/04  to allow retrospective uncommenting of turning points
	local($dx)=0; # added DJCM Tue 6/7/04
	local($dy)=0; # added DJCM Tue 6/7/04
	local($ex)=0; # added DJCM Tue 6/7/04
	local($ey)=0; # added DJCM Tue 6/7/04
	local($bufferfull)=0;

	$maxbits = -1;
	$r = '';
	$trailer = substr($stroke, index($stroke, pack('C2', 0xff, 0xff)));
	$npoints0 = $npoints = unpack('x2 n', $trailer);
	print "% npoints=$npoints0\n" if ($debug);

	$r = unpack('B*', $stroke);
	$r =~ s/\s+//g;
	@t = sort {length($b) <=> length($a)} (keys %huffman);
	$cnt = 0;
	$npoints *= 2;
	while (2 < $npoints && length($r)) {
		foreach $i (@t) {
			if (substr($r, 0, length($i)) eq $i) {
				$m = $i;
				last;
			}
		}

		if ($huffman{$m} == -999) {
			print "% huffman code length mismatch? "
				. "seen temrination. npoints=$npoints0\n"
				if ($debug);
			last;
		} elsif ($huffman{$m} == -998) {
			$v = unpack('c', pack('B*', substr($r, length($m), 8)));
			$m .= substr($r, length($m), 8);
		} elsif (length($m) && substr($r, 0, length($m)) eq $m) {
			$v = $huffman{$m};
		} else {
			&failure("unknown huffman code ". substr($r, 0, 10), 1);
				
			print STDERR "please contact $reportto so that "
				. "the tool can be more perfect.\n";
			&maildocument(substr($r, 0, 10));
			exit 1;

#			print ' unknown(' . ($cnt % 2 ? 'y' : 'x') . ':' . $r. ')';
#			last;
		}

		if ($cnt % 2 == 0) {
			$v = $v * $xscale + 5;
			$curx += ($v - 5);
		} else {
			$v = $v * $yscale + 5;
			$cury += ($v - 5);
			$xx = $curx-$firstx; $yy = $cury-$firsty ;
			if( $bufferfull ) {
			    if ( $seekcusps ) {
				# consider the last point, which is commented out,
				# and decide whether to reinstate it
				$ex = $xx - $lostx ; 
				$ey = $yy - $losty ; 
				if( ($dx*$ex + $dy*$ey) < 0.0 ) { # then a significant change in direction has taken place
				    $buffer =~ s/\%// ;
				    $px = $lostx ; $py = $losty ;
				    print STDERR "restored cusp!\n" if(0) ;
				}
				# now print the buffer and move on.
			    }
			    print $buffer ;
			    $bufferfull = 0 ;
			}
			$buffer="" ;
			$printit =  0; 
			if(($gap<=0)||($npoints-1<=2)) {
			    # default: show all points; and always show the last in the line.
			    $printit =  1; 
			} else {
			    # consider whether to comment out this point.
			    if( ( ($xx-$px)**2 +  ($yy-$py)**2 ) >= $gap**2 ) {
				# then let the point through.
				$px=$xx; $py=$yy ;
				$printit =  1; 
			    } else {
				# comment it out
				$buffer .= '%' ;
				$lostx = $xx ; $losty = $yy ; # keep track in case we want to reinstate this point
				$dx = $xx-$px ; $dy = $yy-$py ;
			    }
			}
			$buffer .= sprintf("$join(%d,%d)\n",
					   $xx, $yy);
			if( $printit ) {
			    print $buffer ;
			    $bufferfull = 0 ;
			} else {
			    $bufferfull = 1 ; 
			}
		}
		$r = substr($r, length($m));
		$cnt++;
		$npoints--;
	}
	if( $bufferfull ) {
	    print STDERR "unexpected print buffer nonempty\n" ; # DJCM  Tue 6/7/04
	    print $buffer ;
	    $bufferfull = 0 ;
	}
	print "  ) shifted ($firstx, $firsty) scaled 1bp\n  withcolor $currentcolor;\n";
	print "\n";
}

sub usage {
	print STDERR << "EOF";
usage: $progname [-help] [-debug] [-startpage #] [-endpage #] [-join string]
                 [-page #] [-colors color1:color2...] [-w linewidth] [-gap #] filename
Options may be abbreviated to shortest unique name (usually single letters)
Try '$progname -help' for detailed help
EOF
       exit 1;
}

sub failure {
	local($msg, $mailit) = @_;
	print STDERR "FATAL: $msg\n";
	if ($mailit) {
	    print "contact $reportto for help improving the program.\n";
	}
	exit 1;
}

sub maildocument {
	local($unknownhuff) = @_;
	print STDERR <<EOF
NOTE: automatic emailing function is not implemented yet...
transmit $filename to $reportto, uuencoded.
EOF
}

sub joinpages {
	local($t, $i, $n);
	local(@t);

	die if (! -f "$tmpdir/$startpage");

	select STDOUT;
	print <<EOF;
%CreationDate: $date
%Creator: cpd2mp
%Title: $filename

prologues := 2;

beginfig($fignum)
pickup pencircle scaled ($pslinewidth * 254/72);
EOF

	opendir(DIR, $tmpdir) || die;
	@t = grep(/^\d+$/, readdir(DIR));
	closedir(DIR);
	$n = 0;
	foreach $i (sort {$a <=> $b} @t) {
		next if ($i < $startpage || $endpage < $i);

		$n++;
		print "%Page: $n\n" if (1 || $debug);
		open(IN, "< $tmpdir/$i") || die;
		while (<IN>) {
			print;
		}
		close(IN);
	}

	print <<EOF;
% CrossPad outputs y-negated coordinates, hence the 'yscaled -1'
% It also uses a 254dpi coordinate system, whereas postscript
% points are 72dpi
currentpicture := currentpicture scaled (72/254) yscaled -1;
EOF
    if ($border) {
	print << "EOF";
% shift figure so that center is at origin
currentpicture := currentpicture shifted -(center currentpicture);
pickup pensquare scaled 0.5bp;
z0 = origin;
z1 = $paperdimen{$papersize};
z2 = 0.5(0.5bp,0.5bp);
z3 = z0 + z2;
z4 = z1 - z2;

draw (z3--(x4,y3)--z4--(x3,y4)--z3--cycle) shifted -0.5[z3,z4];
EOF
    }
	if($landscape) {
	    if($landscape eq "1") {
		$landscape = 90 ;
	    }
	    print "\n%% rotate figure through angle landscape\n";
	    print "currentpicture := currentpicture rotated $landscape ;\n" ; 
	}
    print << "EOF";
% shift figure so that lower left is at origin
currentpicture := currentpicture shifted -(llcorner currentpicture);
endfig;
EOF
    if (!$omitend) {
	print "\nend";
    }
    print "\n";
}
