chiark / gitweb /
87d5c66c33aed1f488b80056642c4a9c97cf611b
[trains.git] / layout / layout
1 #!/usr/bin/perl -w
2
3 use POSIX;
4 use IO::Handle;
5 use IO::File;
6
7 use strict;
8 no strict 'subs';
9
10 our $file_lineno= 0;
11 our $file_filename;
12
13 our $scale= 7.0;
14 our $page_x= 0;
15 our $page_y= 0;
16 our $quiet=0;
17 our $debug=0;
18 our $output_layer= '*';
19 our $subsegcmapreq=0;
20 our $subsegmovfeatpos='f';
21 our $subsegcmapangscale;
22
23 our $ps_page_shift= 615;
24 our $ps_page_xmul= 765.354;
25 our $ps_page_ymul= 538.583;
26
27 our @eopts;
28 our @segments= ('/');
29 our @ident_strings= ();
30 our %subsegcmap;
31 our %segcmap;
32
33 our $drawers= 'arqscldmnoge';
34 our %chdraw_emap= qw(A ARScgd
35                      R aRscgD
36                      S aRScgd
37                      C arsCgd
38                      c Arscgd
39                      r arcs
40                      L LMg
41                      l l
42                      D D
43                      d d
44                      M Mnog
45                      N MNog
46                      O MNOg
47                      m mnol
48                      G Garsclmno);
49
50 while (@ARGV && $ARGV[0] =~ m/^\-/) {
51     last if $ARGV[0] eq '-';
52     $_= shift @ARGV;
53     last if $_ eq '--';
54     s/^\-//;
55     while (length) {
56         if (s/^D(\d+)//) { $debug= $1; }
57         elsif (s/^D//) { $debug++; }
58         elsif (s/^q//) { $quiet=1; }
59         elsif (s/^l(\d+|\*)//) { $output_layer=$1; }
60         elsif (s/^S([0-9.]+)$//) { $scale= $1 * 1.0; }
61         elsif (s/^P(\d+)x(\d+)$//) { $page_x= $1; $page_y= $2; }
62         elsif (s/^GR//) { $subsegcmapreq=1; }
63         elsif (s/^GP(\d+|f)$//) { $subsegmovfeatpos=$1; }
64         elsif (s/^GL(.*)$//) {
65             my ($sscmfn) = $1;
66             my ($sscmf, $datum, $csss, $angbits);
67             local ($_);
68             $sscmf= new IO::File $sscmfn, 'r'
69                 or die "$sscmfn: cannot open: $!\n";
70             for (;;) {
71                 $!=0; $_= <$sscmf>; die $! unless defined $_;
72                 last if m/^E/;
73                 next unless m/^C/;
74                 m,^C\s+(\w*/(?:[A-Za-z_]+)?)\s+(0x[0-9a-f]+)\s+(\d+)\s*$,
75                     or die "$sscmfn:$.: syntax error in subseg cmap\n";
76                 ($csss,$datum,$angbits)= ($1,$2,$3);
77                 if (!defined $subsegcmapangscale) {
78                     $subsegcmapangscale= 1<<$angbits;
79                 } else {
80                     die "angbits varies" if $subsegcmapangscale != 1<<$angbits;
81                 }
82                 $datum= hex($datum);
83                 if ($datum & 0x0ff) {
84                     die "sorry, cannot put any movfeatpos or segment in red";
85                 }
86                 $subsegcmap{$csss}= sprintf("%.6f %.6f",
87                                             (($datum >> 8) & 0xff)/255.0,
88                                             (($datum >> 16) & 0xff)/255.0);
89             }
90             $sscmf->error and die "$sscmfn: error reading: $!\n";
91             close $sscmf;
92         } elsif (s/^(e)
93                ((?:[a-z]|\*|\?|\[[a-z][-a-z]*\])*?)
94                (\~?) (\d*) (\=*|\-+|\++) (\d*|\*)
95                ([a-z]+)$//ix) {
96             my ($ee,$g,$n,$d,$c,$v,$cc) = ($1,$2,$3,$4,$5,$6,$7);
97             my ($eo, $invert, $lfn, $ccc, $sense,$limit);
98             $g =~ s/\?/\./g; $g =~ s/\*/\.\*/g;
99             die '-[eE]GND[=]* not allowed' if $v eq '*' && length $d;
100             $d= $output_layer if !length $d;
101             $d= 5 if $d eq '*';
102             $invert= length $n;
103             $c= '=' if !length $c;
104             if (length $v && $v ne '*') {
105                 die '-[eE]GN[D]CCV not allowed' if length $c > 1;
106                 $c= $c x $v;
107             }
108             if ($c =~ m/^[-+]/) {
109                 die '-[eE]GN+/-* not allowed' if $v eq '*';
110                 $sense= ($&.'1') + 0;
111                 $limit= ($sense * $d) + length($c) - 1;
112                 $lfn= sub {
113                     ($output_layer eq '*' ? $d
114                      : $_[0]) * $sense >= $limit
115                          xor $invert;
116                 };
117             } elsif ($v eq '*') {
118                 $lfn= sub { !$invert; };
119             } else {
120                 $limit= length($c) - 1;
121                 $lfn= sub {
122 #my ($lfn_result)=(
123                     ($output_layer eq '*' ? 1
124                      : abs($_[0] - $d) <= $limit)
125                         xor $invert
126 #)
127                             ;
128 #print STDERR "output layer $output_layer; asking re $_[0] rel $d lim $limit invert $invert result $lfn_result\n";
129 #$lfn_result;
130                 };
131             }
132             $ccc= '';
133             foreach $c (split //, $cc) {
134                 if ($ee eq 'e') {
135                     die "bad -e option $c" unless defined $chdraw_emap{$c};
136                     $ccc .=  $chdraw_emap{$c};
137                 } else {
138                     die "bad -E option $c" unless $c =~ m/[$drawers]/i;
139                     $ccc .= $c;
140                 }
141             }
142             $eo->{GlobRe}= $g;
143             $eo->{LayerCheck}= $lfn;
144             $eo->{DrawMods}= $ccc;
145 #print STDERR "created eo $eo re $eo->{GlobRe} n=$n d=$d v=$v c=$c limit=$limit cc=$cc\n";
146             push @eopts, $eo;
147         } elsif (m/^S/) {
148             die "-S option must come right at the start and have numeric arg";
149         } else {
150             die "unknown option -$_";
151         }
152     }
153 }
154
155 our $ptscale= 72/25.4 / $scale;
156
157 our $psu_ulen= 4.5;
158 our $psu_edgelw= 0.5;
159 our $psu_ticklw= 0.1;
160 our $psu_ticksperu= 1;
161 our $psu_ticklen= 5.0;
162 our $psu_gauge= 9;
163 our $psu_sleeperlen= 17;
164 our $psu_sleeperlw= 15;
165 our $psu_raillw= 1.0;
166 our $psu_thinlw= 1.0;
167 our %psu_subseglw;
168
169 $psu_subseglw{'e'}= 20.0;
170 $psu_subseglw{'m'}= 15.0;
171 $psu_subseglw{'q'}= 20.0;
172 our $lmu_segtpt= 25;
173 our $lmu_segtxtoff= -8;
174
175 our $lmu_marklw= 4;
176 our $lmu_marktpt= 11;
177 our $lmu_txtboxtxty= $lmu_marktpt * 0.300;
178 our $lmu_txtboxh= $lmu_marktpt * 1.100;
179 our $lmu_txtboxpadx= $lmu_marktpt * 0.335;
180 our $lmu_txtboxoff= $lmu_marklw / 2;
181 our $lmu_txtboxlw= 1;
182 our $lmu_lenlabeloffctr= -$lmu_marklw * 1.0;
183 our $lmu_lenlabeloff=     $lmu_marklw * 0.5;
184
185 our $olu_left= 10 * $scale;
186 our $olu_right= 217 * $scale - $olu_left;
187 our $olu_bottom= 25 * $scale;
188 our $olu_top= 270 * $scale - $olu_bottom;
189 our $olu_gap_x= 30;
190 our $olu_gap_y= 60;
191 our $olu_textheight= 15;
192 our $olu_textallowperc= $lmu_marktpt * 5.0/11;
193
194 our $pi= atan2(0,-1);
195
196 sub allwidth2 ($) {
197     my ($radius)= @_;
198     return 27 unless defined $radius;
199     $radius= abs($radius);
200     return ($radius >= 450 ? 33 :
201             $radius >= 400 ? 35 :
202             37);
203 }
204 sub allwidth ($) { return allwidth2($_[0]) * 0.5; }
205
206 our $allwidthmax= allwidth(0);
207 our $allwidthmin= allwidth(undef);
208
209 # Data structures:
210 #  $ctx->{CmdLog}= undef                  } not in defobj
211 #  $ctx->{CmdLog}[]= [ command args ]     } in defobj
212 #  $ctx->{Parent}= $parent_ctx or undef
213 #  $ctx->{LocsMade}[]{Id}= $id
214 #  $ctx->{LocsMade}[]{Neg}= 1 or 0
215 #  $ctx->{Loc}{$id}{X}
216 #  $ctx->{Loc}{$id}{Y}
217 #  $ctx->{Loc}{$id}{A}
218 #  $ctx->{Loc}{$id}{LayerKind}
219 #  $ctx->{Trans}{X}       # transformation.  is ev representing
220 #  $ctx->{Trans}{Y}       # new origin.  (is applied at _input_
221 #  $ctx->{Trans}{A}       # not at plot-time)
222 #  $ctx->{Trans}{R}       # but multiply all y coords by this!
223 #  $ctx->{Draw}           # sequence of one or more chrs from uc $drawers
224 #                         #  possibly including X meaning never draw
225 #                         #  anything now (eg in defobj)
226 #  $ctx->{DrawMap}        # =$fn s.t.
227 #                         #  &$fn($drawchrs_spec_by_layer_cmdline)
228 #                         #   = $drawchrs_we_should_use_due_to_obj_etc
229 #  $ctx->{SegName}        # initial segment name (at start of object or file)
230 #                         #  or nonexistent if in object in unknown segment
231 #                         #  may have leading `-'
232 #  $ctx->{SegMapN}{$s}= $o
233 #  $ctx->{SegMapNM}{$s}= $o
234 #  $ctx->{SavedSegment}   # exists iff segment command used, is a $csss
235 #  $ctx->{Layer}{Level}
236 #  $ctx->{Layer}{Kind}
237 #
238 #  $objs{$id}{CmdLog}
239 #  $objs{$id}{Loc}
240 #  $objs{$id}{Part}       # 1 iff object is a part
241 #
242 #  $eopts[]{GlobRe}       # regexp for K
243 #  $eopts[]{LayerCheck}   # =$fn where &$fn($l) is true iff layer matches
244 #  $eopts[]{DrawMods}     # modifier chars for drawing
245 #
246 #  @segments= ( $csss0, $dist0, $csss1, $dist1, ..., $csssn )
247 #                         # here each csss may have preceding `-'
248 #
249 #  $subsegcmap{$csss} = "$green $blue"
250 #                         # $csss is canonical subseg spec; always has '/'
251 #  $segcmap{$bareseg} = "$postscript"
252 #
253 #  $seggraphends{"$bareseg"}[]{X}
254 #  $seggraphends{"$bareseg"}[]{Y}
255 #  $seggraphends{"$bareseg"}[]{A}
256 #  $seggraphends{"-$bareseg"}[]...
257 #  $seggraphend[0]{X}
258 #  $seggraphend[0]{Y}
259 #  $seggraphend[1]{X}
260 #  $seggraphend[1]{Y}
261
262 our $ctx;
263 our %objs;
264 our %seggraphends;
265 our @seggraphend;
266 our @al; # current cmd
267
268 our $o='';
269 our $ol='';
270
271 our $param; # for parametric_segment
272
273 # ev_... functions
274 #
275 # Operate on Enhanced Vectors which are a location (coordinates) and a
276 # direction at that location.  Representation is a hash with members X
277 # Y and A (angle of the direction in radians, anticlockwise from
278 # East).  May be absolute, or interpreted as relative, according to
279 # context.
280 #
281 # Each function's first argument is a hashref whose X Y A members will
282 # be created or overwritten; this hashref will be returned (so you can
283 # use it `functionally' by passing {}).  The other arguments may be ev
284 # hashrefs, or other info.  The results are in general undefined if
285 # one of the arguments is the same hash as the result.
286
287 sub ev_byang ($$;$) {
288     # ev_byang(R, ANG,[LEN])
289     # result is evec LEN (default=1.0) from origin pointing in direction ANG
290     my ($res,$ang,$len)=@_;
291     $len=1.0 unless defined $len;
292     $res->{X}= $len * cos($ang);
293     $res->{Y}= $len * sin($ang);
294     $res->{A}= $ang;
295     $res;
296 }
297 sub ev_compose ($$$) {
298     # ev_compose(SUM_R, A,B);
299     # appends B to A, result is end of new B
300     # (B's X is forwards from end of A, Y is translating left from end of A)
301     # A may have a member R, which if provided then it should be 1.0 or -1.0,
302     # and B's Y and A will be multiplied by R first (ie, we can reflect);
303     my ($sum,$a,$b) = @_;
304     my ($r);
305     $r= defined $a->{R} ? $a->{R} : 1.0;
306     $sum->{X}= $a->{X} + $b->{X} * cos($a->{A}) - $r * $b->{Y} * sin($a->{A});
307     $sum->{Y}= $a->{Y} + $r * $b->{Y} * cos($a->{A}) + $b->{X} * sin($a->{A});
308     $sum->{A}= $a->{A} + $r * $b->{A};
309     $sum;
310 }
311 sub ev_decompose ($$$) {
312     # ev_decompose(B_R, A,SUM)
313     # computes B_R s.t. ev_compose({}, A, B_R) gives SUM
314     my ($b,$a,$sum)=@_;
315     my ($r,$brx,$bry);
316     $r= defined $a->{R} ? $a->{R} : 1.0;
317     $brx= $sum->{X} - $a->{X};
318     $bry= $r * ($sum->{Y} - $a->{Y});
319     $b->{X}= $brx * cos($a->{A}) + $bry * sin($a->{A});
320     $b->{Y}= $bry * cos($a->{A}) - $brx * sin($a->{A});
321     $b->{A}= $r * ($sum->{A} - $a->{A});
322     $b;
323 }
324 sub ev_lincomb ($$$$) {
325     # ev_linkcomb(RES,A,B,P)
326     # gives P*A + (1-P)*B
327     my ($r,$a,$b,$p) = @_;
328     my ($q) = 1.0-$p;
329     map { $r->{$_} = $q * $a->{$_} + $p * $b->{$_} } qw(X Y A);
330     $r;
331 }
332 sub a_normalise ($$) {
333     # a_normalise(A,Z)
334     # adds or subtracts 2*$pi to/from A until it is in [ Z , Z+2*$pi >
335     my ($a,$z)=@_;
336     my ($r);
337     $r= $z + fmod($a - $z, 2.0*$pi);
338     $r += 2*$pi if $r < $z;
339     return $r;
340 }
341 sub ev_bearing ($$) {
342     # ev_bearing(A,B)
343     # returns bearing of B from A
344     # value returned is in [ A->{A}, A->{A} + 2*$pi >
345     # A->{A} and B->{A} are otherwise ignored
346     my ($a,$b)= @_;
347     my ($r);
348     $r= atan2($b->{Y} - $a->{Y},
349               $b->{X} - $a->{X});
350     $r= a_normalise($r,$a->{A});
351     return $r;
352 }
353
354 sub v_rotateright ($) {
355     # v_rotateright(A)
356     # returns image of A rotated 90 deg clockwise
357     my ($a)= @_;
358     return { X => $a->{Y}, Y => -$a->{X} };
359 }
360 sub v_dotproduct ($$) {
361     # v_dotproduct(A,B)
362     my ($a,$b)= @_;
363     return $a->{X} * $b->{X} + $a->{Y} * $b->{Y};
364 }
365 sub v_scalarmult ($$) {
366     # v_scalarmult(S,V)
367     # multiplies V by scalar S and returns product
368     my ($s,$v)=@_;
369     return { X => $s * $v->{X}, Y => $s * $v->{Y} };
370 }
371 sub v_add ($;@) {
372     # v_add(A,B,...)
373     # vector sum of all inputs
374     my (@i) = @_;
375 #print STDERR "add ".join('|',keys %{$i[0]}),"<\n";
376 #map { print STDERR " ".join('|',keys %{$_}),"<\n"; } @i;
377     my ($r,$i);
378     $r= { X => 0.0, Y => 0.0 };
379     foreach $i (@i) { $r->{X} += $i->{X}; $r->{Y} += $i->{Y}; }
380     return $r;
381 }
382 sub v_mean (;@) {
383     my (@i) = @_;
384 #print STDERR "mean ".join('|',keys %{$i[0]}),"<\n";
385 #map { print STDERR " ".join('|',keys %{$_}),"<\n"; } @i;
386     my ($r) = v_add($i[0],@i[1..$#i]);
387     $r->{X} /= @i;
388     $r->{Y} /= @i;
389     return $r;
390 }
391 sub v_subtract ($$) {
392     # v_subtract(A,B)
393     # returns vector from A to B, ie B - A
394     my ($a,$b)= @_;
395     return { X => $b->{X} - $a->{X},
396              Y => $b->{Y} - $a->{Y} };
397 }
398 sub v_len ($) {
399     # v_len(V)
400     # scalar length of V
401     my ($v)=@_;
402     my ($x,$y) = ($v->{X}, $v->{Y});
403     return sqrt($x*$x + $y*$y);
404 }
405 sub v_dist ($$) {
406     # v_dist(A,B)
407     # returns distance from A to B
408     return v_len(v_subtract($_[0],$_[1]));
409 }
410
411 sub upd_min ($$) {
412     my ($limr,$now)=@_;
413     $$limr= $now unless defined $$limr && $$limr <= $now;
414 }
415 sub upd_max ($$) {
416     my ($limr,$now)=@_;
417     $$limr= $now unless defined $$limr && $$limr >= $now;
418 }
419
420 sub canf ($$) {
421     my ($converter,$defaulter)=@_;
422     my ($spec,$v);
423     return &$defaulter unless @al;
424     $spec= shift @al;
425     $v= &$converter($spec);
426     dv('canf ','$spec',$spec, '$v',$v);
427     return $v;
428 }
429 sub can ($) { my ($c)=@_; canf($c, sub { die "too few args"; }); }
430 sub cano ($$) { my ($c,$def)=@_; canf($c, sub { return $def }); }
431
432 sub signum ($) { return ($_[0] > 0) - ($_[0] < 0); }
433
434 sub bbox ($) {
435     my ($objhash) = @_;
436     my ($min_x, $max_x, $min_y, $max_y);
437     my ($loc);
438     foreach $loc (values %$objhash) {
439         upd_min(\$min_x, $loc->{X} - abs($allwidthmax * sin($loc->{A})));
440         upd_max(\$max_x, $loc->{X} + abs($allwidthmax * sin($loc->{A})));
441         upd_min(\$min_y, $loc->{Y} - abs($allwidthmax * cos($loc->{A})));
442         upd_max(\$max_y, $loc->{Y} + abs($allwidthmax * cos($loc->{A})));
443     }
444     return ($min_x, $max_x, $min_y, $max_y);
445 }
446
447 our %units_len= qw(- mm  mm 1  cm 10  m 1000);
448 our %units_ang= qw(- d   r 1); $units_ang{'d'}= 2*$pi / 360;
449
450 sub cva_len ($) { my ($sp)=@_; cva_units($sp,\%units_len); }
451 sub cva_identity ($) { my ($sp)=@_; $sp; }
452 sub cva_ang ($) { my ($sp)=@_; cva_units($sp,\%units_ang); }
453 sub cva_absang ($) { input_absang(cva_ang($_[0])) }
454 sub cva_units ($$) {
455     my ($sp,$ua)=@_;
456     my ($n,$u,$r);
457     $sp =~ m/^([-0-9eE.]*[0-9.])([A-Za-z]*)$/
458         or die "lexically invalid quantity";
459     ($n,$u)= ($1,$2);
460     $u=$ua->{'-'} unless length $u;
461     defined $ua->{$u} or die "unknown unit $u";
462     $r= $n * $ua->{$u};
463     print DEBUG "cva_units($sp,)=$r ($n $u $ua->{$u})\n";
464     return $r;
465 }
466 sub cva_idstr ($) {
467     my ($sp)=@_;
468     die "invalid id" unless $sp =~ m/^[a-z][_0-9A-Za-z]*$/;
469     return $&;
470 }
471 sub cva_idex ($) {
472     my ($sp)=@_;
473     my ($id,$r,$d,$k,$neg,$na,$obj_id,$vflip,$locs);
474     if ($sp =~ s/^(\^?)(\w+)\!//) {
475         $vflip= length($1);
476         $obj_id= $2;
477         die "invalid obj $obj_id in loc" unless exists $objs{$obj_id};
478         $locs= $objs{$obj_id}{Loc};
479     } else {
480         $locs= $ctx->{Loc};
481         $vflip= 0;
482     }
483     $neg= $sp =~ s/^\-//;
484     $id= cva_idstr($sp);
485     die "unknown $id" unless defined $locs->{$id};
486     $r= $locs->{$id};
487     $d= "idex $id";
488     foreach $k (sort keys %$r) { $d .= " $k=$r->{$k}"; }
489     printf DEBUG "%s\n", $d;
490     if ($vflip) {
491         $r= { X => $r->{X}, Y => -$r->{Y}, A => -$r->{A} };
492     }
493     if ($neg) {
494         $na= $r->{A} + $pi;
495         $na= a_normalise($na,0);
496         $r= { X => $r->{X}, Y => $r->{Y}, A => $na };
497     }
498     return $r;
499 }
500 sub cva_idnew ($) {
501     my ($sp)=@_;
502     my ($id, $neg);
503     $neg = $sp =~ s/^\-//;
504     $id=cva_idstr($sp);
505     die "duplicate $id" if exists $ctx->{Loc}{$id};
506     $ctx->{Loc}{$id}{LayerKind}= $ctx->{Layer}{Kind};
507     push @{ $ctx->{LocsMade} }, {
508         Id => $id,
509         Neg => $neg,
510     };
511     return $ctx->{Loc}{$id};
512 }
513 sub cva_cmd ($) { return cva_idstr($_[0]); }
514 sub cva__enum ($$) {
515     my ($sp,$el)=@_;
516     return $sp if grep { $_ eq $sp } @$el;
517     die "invalid option (permitted: @$el)";
518 }
519 sub cvam_enum { my (@e) = @_; return sub { cva__enum($_[0],\@e); }; }
520
521 sub cmd_abs {
522     my ($i,$nl);
523     $nl= can(\&cva_idnew);
524     $i->{X}= can(\&cva_len);
525     $i->{Y}= can(\&cva_len);
526     $i->{A}= can(\&cva_ang);
527     ev_compose($nl, $ctx->{Trans}, $i);
528 }
529 sub cmd_rel {
530     my ($from,$to,$len,$right,$turn);
531     $from= can(\&cva_idex);
532     $to= can(\&cva_idnew);
533     $len= cano(\&cva_len,0);
534     $right= cano(\&cva_len,0) * $ctx->{Trans}{R};
535     $turn= cano(\&cva_ang, 0) * $ctx->{Trans}{R};
536     my ($u)= ev_compose({}, $from, { X => $len, Y => -$right, A => 0 });
537     ev_compose($to, $u, { X => 0, Y => 0, A => $turn });
538 }
539
540 sub dv__evreff ($) {
541     my ($pfx) = @_;
542     $pfx . ($pfx =~ m/\}$|\]$/ ? '' : '->');
543 }
544 sub dv__evr ($) {
545     my ($v) = @_;
546     return 'undef' if !defined $v;
547     return $v if $v !~ m/\W/ && $v =~ m/[A-Z]/ && $v =~ m/^[a-z_]/i;
548     return $v if $v =~ m/^[0-9.]+/;
549     $v =~ s/[\\\']/\\$&/g;
550     return "'$v'";
551 }
552 sub dv1 ($$$);
553 sub dv1_kind ($$$$$$$) {
554     my ($pfx,$expr,$ref,$ref_exp,$ixfmt,$ixesfn,$ixmapfn) = @_;
555     my ($ix,$any);
556     return 0 if $ref ne $ref_exp;
557     $any=0;
558     foreach $ix (&$ixesfn) {
559         $any=1;
560         my ($v)= &$ixmapfn($ix);
561 #print STDERR "dv1_kind($pfx,$expr,$ref,$ref_exp,$ixmapfn) ix=$ix v=$v\n";
562         dv1($pfx,$expr.sprintf($ixfmt,dv__evr($ix)),$v);
563     }
564     if (!$any) {
565         printf DEBUG "%s%s= $ixfmt\n", $pfx, $expr, ' ';
566     }
567     1;
568 }    
569 sub dv1 ($$$) {
570     return 0 unless $debug;
571     my ($pfx,$expr,$v) = @_;
572     my ($ref);
573     $ref= ref $v;
574 #print STDERR "dv1 >$pfx|$ref<\n";
575     if (!$ref) {
576         printf DEBUG "%s%s= %s\n", $pfx,$expr, dv__evr($v);
577         return;
578     } elsif ($ref eq 'SCALAR') {
579         dv1($pfx, ($expr =~ m/^\$/ ? "\$$expr" : '${'.$expr.'}'), $$v);
580         return;
581     }
582     $expr.='->' unless $expr =~ m/\]$|\}$/;
583     return if dv1_kind($pfx,$expr,$ref,'ARRAY','[%s]',
584                        sub { ($[ .. $#$v) },
585                        sub { $v->[$_[0]] });
586     return if dv1_kind($pfx,$expr,$ref,'HASH','{%s}',
587                        sub { sort keys %$v },
588                        sub { $v->{$_[0]} });
589     printf DEBUG "%s%s is %s\n", $pfx, $expr, $ref;
590 }
591     
592 sub dv {
593     my ($pfx,@l) = @_;
594     my ($expr,$v,$ref);
595     while (@l) {
596         ($expr,$v,@l)=@l;
597         dv1($pfx,$expr,$v);
598     }
599 }                   
600
601 sub o ($) { $o .= $_[0]; }
602 sub ol ($) { $ol .= $_[0]; }
603 sub oflushpage () {
604     return if $subsegcmapreq;
605
606     print $o, $ol, "  showpage\n"
607         or die $!;
608     $o=$ol='';
609 }
610
611 our $o_path_verb;
612
613 sub o_path_begin () {
614     o("      newpath\n");
615     $o_path_verb= 'moveto';
616 }
617 sub o_path_point ($) {
618     my ($pt)=@_;
619     o("        $pt $o_path_verb\n");
620     $o_path_verb= 'lineto';
621 }
622 sub o_path_stroke ($) {
623     my ($width)=@_;
624     o("        $width setlinewidth stroke\n");
625 }
626 sub o_path_strokeonly () {
627     o("      stroke\n");
628 }
629
630 sub o_transform ($) {
631     my ($pt) = @_;
632     my ($ad);
633     $ad= ang2deg($pt->{A});
634     ol("      gsave\n".
635        "        $pt->{X} $pt->{Y} translate\n".
636        "        $ad rotate\n");
637 }
638
639 sub o_line ($$$) {
640     my ($a,$b,$width)=@_;
641     o_path_begin();
642     o_path_point($a);
643     o_path_point($b);
644     o_path_stroke($width);
645 }
646
647 sub current_draw () {
648     my ($r);
649     $r= $ctx->{Draw} =~ m/X/ ? '' : $ctx->{Draw};
650     $r;
651 }
652
653 sub psu_coords ($$$) {
654     my ($ends,$inunit,$across)=@_;
655     # $ends->[0]{X} etc.; $inunit 0 to 1 (but go to 1.5);
656     # $across in mm, +ve to right.
657     my (%ea_zo, $zo, $prop);
658     $ea_zo{X}=$ea_zo{Y}=0;
659     foreach $zo (qw(0 1)) {
660         $prop= $zo ? $inunit : (1.0 - $inunit);
661         $ea_zo{X} += $prop * ($ends->[$zo]{X} - $across * sin($ends->[0]{A}));
662         $ea_zo{Y} += $prop * ($ends->[$zo]{Y} + $across * cos($ends->[0]{A}));
663     }
664 #    dv("psu_coords ", '$ends',$ends, '$inunit',$inunit, '$across',$across,
665 #       '\\%ea_zo', \%ea_zo);
666     return $ea_zo{X}." ".$ea_zo{Y};
667 }
668
669 sub parametric__o_pt ($) {
670     my ($pt)=@_;
671     o_path_point("$pt->{X} $pt->{Y}");
672 }
673
674 our $segused_incurrent;
675 our $segused_currentpt;
676 our $segmentpart_counter=0;
677 our $segused_restorecounter;
678
679 sub segment_used__print ($) {
680     my ($pt) = @_;
681     if ($segused_incurrent > 0 && $segused_restorecounter==1) {
682         o("%L segmentpart ".
683           $segmentpart_counter++." ".
684           $ctx->{Layer}{Level}.$ctx->{Layer}{Kind}." ".
685           $segments[0]." ".
686           $segused_incurrent." ".
687           loc2dbg($segused_currentpt)." ".
688           loc2dbg($pt)."\n");
689     }
690     $segused_incurrent= undef;
691     $segused_currentpt= undef;
692 }
693     
694 sub segment_used__len ($$) {
695     my ($used,$pt) = @_;
696     $segused_incurrent += $used;
697
698     return if @segments < 3;
699     $segments[1] -= $used;
700     return if $segments[1] > 0;
701
702     segment_used__print($pt);
703     segment_used_begin($pt);
704
705     @segments= @segments[2..$#segments];
706     o("% segments @segments\n");
707 }
708     
709 sub segment_state_save () {
710     return [ 0, $segused_incurrent, $segused_currentpt,
711              $segmentpart_counter, @segments ];
712 }
713 sub segment_state_restore ($) {
714     my ($r) = @_;
715     ($segused_restorecounter, $segused_incurrent, $segused_currentpt,
716      $segmentpart_counter, @segments) = @$r;
717     $r->[0]++;
718 }
719
720 sub segment__check_graphends () {
721     my ($bare,$ge,$i,$key);
722     @seggraphend= ();
723     $segments[0] =~ m/^\-?(\w+)/ or return;
724     $bare= $1;
725     foreach $i (qw(0 1)) {
726         $key= ('', '-')[$i].$bare;
727         $ge= $seggraphends{$key};
728         defined $ge or return;
729 #print STDERR "$key @$ge\n";
730 #map { print STDERR " ".join('|',keys %{$_}),"<\n"; } @$ge;
731         $seggraphend[$i]= v_mean(@$ge);
732 #print STDERR "SGE $i $seggraphend[$i]{X} $seggraphend[$i]{Y}\n";
733     }
734 }
735
736 sub segment_used_begin ($) {
737     $segused_incurrent= 0;
738     $segused_currentpt= $_[0];
739     segment__check_graphends();
740 }
741 sub segment_used_middle ($$) {
742     my ($used,$pt) = @_;
743     segment_used__len($used,$pt);
744     segment__check_graphends();
745 }
746 sub segment_used_end ($$) {
747     my ($used,$pt) = @_;
748     segment_used__len($used,$pt);
749     segment_used__print($pt);
750 }
751 sub parametric_segment ($$$$$) {
752     my ($p0,$p1,$lenperp,$minradius,$calcfn) = @_;
753     # makes $param (global) go from $p0 to $p1  ($p1>$p0)
754     # $lenperp is the length of one unit p, ie the curve
755     # must have a uniform `density' in parameter space
756     # $calcfn is invoked with $param set and should return a loc
757     # (ie, ref to X =>, Y =>, A =>).
758     my ($pa,$pb,@ends,$side,$ppu,$e,$v,$tick,$draw,$allwidth,%seglabel);
759     return unless $ctx->{Draw} =~ m/[ARSCGQE]/;
760     $ppu= $psu_ulen/$lenperp;
761     $allwidth= allwidth($minradius);
762     my ($railctr)=($psu_gauge + $psu_raillw)*0.5;
763     my ($tickend)=($allwidth - $psu_ticklen);
764     my ($tickpitch)=($psu_ulen / $psu_ticksperu);
765     my ($sleeperctr)=($psu_ulen*0.5);
766     my ($sleeperend)=($psu_sleeperlen*0.5);
767 print DEBUG "ps $p0 $p1 $lenperp ($ppu)\n";
768     $draw= current_draw();
769     if ($draw =~ m/[QGE]/) {
770         my ($pt,$going,$red,$csegbare,$movfeat,$movstroke);
771         my ($used_last,$me,$segsave,$diff);
772         o("gsave\n");
773         $segsave= segment_state_save();
774         foreach $me ($draw =~ m/Q/ ? qw(q) : qw(e m)) {
775             segment_state_restore($segsave);
776             $going=0;
777             o("% segments @segments\n");
778             $param=$p0;
779             $pt= &$calcfn;
780             segment_used_begin($pt);
781             for (;;) {
782                 $movstroke= "      cmapreq-stroke\n";
783                 $csegbare= $segments[0];
784                 $csegbare =~ s/^\-//;
785                 if ($subsegcmapreq) {
786                     if (!exists $subsegcmap{$csegbare}) {
787                         print "$csegbare\n" or die $!;
788                         $subsegcmap{$csegbare}++;
789                     }
790                 } else {
791                     if ($draw =~ m/Q/) {
792                         $csegbare =~ m,^[^/]*,;
793 #print STDERR "looking for \`$&' $me\n";
794                         $movstroke= $segcmap{$&};
795                         $movstroke= "%     no-colour    "
796                             unless defined $movstroke;
797                     } elsif ($draw =~ m/G/) {
798                         $movfeat= $csegbare =~ s,(/\D+)(\d+)$,$1, ? $2 : 'f';
799                         die "unknown subsegment colour for $csegbare\n"
800                             unless exists $subsegcmap{$csegbare};
801                         $red= $pt->{A} / (2*$pi);
802                         $red *= $subsegcmapangscale;
803                         $red += $subsegcmapangscale*2;
804                         $red += $subsegcmapangscale/2
805                             if $segments[0] =~ m/^\-/;
806                         $red %= $subsegcmapangscale;
807                         $red += $subsegcmapangscale if $me eq 'e';
808                         $red= sprintf("%f", $red / 255.0);
809                         $movstroke= "    $red $subsegcmap{$csegbare}".
810                                     " setrgbcolor\n";
811                         if ($subsegmovfeatpos ne $movfeat ||
812                             ($me eq 'e' && $csegbare =~ m,^/,)) {
813                             $movstroke= "%     no-stroke    ";
814                         }
815                     } else {
816                         $movstroke= "!! seglabels-only ";
817                     }
818                     $movstroke .=
819                         "    $psu_subseglw{$me} setlinewidth stroke\n";
820                 }
821                 if ($draw =~ m/[QG]/) {
822                     o_path_begin();
823                     parametric__o_pt($pt);
824                 }
825                 $param += $ppu;
826                 last if $param>=$p1;
827                 $pt= &$calcfn;
828                 if ($draw =~ m/E/ && @seggraphend==2) {
829                     $diff= v_len(v_subtract($pt, $seggraphend[0])) -
830                            v_len(v_subtract($pt, $seggraphend[1]));
831                     if (abs($diff) < $psu_ulen*3) {
832                         $segments[0] =~ m/^(\-?)(\w+)/;
833                         $seglabel{$2}{X}= $pt->{X};
834                         $seglabel{$2}{Y}= $pt->{Y};
835                         $seglabel{$2}{A}= $pt->{A};
836                         $seglabel{$2}{A} += $pi if length($1);
837                     }
838                 }
839                 segment_used_middle($psu_ulen,$pt);
840                 if ($draw =~ m/[QG]/) {
841                     parametric__o_pt($pt);
842                     o($movstroke);
843                 }
844             }
845             $used_last= $p1-($param-$ppu);
846             $param=$p1;
847             $pt= &$calcfn;
848             segment_used_end($used_last * $lenperp, $pt);
849             parametric__o_pt($pt);
850             o($movstroke);
851         }
852         o("grestore\n");
853     }
854     if ($draw =~ m/C/) {
855         my ($pt);
856         o("    $psu_thinlw setlinewidth\n");
857         o_path_begin();
858         for ($param=$p0; $param<$p1; $param += $ppu) {
859             parametric__o_pt(&$calcfn);
860         }
861         $param=$p1;
862         parametric__o_pt(&$calcfn);
863         o("      stroke\n");
864     }
865     if ($draw =~ m/E/) {
866         my ($pt,$seg);
867         foreach $seg (keys %seglabel) {
868             $pt= $seglabel{$seg};
869             ol("    gsave\n");
870             o_transform($pt);
871             ol("      /s ($seg) def\n".
872                "      sf setfont\n".
873                "      0 0 moveto\n".
874                "      s stringwidth pop -0.5 mul  $lmu_segtxtoff  moveto\n".
875                "      s show\n".
876                "      grestore\n");
877         }
878     }
879     if ($draw =~ m/[ARS]/) { for ($pa= $p0; $pa<$p1; $pa=$pb) {
880         $pb= $pa + $ppu;
881         $param= $pa; $ends[0]= @ends ? $ends[1] : &$calcfn;
882         $param= $pb; $ends[1]= &$calcfn;
883 #print DEBUG "pa $pa $ends[0]{X} $ends[0]{Y} $ends[0]{A}\n";
884 #print DEBUG "pb $pb $ends[1]{X} $ends[1]{Y} $ends[1]{A}\n";
885         $e= $pb<=$p1 ? 1.0 : ($p1-$pa)/$ppu;
886         o("    gsave\n");
887         o_path_begin();
888         o_path_point(psu_coords(\@ends,0,-$allwidth));
889         o_path_point(psu_coords(\@ends,0,$allwidth));
890         o_path_point(psu_coords(\@ends,$e,$allwidth));
891         o_path_point(psu_coords(\@ends,$e,-$allwidth));
892         o("        closepath clip\n");
893         foreach $side qw(-1 1) {
894             if ($draw =~ m/R/) {
895                 o_line(psu_coords(\@ends,0,$side*$railctr),
896                        psu_coords(\@ends,1.5,$side*$railctr),
897                        $psu_raillw);
898             }
899         }
900         if ($draw =~ m/S/) {
901             o_line(psu_coords(\@ends,$sleeperctr,-$sleeperend),
902                    psu_coords(\@ends,$sleeperctr,+$sleeperend),
903                    $psu_sleeperlw);
904         }
905         if ($draw =~ m/A/) {
906             o("        0.5 setgray\n");
907             foreach $side qw(-1 1) {
908                 o_line(psu_coords(\@ends,0,$side*$allwidth),
909                        psu_coords(\@ends,1.5,$side*$allwidth),
910                        $psu_edgelw);
911                 for ($tick=0; $tick<1.5; $tick+=$tickpitch/$psu_ulen) {
912                     o_line(psu_coords(\@ends,$tick,$side*$allwidth),
913                            psu_coords(\@ends,$tick,$side*$tickend),
914                            $psu_ticklw);
915                 }
916             }
917         }
918         o("      grestore\n");
919     } }
920     if ($draw =~ m/D/) {
921         my ($pt,$len,$off);
922         $param= ($p0+$p1)*0.5;
923         $pt= &$calcfn;
924         $len= sprintf "%.0f", $lenperp * abs($p1-$p0);
925         $off= $draw =~ m/C/ ? $lmu_lenlabeloff : $lmu_lenlabeloffctr;
926         ol("      gsave\n");
927         o_transform($pt);
928         ol("        lf setfont\n".
929            "        0 $off moveto\n".
930            "        ($len) show\n".
931            "      grestore\n");
932     }    
933 }
934
935 sub arc ($$$$$) {
936     my ($to, $ctr,$from, $radius,$delta) = @_;
937     # does parametric_segment to draw an arc centred on $ctr
938     # ($ctr->{A} ignored)
939     # from $from with radius $radius (this must be consistent!)
940     # and directionally-subtending an angle $delta.
941     # sets $to->... to be the other end, and returns $to
942     my ($beta);
943     $to->{A}= $beta= $from->{A} + $delta;
944     $to->{X}= $ctr->{X} - $radius * sin($beta);
945     $to->{Y}= $ctr->{Y} + $radius * cos($beta);
946     return if abs($delta*$radius) < 1e-9;
947     parametric_segment(0.0,1.0, abs($radius*$delta), $radius, sub {
948         my ($beta) = $from->{A} + $delta * $param;
949         return { X => $ctr->{X} - $radius * sin($beta),
950                  Y => $ctr->{Y} + $radius * cos($beta),
951                  A => $beta }
952     });
953 }
954
955 # joins_xxx all take $results, $from, $to, $minradius
956 # where $results->[]{Path}{K} etc. and $results->[]{SolKinds}[]
957
958 sub joins_twoarcs ($$$$) {
959     my ($results, $from,$to,$minradius) = @_;
960     # two circular arcs of equal maximum possible radius
961     # algorithm courtesy of Simon Tatham (`Railway problem',
962     # pers.comm. to ijackson@chiark 23.1.2004)
963     my ($sigma,$distfact, $theta,$phi, $a,$b,$c,$d, $m,$r, $radius);
964     my ($cvec,$cfrom,$cto,$midpt, $delta1,$delta2, $path,$reverse);
965     $sigma= ev_bearing($from,$to);
966     $distfact= v_dist($from,$to);
967     $theta= 0.5 * $pi - ($from->{A} - $sigma);
968     $phi=   0.5 * $pi - ($to->{A} + $pi - $sigma);
969     $a= 2 * (1 + cos($theta - $phi));
970     $b= 2 * (cos($theta) - cos($phi));
971     $c= -1;
972     $d= sqrt($b*$b - 4*$a*$c);
973     o("%     twoarcs theta=".ang2deg($theta)." phi=".ang2deg($phi).
974       " ${a}r^2 + ${b}r + ${c} = 0\n");
975     foreach $m (qw(-1 1)) {
976         if ($a < 1e-6) {
977             o("%     twoarcs $m insoluble\n");
978             next;
979         }
980         $r= -0.5 * (-$b + $m*$d) / $a;
981         $radius= -$r * $distfact;
982         o("%     twoarcs $m radius $radius ");
983         if (abs($radius) < $minradius) { o("too-small\n"); next; }
984         $cfrom=  ev_compose({}, $from, { X=>0, Y=>-$radius, A=>-0.5*$pi });
985         $cto=    ev_compose({}, $to,   { X=>0, Y=> $radius, A=> 0.5*$pi });
986         $midpt=  ev_lincomb({}, $cfrom, $cto, 0.5);
987         $reverse= signum($r);
988         if ($reverse<0) {
989             $cfrom->{A} += $pi;
990             $cto->{A} += $pi;
991         }
992         $delta1= ev_bearing($cfrom, $midpt) - $cfrom->{A};
993         $delta2= ev_bearing($cto,   $midpt) - $cto->{A};
994         o("ok deltas ".ang2deg($delta1)." ".ang2deg($delta2)."\n");
995         if ($reverse<0) {
996             $delta1 -= 2*$pi;
997             $delta2 -= 2*$pi;
998         }
999         my ($fs);
1000         $path= [{ T=>Arc, F=>$from, C=>$cfrom, R=> $radius, D=>$delta1 },
1001                 { T=>Arc, F=>$to,   C=>$cto,   R=>-$radius, D=>$delta2 }];
1002         push @$results, { Path => $path,
1003                           SolKinds =>  [ 'twoarcs', 'cross' ] };
1004     }
1005 }
1006     
1007 sub joins_arcsline ($$$$) {
1008     my ($results, $from,$to,$minradius) = @_;
1009     # two circular arcs of specified radius
1010     # with an intervening straight
1011     my ($lr,$inv, $c,$d,$alpha,$t,$k,$l,$rpmsina,$rcosa,$linelen, $path);
1012     if ($minradius<=1e-6) { o("%     arcsline no-radius\n"); return; }
1013     foreach $lr (qw(-1 +1)) {
1014         foreach $inv (qw(-1 +1)) {
1015             $c=ev_compose({},$from,{X=>0,Y=>-$lr*$minradius, A=>0 });
1016             $d=ev_compose({},$to,{X=>0, Y=>-$inv*$lr*$minradius, A=>$pi });
1017             $t= v_dist($c,$d);
1018             o("%     arcsline $lr $inv t=$t ");
1019             if ($t < 1e-6) { o("concentric"); next; }
1020             $c->{A}= $d->{A}= ev_bearing($c,$d);
1021             o("bearing ".ang2deg($c->{A}));
1022             if ($inv>0) {
1023                 o("\n");
1024                 $k= ev_compose({}, $c, { X=>0, Y=>$lr*$minradius, A=>0 });
1025                 $l= ev_compose({}, $d, { X=>0, Y=>$lr*$minradius, A=>0 });
1026                 $linelen= $t;
1027             } else {
1028                 my ($cosalpha) = 2.0 * $minradius / $t;
1029                 if ($cosalpha > (1.0 - 1e-6)) { o(" too-close\n"); next; }
1030                 $alpha= acos($cosalpha);
1031                 $rpmsina= $lr * $minradius * sin($alpha);
1032                 $rcosa= $minradius * $cosalpha;
1033                 $k= ev_compose({}, $c, { X=>$rcosa, Y=>$rpmsina, A=>0 });
1034                 $l= ev_compose({}, $d, { X=>-$rcosa, Y=>-$rpmsina, A=>0 });
1035                 $k->{A}= $l->{A}= ev_bearing($k,$l);
1036                 o(" alpha=".ang2deg($alpha)." kl^=".ang2deg($k->{A})."\n");
1037                 $linelen= v_dist($k,$l);
1038             }
1039             $path= [{ T => Arc, F => $from, C => $c,
1040                       R =>$lr*$minradius,
1041                       D => -$lr * a_normalise
1042                           ($lr * ($from->{A} - $k->{A}), 0) },
1043                     { T => Line, A => $k, B => $l, L => $linelen },
1044                     { T => Arc, F => $l, C => $d,
1045                       R => $inv*$lr*$minradius,
1046                       D => -$lr*$inv * a_normalise
1047                           (-$lr*$inv * ($to->{A} - $l->{A}), 0) }];
1048             push @$results,
1049             { Path => $path,
1050               SolKinds => [ 'arcsline', ($inv<0 ? 'cross' : 'loop') ] };
1051         }
1052     }
1053 }
1054
1055 sub joins_arcline ($$$$) {
1056     my ($results, $from,$to,$minradius) = @_;
1057     # one circular arc and a straight line
1058     my ($swap,$echoice,$path, $ap,$bp,$av,$bv, $e,$f, $ae,$af,$afae);
1059     my ($dak,$ak,$kj,$k,$j,$aja,$jl,$l,$jc,$lc,$c,$rj,$rb);
1060     foreach $swap (qw(-1 +1)) {
1061         foreach $echoice (qw(0 1)) {
1062             $ap= $from; $bp= { %$to }; $bp->{A} += $pi;
1063             ($ap,$bp)= ($bp,$ap) if $swap<0;
1064             $av= ev_byang({}, $ap->{A});
1065             $bv= ev_byang({}, $bp->{A});
1066             $e= ev_byang({}, 0.5 * ($ap->{A} + $bp->{A} + $echoice * $pi));
1067             $f= v_rotateright($e);
1068             o("%     arcline $swap $echoice e ".loc2dbg($e)."\n");
1069             $ae= v_dotproduct($av,$e);
1070             $af= v_dotproduct($av,$f);
1071             o("%     arcline $swap $echoice a.e=$ae a.f=$af ");
1072             if (abs($ae) < 1e-6) { o(" singular\n"); next; }
1073             $afae= $af/$ae;
1074             o("a.f/a.e=$afae\n");
1075             $dak= v_dotproduct(v_subtract($ap,$bp), $e);
1076             $ak= v_scalarmult($dak, $e);
1077             $kj= v_scalarmult($dak * $afae, $f);
1078             $k= v_add($ap, $ak);
1079             $j= v_add($k, $kj);
1080             $aja= v_dotproduct(v_subtract($ap,$j), $av);
1081             o("%     arcline $swap $echoice d_ak=$dak aj.a=$aja ");
1082             if ($aja < 0) { o(" backwards aj\n"); next; }
1083             $jl= v_scalarmult(0.5, v_subtract($j, $bp));
1084             $lc= v_scalarmult(-v_dotproduct($jl, $f) * $afae, $e);
1085             $l= v_add($j, $jl);
1086             $c= v_add($l, $lc);
1087             $rj= v_dotproduct(v_subtract($j,$c), v_rotateright($av));
1088             $rb= v_dotproduct(v_subtract($c,$bp), v_rotateright($bv));
1089             o("r_j=$rj r_b=$rb ");
1090             if ($rj * $rb < 0) { o(" backwards b\n"); next; }
1091             if (abs($rj) < $minradius) { o(" too-small\n"); next; }
1092             o("ok\n");
1093             $j->{A}= $ap->{A};
1094             $c->{A}= 0;
1095             $path= [{ T => Line, A => $ap, B => $j, L => $aja },
1096                     { T => Arc, F => $j, C => $c, R => $rj,
1097                       D => -signum($rj) * a_normalise
1098                           (-signum($rj) * ($bp->{A} + $pi - $j->{A}), 0) }];
1099             $path= [ reverse @$path ] if $swap<0;
1100             push @$results, { Path => $path, SolKinds =>  [ 'arcline' ] };
1101         }
1102     }
1103 }
1104
1105 sub cmd_join {
1106     my ($from,$to,$minradius);
1107     my (@results,$result);
1108     my ($path,$segment,$bestpath,$len,$scores,$bestscores,@bends,$skl);
1109     my ($crit,$cs,$i,$cmp);
1110     $from= can(\&cva_idex);
1111     $to= can(\&cva_idex);
1112     $minradius= can(\&cva_len);
1113     o("%   join ".loc2dbg($from)."..".loc2dbg($to)." $minradius\n");
1114     joins_twoarcs(\@results, $from,$to,$minradius);
1115     joins_arcsline(\@results, $from,$to,$minradius);
1116     joins_arcline(\@results, $from,$to,$minradius);
1117     foreach $result (@results) {
1118         $path= $result->{Path};
1119         $skl= $result->{SolKinds};
1120         o("%   possible path @$skl $path\n");
1121         $len= 0;
1122         @bends= ();
1123         foreach $segment (@$path) {
1124             if ($segment->{T} eq Arc) {
1125                 o("%     Arc C ".loc2dbg($segment->{C}).
1126                   " R $segment->{R} D ".ang2deg($segment->{D})."\n");
1127                 $len += abs($segment->{R} * $segment->{D});
1128                 push @bends, -abs($segment->{R}) * $segment->{D}; # right +ve
1129             } elsif ($segment->{T} eq Line) {
1130                 o("%     Line A ".loc2dbg($segment->{A}).
1131                   " B ".loc2dbg($segment->{A})." L $segment->{L}\n");
1132                 $len += abs($segment->{L});
1133             } else {
1134                 die "unknown segment $segment->{T}";
1135             }
1136         }
1137         o("%    length $len bends @bends.\n");
1138         $scores= [];
1139         foreach $crit (@al, 'short') {
1140             if ($crit eq 'long') { $cs= $len; }
1141             elsif ($crit eq 'short') { $cs= -$len; }
1142             elsif ($crit =~ m/^(begin|end|)(left|right)$/) {
1143                 if ($1 eq 'begin') { $cs= $bends[0]; }
1144                 elsif ($1 eq 'end') { $cs= $bends[$#bends]; }
1145                 else { $cs=0; map { $cs += $_ } @bends; }
1146                 $cs= -$cs if $2 eq 'left';
1147             } elsif ($crit =~ m/^(\!?)(twoarcs|arcs?line|cross|loop)$/) {
1148                 $cs= !!(grep { $2 eq $_ } @$skl) != ($1 eq '!');
1149             } else {
1150                 die "unknown sort criterion $crit";
1151             }
1152             push @$scores, $cs;
1153         }
1154         o("%    scores @$scores\n");
1155         if (defined $bestpath) {
1156             for ($i=0,$cmp=0; !$cmp && $i<@$scores; $i++) {
1157                 $cmp= $scores->[$i] <=> $bestscores->[$i];
1158             }
1159             next if $cmp < 0;
1160         }
1161         $bestpath= $path;
1162         $bestscores= $scores;
1163     }
1164     die "no solution" unless defined $bestpath;
1165     o("%   chose path $bestpath @al\n");
1166     @al= ();
1167     foreach $segment (@$bestpath) {
1168         if ($segment->{T} eq 'Arc') {
1169             arc({}, $segment->{C},$segment->{F},$segment->{R},$segment->{D});
1170         } elsif ($segment->{T} eq 'Line') {
1171             line($segment->{A}, $segment->{B}, $segment->{L});
1172         } else {
1173             die "unknown segment";
1174         }
1175     }
1176 }
1177
1178 sub line ($$$) {
1179     my ($from,$to,$len) = @_;
1180     if ($len < 0) {
1181         ($from,$to,$len) = ($to,$from,-$len);
1182     }
1183     parametric_segment(0.0, 1.0, $len + 1e-6, undef, sub {
1184         ev_lincomb({}, $from, $to, $param);
1185     });
1186 }
1187
1188 sub cmd_extend {
1189     my ($from,$to,$radius,$len,$upto,$ctr,$beta,$ang,$how,$sign_r);
1190     $from= can(\&cva_idex);
1191     $to= can(\&cva_idnew);
1192     printf DEBUG "from $from->{X} $from->{Y} $from->{A}\n";
1193     $how= can(cvam_enum(qw(len upto ang uptoang parallel)));
1194     if ($how eq 'len') { $len= can(\&cva_len); }
1195     elsif ($how =~ m/ang$/) { $ang= can(\&cva_ang); }
1196     elsif ($how eq 'parallel' || $how eq 'upto') { $upto= can(\&cva_idex); }
1197     $radius= cano(\&cva_len, 'Inf'); # +ve is right hand bend
1198     if ($radius eq 'Inf') {
1199 #       print DEBUG "extend inf $len\n";
1200         if ($how eq 'upto') {
1201             $len= ($upto->{X} - $from->{X}) * cos($from->{A})
1202                 + ($upto->{Y} - $from->{Y}) * sin($from->{A});
1203         } elsif ($how eq 'len') {
1204         } else {
1205             die "len of straight spec by angle";
1206         }
1207         printf DEBUG "len $len\n";
1208         $to->{X}= $from->{X} + $len * cos($from->{A});
1209         $to->{Y}= $from->{Y} + $len * sin($from->{A});
1210         $to->{A}= $from->{A};
1211         line($from,$to,$len);
1212     } else {
1213         my ($sign_r, $sign_ang, $ctr, $beta_interval, $beta, $delta);
1214         print DEBUG "radius >$radius<\n";
1215         $radius *= $ctx->{Trans}{R};
1216         $sign_r= signum($radius);
1217         $sign_ang= 1;
1218         $ctr->{X}= $from->{X} + $radius * sin($from->{A});
1219         $ctr->{Y}= $from->{Y} - $radius * cos($from->{A});
1220         if ($how eq 'upto') {
1221             $beta= atan2(-$sign_r * ($upto->{X} - $ctr->{X}),
1222                          $sign_r * ($upto->{Y} - $ctr->{Y}));
1223             $beta_interval= 1.0;
1224         } elsif ($how eq 'parallel') {
1225             $beta= $upto->{A};
1226             $beta_interval= 1.0;
1227         } elsif ($how eq 'uptoang') {
1228             $beta= input_absang($ang);
1229             $beta_interval= 2.0;
1230         } elsif ($how eq 'len') {
1231             $sign_ang= signum($len);
1232             $beta= $from->{A} - $sign_r * $len / abs($radius);
1233             $beta_interval= 2.0;
1234         } else {
1235             $sign_ang= signum($ang);
1236             $beta= $from->{A} - $sign_r * $ang;
1237             $beta_interval= 2.0;
1238         }
1239     printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
1240         $beta += $sign_ang * $sign_r * 4.0 * $pi;
1241         for (;;) {
1242             $delta= $beta - $from->{A};
1243             last if $sign_ang * $sign_r * $delta <= 0;
1244             $beta -= $sign_ang * $sign_r * $beta_interval * $pi;
1245         }
1246     printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
1247         arc($to, ,$ctr,$from, $radius,$delta);
1248     }
1249     printf DEBUG "to $to->{X} $to->{Y} $to->{A}\n";
1250 }
1251
1252 sub loc2dbg ($) {
1253     my ($loc) = @_;
1254     return "$loc->{X} $loc->{Y} ".ang2deg($loc->{A});
1255 }
1256 sub ang2deg ($) {
1257     return $_[0] * 180 / $pi;
1258 }
1259 sub input_absang ($) {
1260     return $_[0] * $ctx->{Trans}{R} + $ctx->{Trans}{A};
1261 }
1262 sub input_abscoords ($$) {
1263     my ($in,$out);
1264     ($in->{X}, $in->{Y}) = @_;
1265     $in->{A}= 0.0;
1266     $out= ev_compose({}, $ctx->{Trans}, $in);
1267     return ($out->{X}, $out->{Y});
1268 }
1269
1270 sub newctx (;$) {
1271     my ($ctx_save) = @_;
1272     $ctx= {
1273         Trans => { X => 0.0, Y => 0.0, A => 0.0, R => 1.0 },
1274         InRunObj => "",
1275         DrawMap => sub { $_[0]; },
1276         SegMapN => { },
1277         SegMapNM => { }
1278         };
1279     if (defined $ctx_save) {
1280         %{ $ctx->{Layer} }= %{ $ctx_save->{Layer} };
1281         $ctx->{Parent}= $ctx_save;
1282     }
1283 }
1284
1285 our $defobj_save;
1286 our $defobj_ispart;
1287
1288 sub cmd_defobj { cmd__defobj(0); }
1289 sub cmd_defpart { cmd__defobj(1); }
1290 sub cmd__defobj ($) {
1291     my ($ispart) = @_;
1292     my ($id);
1293     $id= can(\&cva_idstr);
1294     die "nested defobj" if $defobj_save;
1295     die "repeated defobj" if exists $objs{$id};
1296     $defobj_save= $ctx;
1297     $defobj_ispart= $ispart;
1298     newctx($defobj_save);
1299     $ctx->{CmdLog}= [ ];
1300     $ctx->{InDefObj}= $id;
1301     $ctx->{Draw}= $defobj_save->{Draw}.'X';
1302     $ctx->{DrawMap}= sub { ''; };
1303     $ctx->{Layer}= { Level => 5, Kind => '' };
1304 }
1305
1306 sub cmd_enddef {
1307     my ($bit,$id);
1308     $id= $ctx->{InDefObj};
1309     die "unmatched enddef" unless defined $id;
1310     foreach $bit (qw(CmdLog Loc)) {
1311         $objs{$id}{$bit}= $ctx->{$bit};
1312     }
1313     $objs{$id}{Part}= $defobj_ispart;
1314     $ctx= $defobj_save;
1315     $defobj_save= undef;
1316     $defobj_ispart= undef;
1317 }
1318
1319 sub cmd__runobj ($) {
1320     my ($obj_id)=@_;
1321     my ($c);
1322     local (@al);
1323     dv("cmd__runobj $obj_id ",'$ctx',$ctx);
1324     foreach $c (@{ $objs{$obj_id}{CmdLog} }) {
1325         @al= @$c;
1326         next if $al[0] eq 'enddef';
1327         cmd__one();
1328     }
1329 }
1330
1331 sub cva_segment ($) {
1332     my ($sp)=@_;
1333     die "invalid segment" if $sp =~ m/\W/;
1334     return $sp;
1335 }
1336
1337 sub cva_segment_n ($) {
1338     my ($sp)=@_;
1339     die "invalid segment" if $sp =~ m/[^-0-9A-Za-z_]/;
1340     return $sp;
1341 }
1342
1343 sub cva_subsegspec ($) {
1344     my ($sp)=@_;
1345     die "invalid subsegment spec" unless
1346         $sp =~ m,^(\-?)([0-9A-Za-z_]*)(?:/(?:([A-Za-z_]+)(\d+))?)?$,;
1347     my ($sign,$segname,$movfeat,$movconf)=($1,$2,$3,$4);
1348
1349     if (!exists $ctx->{SegName}) {
1350         $segname= '';
1351         $sign= '';
1352     } else {
1353         my ($map_ctx);
1354         
1355         $ctx->{SegName} =~ m/^\-?/ or die;
1356         $sign .= $&;
1357         $segname= $'.$segname;
1358         
1359         for ($map_ctx= $ctx;
1360              defined $map_ctx;
1361              $map_ctx= $map_ctx->{Parent}) {
1362             if (defined $movfeat &&
1363                 exists $map_ctx->{SegMapNM}{"$segname/$movfeat"}) {
1364                 $movfeat= $map_ctx->{SegMapNM}{"$segname/$movfeat"};
1365             }
1366             if (exists $map_ctx->{SegMapN}{$segname}) {
1367                 $map_ctx->{SegMapN}{$segname} =~ m/^\-?/ or die;
1368                 $sign .= $&;
1369                 $segname= $';
1370             }
1371         }
1372         $sign =~ s/\-\-//g;
1373     }
1374
1375     return $sign.$segname.'/'.
1376         (defined $movfeat ? sprintf "%s%d", $movfeat, $movconf : '');
1377 }
1378
1379 sub cmd_segment {
1380     my ($csss,$length);
1381     $ctx->{SavedSegment}= pop @segments
1382         unless exists $ctx->{SavedSegment};
1383     @segments= ();
1384     while (@al>1) {
1385         $csss= can(\&cva_subsegspec);
1386         $length= can(\&cva_len);
1387         push @segments, $csss, $length;
1388     }
1389     $csss= can(\&cva_subsegspec);
1390     push @segments, $csss;
1391 }
1392
1393 sub cva_segmap_s {
1394     my ($sp) = @_;
1395     $sp =~ m,^\w+(?:/[a-zA-Z_]+)?$,
1396         or die "invalid (sub)segment mapping S \`$sp'";
1397     return $sp;
1398 }
1399
1400 sub cva_segmap_n {
1401     my ($sp) = @_;
1402     $sp =~ m,^\-?\w+$, or die "invalid segment mapping N' \`$sp'";
1403     return $sp;
1404 }
1405     
1406 sub cva_segmap_m {
1407     my ($sp) = @_;
1408     $sp =~ m,^[a-zA-Z_]+$, or die "invalid segment mapping M' \`$sp'";
1409     return $sp;
1410 }
1411
1412 sub cmd_segmap {
1413     my ($s,$d);
1414     while (@al) {
1415         $s= can(\&cva_segmap_s);
1416         if ($s =~ m,/,) {
1417             $ctx->{SegMapNM}{$s}= can(\&cva_segmap_m);
1418         } else {
1419             $ctx->{SegMapN}{$s}= can(\&cva_segmap_n);
1420         }
1421     }
1422 }
1423
1424 sub cmd_segcmap {
1425     my ($seg,$colour);
1426     $seg= can(\&cva_segment);
1427     $segcmap{$seg}= "@al";
1428     @al= ();
1429 };
1430
1431 sub cmd_segend {
1432     my ($from,$sp) = @_;
1433     $from= can(\&cva_idex);
1434     $sp= can(\&cva_segment_n);
1435 #print STDERR "setting $from ".join('|',keys %$from),"<\n";
1436     push @{ $seggraphends{$sp} }, $from;
1437 };
1438
1439 sub layer_draw ($$) {
1440     my ($k,$l) = @_;
1441     my ($eo,$cc, $r);
1442     if ($k eq '') {
1443         $r= 'RLMN';
1444     } elsif ($k eq 's') {
1445         $r= '';
1446     } elsif ($k eq 'l') {
1447         $r= 'CLMN';
1448     } else {
1449         $r= 'ARSCLMNO';
1450     }
1451     foreach $eo (@eopts) {
1452 #print STDERR "$. layer $k$l eo $eo re $eo->{GlobRe} then $eo->{DrawMods} now $r\n";
1453         next unless $k =~ m/^$eo->{GlobRe}$/;
1454 #print STDERR "$. layer $k$l eo re $eo->{GlobRe} match\n";
1455         next unless &{ $eo->{LayerCheck} }($l);
1456 #print STDERR "$. layer $k$l eo re $eo->{GlobRe} checked\n";
1457         foreach $cc (split //, $eo->{DrawMods}) {
1458             $r =~ s/$cc//ig;
1459             $r .= $cc if $cc =~ m/[A-Z]/;
1460         }
1461     }
1462 #print STDERR "layer $k$l gives $r (before map)\n";
1463     $r= &{ $ctx->{DrawMap} }($r);
1464     return $r;
1465 }
1466
1467 sub cmd_layer {
1468     my ($kl, $k,$l);
1469     $kl= can(\&cva_identity);
1470     $kl =~ m/^([A-Za-z_]*)(\d*|\=|\*)$/ or die "invalid layer spec";
1471     ($k,$l)=($1,$2);
1472     $l= $output_layer if $l eq '*';
1473     $l= $ctx->{Layer}{Level} if $l =~ m/^\=?$/;
1474     $ctx->{Layer}{Kind}= $k;
1475     $ctx->{Layer}{Level}= $l;
1476     $ctx->{Draw}= layer_draw($k,$l);
1477 }    
1478
1479 sub cmd_part { cmd__obj(Part); }
1480 sub cmd_obj { cmd__obj(1); }
1481 sub cmd_objflip { cmd__obj(-1); }
1482
1483 sub cmd__obj ($) {
1484     my ($how)=@_;
1485     my ($obj_id, $ctx_save, $pfx, $actual, $formal_id, $formal, $formcv);
1486     my ($part_name, $ctx_inobj, $obj, $id, $newid, $newpt);
1487     if ($how eq Part) {
1488         $part_name= can(\&cva_idstr);
1489         $how= (@al && $al[0] =~ s/^\^//) ? -1 : +1;
1490     }
1491     $obj_id= can(\&cva_idstr);
1492     if (defined $part_name) {
1493         $formal_id= can(\&cva_idstr);
1494         $actual= cano(\&cva_idex, undef);
1495         if (!defined $actual) {
1496             $actual= cva_idex("${part_name}_${formal_id}");
1497         }
1498     } else {
1499         $actual= can(\&cva_idex);
1500         $formal_id= can(\&cva_idstr);
1501     }
1502     $obj= $objs{$obj_id};
1503     dv("cmd__obj ",'$obj',$obj);
1504     die "unknown obj $obj_id" unless $obj;
1505     $formal= $obj->{Loc}{$formal_id};
1506     die "unknown formal $formal_id" unless $formal;
1507     $ctx_save= $ctx;
1508     newctx($ctx_save);
1509     $how *= $ctx_save->{Trans}{R};
1510     $ctx->{Trans}{R}= $how;
1511     $ctx->{Trans}{A}= $actual->{A} - $formal->{A}/$how;
1512     $formcv= ev_compose({}, $ctx->{Trans},$formal);
1513     $ctx->{Trans}{X}= $actual->{X} - $formcv->{X};
1514     $ctx->{Trans}{Y}= $actual->{Y} - $formcv->{Y};
1515     if (defined $part_name) {
1516         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${part_name}:";
1517     } else {
1518         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}::";
1519     }
1520     if ($segments[0] =~ m,(.*[^-]+)/,) {
1521         $ctx->{SegName}= $1;
1522     }
1523     $ctx->{DrawMap}= sub {
1524         my ($i) = @_;
1525         $i= &{ $ctx_save->{DrawMap} }($i);
1526         if ($obj->{Part}) {
1527             $i =~ s/[LMN]//g;
1528             $i =~ s/O/MNO/;
1529         } else {
1530             $i =~ s/[LM]//g;
1531             $i =~ s/N/MN/;
1532         }
1533         return $i;
1534     };
1535     $ctx->{Draw}= &{ $ctx->{DrawMap} }($ctx_save->{Draw});
1536     cmd__runobj($obj_id);
1537     if (defined $part_name) {
1538         $pfx= $part_name.'_';
1539     } else {
1540         if (@al && $al[0] eq '=') {
1541             $pfx= ''; shift @al;
1542         } else {
1543             $pfx= cano(\&cva_idstr,undef);
1544         }
1545     }
1546     if (exists $ctx->{SavedSegment}) {
1547         @segments= ($ctx->{SavedSegment});
1548     }
1549     $ctx_inobj= $ctx;
1550     $ctx= $ctx_save;
1551     if (defined $pfx) {
1552         foreach $id (keys %{ $ctx_inobj->{Loc} }) {
1553             next if $id eq $formal_id;
1554             $newid= $pfx.$id;
1555             next if exists $ctx_save->{Loc}{$newid};
1556             $newpt= cva_idnew($newid);
1557             %$newpt= %{ $ctx_inobj->{Loc}{$id} };
1558         }
1559     }
1560     if (defined $part_name) {
1561         my ($formalr_id, $actualr_id, $formalr, $actualr);
1562         while (@al) {
1563             die "part results come in pairs\n" unless @al>=2;
1564             ($formalr_id, $actualr_id, @al) = @al;
1565             if ($actualr_id =~ s/^\-//) {
1566                 $formalr_id= "-$formalr_id";
1567                 $formalr_id =~ s/^\-\-//;
1568             }
1569             {
1570                 local ($ctx) = $ctx_inobj;
1571                 $formalr= cva_idex($formalr_id);
1572             }
1573             $actualr= cva_idnew($actualr_id);
1574             %$actualr= %$formalr;
1575         }
1576     }
1577 }
1578
1579 sub cmd__do {
1580     my ($cmd);
1581 dv("cmd__do $ctx @al ",'$ctx',$ctx);
1582     $cmd= can(\&cva_cmd);
1583     my ($lm,$id,$loc,$io,$ad,$draw,$thendrawre);
1584     $io= defined $ctx->{InDefObj} ? "$ctx->{InDefObj}!" : $ctx->{InRunObj};
1585     o("%L cmd   $io $cmd @al\n");
1586     $ctx->{LocsMade}= [ ];
1587     {
1588         no strict 'refs';
1589         &{ "cmd_$cmd" };
1590     };
1591     die "too many args" if @al;
1592     foreach $lm (@{ $ctx->{LocsMade} }) {
1593         $id= $lm->{Id};
1594         $loc= $ctx->{Loc}{$id};
1595         $loc->{A} += $pi if $lm->{Neg};
1596         $ad= ang2deg($loc->{A});
1597         ol("%L point $io$id ".loc2dbg($loc)." ($lm->{Neg})\n");
1598         $draw= layer_draw($loc->{LayerKind}, $ctx->{Layer}{Level});
1599         if ($draw =~ m/[LM]/) {
1600             ol("    gsave\n".
1601                "      $loc->{X} $loc->{Y} translate $ad rotate\n");
1602             if ($draw =~ m/M/) {
1603                 ol("      0 $allwidthmin newpath moveto\n".
1604                    "      0 -$allwidthmin lineto\n".
1605                    "      $lmu_marklw setlinewidth stroke\n");
1606             }
1607             if ($draw =~ m/L/) {
1608                 ol("      /s ($id) def\n".
1609                    "      lf setfont\n".
1610                    "      /sx5  s stringwidth pop\n".
1611                    "      0.5 mul $lmu_txtboxpadx add def\n".
1612                    "      -90 rotate  0 $lmu_txtboxoff translate  newpath\n".
1613                    "      sx5 neg  0             moveto\n".
1614                    "      sx5 neg  $lmu_txtboxh  lineto\n".
1615                    "      sx5      $lmu_txtboxh  lineto\n".
1616                    "      sx5      0             lineto closepath\n".
1617                    "      gsave  1 setgray fill  grestore\n".
1618                    "      $lmu_txtboxlw setlinewidth stroke\n".
1619                    "      sx5 neg $lmu_txtboxpadx add  $lmu_txtboxtxty\n".
1620                    "      moveto s show\n");
1621             }
1622             ol("      grestore\n");
1623         }
1624     }
1625 }
1626
1627 sub cmd_ident {
1628     my ($vs, @lt, $inf, $strft);
1629     $vs= "@al";
1630     $vs= $1 if $vs =~ m/^\$Revision\: ([0-9.]+)\ \$$/;
1631     if (!defined $file_filename) {
1632         $inf= "$vs (unknown file: $file_lineno)";
1633     } elsif (!stat $file_filename ||
1634              !(@lt= localtime((stat _)[9]))) {
1635         $inf= "$file_filename ($1 $!)";
1636     } else {
1637         $strft= strftime "%Y-%m-%d %H:%M:%S +%Z", @lt;
1638         $inf= "$file_filename ($1 $strft)";
1639     }
1640     push @ident_strings, $inf;
1641     @al= ();
1642 }
1643
1644 sub cmd_showlibrary {
1645     my ($obj_id, $y, $x, $ctx_save, $width, $height);
1646     my ($max_x, $min_x, $max_y, $min_y, $nxty, $obj, $loc, $pat, $got, $glob);
1647     my ($adj);
1648     $x=$olu_left; $y=$olu_bottom; undef $nxty;
1649     $ctx_save= $ctx;
1650     foreach $obj_id (sort keys %objs) {
1651         $got= 1;
1652         foreach $glob (@al) {
1653             $pat= $glob;
1654             $got= !($pat =~ s/^\!//);
1655             die "bad pat" if $pat =~ m/[^0-9a-zA-Z_*?]/;
1656             $pat =~ s/\*/\.*/g; $pat =~ s/\?/./g;
1657             last if $obj_id =~ m/^$pat$/;
1658             $got= !$got;
1659         }
1660         next unless $got;           
1661         $obj= $objs{$obj_id};
1662         next unless $obj->{Part};
1663         ($min_x, $max_x, $min_y, $max_y) = bbox($obj->{Loc});
1664         newctx($ctx_save);
1665
1666         for (;;) {
1667             $width= $max_x - $min_x;
1668             $height= $max_y - $min_y;
1669             if ($width < $height) {
1670                 $ctx->{Trans}{A}= 0;
1671                 $ctx->{Trans}{X}= $x - $min_x;
1672                 $ctx->{Trans}{Y}= $y - $min_y + $olu_textheight;
1673             } else {
1674                 ($width,$height)=($height,$width);
1675                 $ctx->{Trans}{A}= 0.5 * $pi;
1676                 $ctx->{Trans}{X}= $x + $max_y;
1677                 $ctx->{Trans}{Y}= $y - $min_x + $olu_textheight;
1678             }
1679             $adj= length($obj_id) * $olu_textallowperc - $width;
1680             $adj=0 if $adj<0;
1681             $width += $adj;
1682             $ctx->{Trans}{X} += 0.5 * $adj;
1683             if ($x + $width > $olu_right && defined $nxty) {
1684                 $x= $olu_left;
1685                 $y= $nxty;
1686                 undef $nxty;
1687             } elsif ($y + $height > $olu_top && $y > $olu_bottom) {
1688                 oflushpage();
1689                 $x= $olu_left; $y= $olu_bottom;
1690                 undef $nxty;
1691             } else {
1692                 last;
1693             }
1694         }
1695             
1696         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}//";
1697         $ctx->{Draw}= $ctx_save->{Draw};
1698         cmd__runobj($obj_id);
1699         ol("    gsave\n".
1700            "      /s ($obj_id) def\n".
1701            "      lf setfont\n      ".
1702            ($x + 0.5*$width)." ".($y - $olu_textheight)." moveto\n".
1703            "      s stringwidth pop -0.5 mul  0  rmoveto\n".
1704            "      s show grestore\n");
1705         $x += $width + $olu_gap_x;
1706         upd_max(\$nxty, $y + $height + $olu_gap_y + $olu_textheight);
1707     }
1708     @al= ();
1709     $ctx= $ctx_save;
1710 }
1711
1712 sub cmd__one {
1713     cmd__do();
1714 }
1715
1716 o("%!\n".
1717   "  /lf /Courier-New findfont $lmu_marktpt scalefont def\n".
1718   "  /sf /Courier-Bold findfont $lmu_segtpt scalefont def\n".
1719   "  $ps_page_shift 0 translate 90 rotate\n".
1720   "  gsave\n");
1721
1722 if ($page_x || $page_y) {
1723     o("  /Courier-New findfont 15 scalefont setfont\n".
1724       "  30 30 moveto (${page_x}x${page_y}) show\n");
1725 }
1726
1727 o("  -$ps_page_xmul $page_x mul  -$ps_page_ymul $page_y mul  translate\n".
1728   "  $ptscale $ptscale scale\n");
1729
1730 newctx();
1731
1732 open DEBUG, ($debug ? ">&2" : ">/dev/null") or die $!;
1733
1734 if ($debug) {
1735     select(DEBUG); $|=1;
1736     select(STDOUT); $|=1;
1737 }
1738
1739 $ctx->{Draw}= '';
1740 $ctx->{SegName}= '';
1741
1742 @al= qw(layer 5);
1743 cmd__one();
1744
1745 while (<>) {
1746     $file_lineno++;
1747     if (m/^\#line (\d+)$/) { $file_lineno= $1; next; }
1748     if (m/^\#line (\d+) (.*)$/) {
1749         $file_lineno= $1;
1750         $file_filename= $2;
1751         $file_filename =~ s/^\"(.*)\"$/$1/;
1752         next;
1753     }
1754     next if m/^\s*\#/;
1755     chomp; s/^\s+//; s/\s+$//;
1756     @al= split /\s+/, $_;
1757     next unless @al;
1758     print DEBUG "=== @al\n";
1759     last if $al[0] eq 'eof';
1760     push @{ $ctx->{CmdLog} }, [ @al ] if exists $ctx->{CmdLog};
1761     cmd__one();
1762 }
1763
1764 {
1765     my ($min_x, $max_x, $min_y, $max_y) = bbox($ctx->{Loc});
1766     my ($bboxstr);
1767     if (defined $min_x) {
1768         $bboxstr= sprintf("width  %.2d (%.2d..%2.d)\n".
1769                           "height %.2d (%.2d..%2.d)\n",
1770                           $max_x - $min_x, $min_x, $max_x,
1771                           $max_y - $min_y, $min_y, $max_y);
1772     } else {
1773         $bboxstr= "no locs, no bbox\n";
1774     }
1775     if (!$quiet) { print STDERR $bboxstr; }
1776     $bboxstr =~ s/^/\%L bbox /mg;
1777     o($bboxstr) or die $!;
1778
1779     if ($scale < 1.5) {
1780         my ($tick_x, $tick_y, $ticklen);
1781         $ticklen= 10;
1782         o(sprintf
1783           "    gsave 0.5 setgray 0.33 setlinewidth\n".
1784           "      /regmark {\n".
1785           "        newpath moveto\n".
1786           "        -%d 0 rmoveto %d 0 rlineto\n".
1787           "        -%d -%d rmoveto 0 %d rlineto stroke\n".
1788           "      } def\n",
1789           $ticklen, $ticklen*2, $ticklen, $ticklen, $ticklen*2);
1790         for ($tick_x= $min_x; $tick_x < $max_x; $tick_x += 150) {
1791             for ($tick_y= $min_y; $tick_y < $max_y; $tick_y += 150) {
1792                 o(sprintf "      %f %f regmark\n", $tick_x, $tick_y);
1793             }
1794         }
1795         o("    grestore\n");
1796     }
1797 }
1798
1799 ol("grestore\n");
1800
1801 if (@ident_strings) {
1802     my ($is);
1803     $is= join('; ', @ident_strings);
1804     $is =~ s/[()\\]/\\$&/g;
1805     ol("25 50 moveto".
1806        "/Courier-New findfont 6 scalefont setfont\n".
1807        " ($is) show\n");
1808 }
1809
1810 oflushpage();