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