File: g_subpaths.c

package info (click to toggle)
plotutils 2.6-15
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,040 kB
  • sloc: ansic: 68,670; sh: 20,086; cpp: 12,382; yacc: 2,588; makefile: 838; lex: 137
file content (2313 lines) | stat: -rw-r--r-- 72,873 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
/* This file is part of the GNU plotutils package.  Copyright (C) 1995,
   1996, 1997, 1998, 1999, 2000, 2005, 2008, Free Software Foundation, Inc.

   The GNU plotutils package is free software.  You may redistribute it
   and/or modify it under the terms of the GNU General Public License as
   published by the Free Software foundation; either version 2, or (at your
   option) any later version.

   The GNU plotutils package is distributed in the hope that it will be
   useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along
   with the GNU plotutils package; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin St., Fifth Floor,
   Boston, MA 02110-1301, USA. */

/* This file contains all of libplot's low-level code for constructing and
   manipulating paths, both simple and compound.  It includes functions
   that construct polygonal and Bezier approximations to a given path.
   They are used by Plotters whose output format does not support all of
   libplot's graphics primitives. */

/* E.g., _fakearc() draws polygonal approximations to circular and elliptic
   quarter-arcs.  Each polygonal approximation will contain
   2**NUM_ARC_SUBDIVISIONS line segments.
   
   Similarly, polygonal approximations to quadratic and cubic Beziers will
   contain no more than 2**MAX_NUM_BEZIER2_SUBDIVISIONS and
   2**MAX_NUM_BEZIER3_SUBDIVISIONS line segments.  However, each bisection
   algorithm used for drawing a Bezier normally usually its recursion based
   on a relative flatness criterion (see below). */

#include "sys-defines.h"
#include "extern.h"
#include "g_arc.h"		/* for chord table */

/* Number of times a circular arc or quarter-ellipse will be recursively
   subdivided.  Two raised to this power is the number of line segments
   that the polygonalization will contain. */

/* NOTE: the maximum allowed value for NUM_ARC_SUBDIVISIONS is
   TABULATED_ARC_SUBDIVISIONS (i.e., the size of the chordal deviation
   table for a quarter-circle or quarter-ellipse, defined in g_arc.h). */
#define NUM_ARC_SUBDIVISIONS 5

/* Maximum number of times quadratic and cubic Beziers will be recursively
   subdivided.  For Beziers we use an adaptive algorithm, in which
   bisection stops when a specified relative flatness has been reached.
   But these parameters provide a hard cutoff, which overrides the relative
   flatness end condition. */
#define MAX_NUM_BEZIER2_SUBDIVISIONS 6
#define MAX_NUM_BEZIER3_SUBDIVISIONS 7

/* The relative flatness parameters. */
#define REL_QUAD_FLATNESS 5e-4
#define REL_CUBIC_FLATNESS 5e-4

#define DATAPOINTS_BUFSIZ PL_MAX_UNFILLED_PATH_LENGTH
#define DIST(p0,p1) (sqrt( ((p0).x - (p1).x)*((p0).x - (p1).x) \
			  + ((p0).y - (p1).y)*((p0).y - (p1).y)))

#define MIDWAY(x0, x1) (0.5 * ((x0) + (x1)))

/* forward references */
static void _prepare_chord_table (double sagitta, double custom_chord_table[TABULATED_ARC_SUBDIVISIONS]);
static void _fakearc (plPath *path, plPoint p0, plPoint p1, int arc_type, const double *custom_chord_table, const double m[4]);

/* ctor for plPath class; constructs an empty plPath, with type set to
   PATH_SEGMENT_LIST (default type) */
plPath *
_new_plPath (void)
{
  plPath *path;
  
  path = (plPath *)_pl_xmalloc (sizeof (plPath));

  path->type = PATH_SEGMENT_LIST;
  path->segments = (plPathSegment *)NULL;
  path->segments_len = 0;	/* number of slots allocated */
  path->num_segments = 0;	/* number of slots occupied */

  path->primitive = false;
  path->llx = DBL_MAX;
  path->lly = DBL_MAX;
  path->urx = -(DBL_MAX);
  path->ury = -(DBL_MAX);

  return path;
}
  
/* dtor for plPath class */
void
_delete_plPath (plPath *path)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type == PATH_SEGMENT_LIST 
      && path->segments_len > 0) /* number of slots allocated */
    free (path->segments);
  free (path);
}

/* reset function for plPath class */
void
_reset_plPath (plPath *path)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type == PATH_SEGMENT_LIST 
      && path->segments_len > 0) /* number of slots allocated */
    free (path->segments);
  path->segments = (plPathSegment *)NULL;
  path->segments_len = 0;
  path->type = PATH_SEGMENT_LIST; /* restore to default */
  path->num_segments = 0;
  
  path->primitive = false;
  path->llx = DBL_MAX;
  path->lly = DBL_MAX;
  path->urx = -(DBL_MAX);
  path->ury = -(DBL_MAX);
}

void
_add_moveto (plPath *path, plPoint p)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments > 0)
    return;
  
  /* empty, so allocate a segment buffer */
  path->segments = (plPathSegment *) 
    _pl_xmalloc (DATAPOINTS_BUFSIZ * sizeof(plPathSegment));
  path->segments_len = DATAPOINTS_BUFSIZ;
  
  path->segments[0].type = S_MOVETO;
  path->segments[0].p = p;
  path->num_segments = 1;
  
  path->llx = p.x;
  path->lly = p.y;
  path->urx = p.x;
  path->ury = p.y;
}

void
_add_line (plPath *path, plPoint p)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
  
  if (path->num_segments == 0)
    /* empty, so allocate a segment buffer */
    {
      path->segments = (plPathSegment *) 
	_pl_xmalloc (DATAPOINTS_BUFSIZ * sizeof(plPathSegment));
      path->segments_len = DATAPOINTS_BUFSIZ;
    }
  
  if (path->num_segments == path->segments_len)
    /* full, so reallocate */
    {
      path->segments = (plPathSegment *) 
	_pl_xrealloc (path->segments, 
			2 * path->segments_len * sizeof(plPathSegment));
      path->segments_len *= 2;
    }
  
  path->segments[path->num_segments].type = S_LINE;
  path->segments[path->num_segments].p = p;
  path->num_segments++;
  
  path->llx = DMIN(path->llx, p.x);
  path->lly = DMIN(path->lly, p.y);
  path->urx = DMAX(path->urx, p.x);
  path->ury = DMAX(path->ury, p.y);
}

void
_add_closepath (plPath *path)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
  
  if (path->num_segments == 0)	/* meaningless */
    return;
  
  if (path->num_segments == path->segments_len)
    /* full, so reallocate */
    {
      path->segments = (plPathSegment *) 
	_pl_xrealloc (path->segments, 
			2 * path->segments_len * sizeof(plPathSegment));
      path->segments_len *= 2;
    }
  
  path->segments[path->num_segments].type = S_CLOSEPATH;
  path->segments[path->num_segments].p = path->segments[0].p;
  path->num_segments++;
}

void
_add_bezier2 (plPath *path, plPoint pc, plPoint p)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
  
  if (path->num_segments == 0)
    /* empty, so allocate a segment buffer */
    {
      path->segments = (plPathSegment *) 
	_pl_xmalloc (DATAPOINTS_BUFSIZ * sizeof(plPathSegment));
      path->segments_len = DATAPOINTS_BUFSIZ;
    }
  
  if (path->num_segments == path->segments_len)
    /* full, so reallocate */
    {
      path->segments = (plPathSegment *) 
	_pl_xrealloc (path->segments, 
			2 * path->segments_len * sizeof(plPathSegment));
      path->segments_len *= 2;
    }
  
  path->segments[path->num_segments].type = S_QUAD;
  path->segments[path->num_segments].p = p;
  path->segments[path->num_segments].pc = pc;
  path->num_segments++;
}

void
_add_bezier3 (plPath *path, plPoint pc, plPoint pd, plPoint p)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
  
  if (path->num_segments == 0)
    /* empty, so allocate a segment buffer */
    {
      path->segments = (plPathSegment *) 
	_pl_xmalloc (DATAPOINTS_BUFSIZ * sizeof(plPathSegment));
      path->segments_len = DATAPOINTS_BUFSIZ;
    }
  
  if (path->num_segments == path->segments_len)
    /* full, so reallocate */
    {
      path->segments = (plPathSegment *) 
	_pl_xrealloc (path->segments, 
			2 * path->segments_len * sizeof(plPathSegment));
      path->segments_len *= 2;
    }
  
  path->segments[path->num_segments].type = S_CUBIC;
  path->segments[path->num_segments].p = p;
  path->segments[path->num_segments].pc = pc;
  path->segments[path->num_segments].pd = pd;
  path->num_segments++;
}

void
_add_arc (plPath *path, plPoint pc, plPoint p1)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
  
  if (path->num_segments == 0)
    /* empty, so allocate a segment buffer */
    {
      path->segments = (plPathSegment *) 
	_pl_xmalloc (DATAPOINTS_BUFSIZ * sizeof(plPathSegment));
      path->segments_len = DATAPOINTS_BUFSIZ;
    }
  
  if (path->num_segments == path->segments_len)
    /* full, so reallocate */
    {
      path->segments = (plPathSegment *) 
	_pl_xrealloc (path->segments, 
			2 * path->segments_len * sizeof(plPathSegment));
      path->segments_len *= 2;
    }
  
  path->segments[path->num_segments].type = S_ARC;
  path->segments[path->num_segments].p = p1;
  path->segments[path->num_segments].pc = pc;
  path->num_segments++;
}

void
_add_ellarc (plPath *path, plPoint pc, plPoint p1)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
  
  if (path->num_segments == 0)
    /* empty, so allocate a segment buffer */
    {
      path->segments = (plPathSegment *) 
	_pl_xmalloc (DATAPOINTS_BUFSIZ * sizeof(plPathSegment));
      path->segments_len = DATAPOINTS_BUFSIZ;
    }
  
  if (path->num_segments == path->segments_len)
    /* full, so reallocate */
    {
      path->segments = (plPathSegment *) 
	_pl_xrealloc (path->segments, 
			2 * path->segments_len * sizeof(plPathSegment));
      path->segments_len *= 2;
    }
  
  path->segments[path->num_segments].type = S_ELLARC;
  path->segments[path->num_segments].p = p1;
  path->segments[path->num_segments].pc = pc;
  path->num_segments++;
}

void
_add_box (plPath *path, plPoint p0, plPoint p1, bool clockwise)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments > 0)
    return;
  
  path->type = PATH_BOX;
  path->p0 = p0;
  path->p1 = p1;
  path->clockwise = clockwise;
  
  path->llx = DMIN(path->llx, p0.x);
  path->lly = DMIN(path->lly, p0.y);
  path->urx = DMAX(path->urx, p0.x);
  path->ury = DMAX(path->ury, p0.y);
  
  path->llx = DMIN(path->llx, p1.x);
  path->lly = DMIN(path->lly, p1.y);
  path->urx = DMAX(path->urx, p1.x);
  path->ury = DMAX(path->ury, p1.y);
}

void
_add_circle (plPath *path, plPoint pc, double radius, bool clockwise)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments > 0)
    return;
  
  path->type = PATH_CIRCLE;
  path->pc = pc;
  path->radius = radius;
  path->clockwise = clockwise;
}

void
_add_ellipse (plPath *path, plPoint pc, double rx, double ry, double angle, bool clockwise)
{
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments > 0)
    return;
  
  path->type = PATH_ELLIPSE;
  path->pc = pc;
  path->rx = rx;
  path->ry = ry;
  path->angle = angle;
  path->clockwise = clockwise;
}

/* Draw a polygonal approximation to the circular arc from p0 to p1, with
   center pc, by calling _fakearc(), which in turn repeatedly calls
   _add_line().  It is assumed that p0 and p1 are distinct.  It is assumed
   that pc is on the perpendicular bisector of the line segment joining
   them, and that the graphics cursor is initially located at p0. */
void
_add_arc_as_lines (plPath *path, plPoint pc, plPoint p1)
{
  /* starting point */
  plPoint p0;
  /* bisection point of arc, and midpoint of chord */
  plPoint pb, pm;
  /* rotation matrix */
  double m[4];
  /* other variables */
  plVector v, v0, v1;
  double radius, sagitta;
  double cross, orientation;
  /* handcrafted relative chordal deviation table, for this arc */
  double custom_chord_table[TABULATED_ARC_SUBDIVISIONS];
  
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
      
  /* determine starting point */
  p0 = path->segments[path->num_segments - 1].p;

  if (p0.x == p1.x && p0.y == p1.y)
    /* zero-length arc, draw as zero-length line segment */
    _add_line (path, p0);

  else
    /* genuine polygonal approximation */
    {
      /* vectors from pc to p0, and pc to p1 */
      v0.x = p0.x - pc.x;
      v0.y = p0.y - pc.y;
      v1.x = p1.x - pc.x;
      v1.y = p1.y - pc.y;
      
      /* cross product, zero if points are collinear */
      cross = v0.x * v1.y - v1.x * v0.y;
      
      /* Compute orientation.  Note libplot convention: if p0, p1, pc are
	 collinear then arc goes counterclockwise from p0 to p1. */
      orientation = (cross >= 0.0 ? 1.0 : -1.0);
      
      radius = DIST(pc, p0);	/* radius is distance to p0 or p1 */
      
      pm.x = 0.5 * (p0.x + p1.x); /* midpoint of chord from p0 to p1 */
      pm.y = 0.5 * (p0.y + p1.y);  
      
      v.x = p1.x - p0.x;	/* chord vector from p0 to p1 */
      v.y = p1.y - p0.y;
      
      _vscale(&v, radius);
      pb.x = pc.x + orientation * v.y; /* bisection point of arc */
      pb.y = pc.y - orientation * v.x;
      
      sagitta = DIST(pb, pm) / radius;
      
      /* fill in entries of chordal deviation table for this user-defined
         sagitta */
      _prepare_chord_table (sagitta, custom_chord_table);
      
      /* call _fakearc(), using for `rotation' matrix m[] a clockwise or
	 counterclockwise rotation by 90 degrees, depending on orientation */

      m[0] = 0.0, m[1] = orientation, m[2] = -orientation, m[3] = 0.0;
      _fakearc (path, p0, p1, USER_DEFINED_ARC, custom_chord_table, m);
    }
}

/* Draw a polygonal approximation to a quarter-ellipse from p0 to p1, by
   calling _fakearc(), which in turn repeatedly calls _add_line().  pc is
   the center of the arc, and p0, p1, pc are assumed not to be collinear.
   It is assumed that the graphics cursor is located at p0 when this
   function is called.

   The control triangle for the elliptic arc will have vertices p0, p1, and
   K = p0 + (p1 - pc) = p1 + (p0 - pc).  The arc will pass through p0 and
   p1, and will be tangent at p0 to the edge from p0 to K, and at p1 to the
   edge from p1 to K. */
void 
_add_ellarc_as_lines (plPath *path, plPoint pc, plPoint p1)
{ 
  plPoint p0;
  plVector v0, v1; 
  double cross;
  double m[4];

  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
      
  /* determine starting point */
  p0 = path->segments[path->num_segments - 1].p;

  /* vectors from pc to p0, and pc to p1 */
  v0.x = p0.x - pc.x;
  v0.y = p0.y - pc.y;
  v1.x = p1.x - pc.x;
  v1.y = p1.y - pc.y;

  /* cross product */
  cross = v0.x * v1.y - v1.x * v0.y;
  if (FROUND(cross) == 0.0)
    /* collinear points, draw line segment from p0 to p1
       (not quite right, could be bettered) */
    _add_line (path, p1);
  else
    {
      /* `rotation' matrix (it maps v0 -> -v1 and v1 -> v0) */
      m[0] = - (v0.x * v0.y + v1.x * v1.y) / cross;
      m[1] = (v0.x * v0.x + v1.x * v1.x) / cross;
      m[2] = - (v0.y * v0.y + v1.y * v1.y) / cross;
      m[3] = (v0.x * v0.y + v1.x * v1.y) / cross;
      
      /* draw polyline inscribed in the quarter-ellipse */
      _fakearc (path, p0, p1, QUARTER_ARC, (double *)NULL, m);
    }
}

/* A function that approximates a circular arc by a cubic Bezier.  The
   approximation used is a standard one.  E.g., a quarter circle extending
   from (1,0) to (0,1), with center (0,0), would be approximated by a cubic
   Bezier with control points (1,KAPPA) and (KAPPA,1).  Here KAPPA =
   (4/3)[sqrt(2)-1] = 0.552284749825, approximately.  The cubic Bezier will
   touch the quarter-circle along the line x=y.

   For a quarter-circle, the maximum relative error in r as a function of
   theta is about 2.7e-4.  The error in r has the same sign, for all theta. */

/* According to Berthold K. P. Horn <bkph@ai.mit.edu>, the general formula
   for KAPPA, for a radius-1 circular arc (not necessary a quarter-circle),

   KAPPA = (4/3)sqrt[(1-cos H)/(1+cos H)] 
   	 = (4/3)[1-cos H]/[sin H] = (4/3)[sin H]/[1+cosH]

   where H is half the angle subtended by the arc.  H=45 degrees for a
   quarter circle.  This is the formula we use. */

/* Louis Vosloo <support@yandy.com> points out that for a quarter-circle,
   the value 0.55228... for KAPPA is, for some purposes, sub-optimal.  By
   dropping the requirement that the quarter-circle and the Bezier touch
   each other along the symmetry line x=y, one can slightly decrease the
   maximum relative error.  He says 0.5541... is the best possible choice.
   He doesn't have an improved value of KAPPA for a general arc, though.  */

void 
_add_arc_as_bezier3 (plPath *path, plPoint pc, plPoint p1)
{ 
  plPoint p0;
  plVector v0, v1;
		  
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
      
  /* determine starting point */
  p0 = path->segments[path->num_segments - 1].p;

  /* vectors to starting, ending points */
  v0.x = p0.x - pc.x;
  v0.y = p0.y - pc.y;
  v1.x = p1.x - pc.x;
  v1.y = p1.y - pc.y;
  
  if ((v0.x == 0.0 && v0.y == 0.0) || (v1.x == 0.0 && v1.y == 0.0)
      || (v0.x == v1.x && v0.y == v1.y))
    /* degenerate case */
    _add_line (path, p1);
  else
    /* normal case */
    {
      double oldangle, newangle, anglerange;
      double cross;
      int orientation;
      
      /* cross product, zero if points are collinear */
      cross = v0.x * v1.y - v1.x * v0.y;
      
      /* Compute orientation.  Note libplot convention: if p0, p1, pc
	 are collinear then arc goes counterclockwise from p0 to p1. */
      orientation = (cross >= 0.0 ? 1 : -1);
	  
      /* compute signed subtended angle */
      oldangle = _xatan2 (v0.y, v0.x);
      newangle = _xatan2 (v1.y, v1.x);
      anglerange = newangle - oldangle;
      if (anglerange > M_PI)
	anglerange -= (2 * M_PI);
      if (anglerange <= -(M_PI))
	anglerange += (2 * M_PI);

      if (FABS(anglerange) > 0.51 * M_PI)
	/* subtended angle > 0.51 * pi, so split arc in two and recurse,
	   since Bezier approximation isn't very good for angles much
	   greater than 90 degrees */
	{
	  double radius;
	  plPoint pb;
	  plVector v;

	  radius = DIST(pc, p0); /* radius is distance to p0 or p1 */
	  
	  v.x = p1.x - p0.x;	/* chord vector from p0 to p1 */
	  v.y = p1.y - p0.y;
	  
	  _vscale(&v, radius);
	  pb.x = pc.x + orientation * v.y; /* bisection point of arc */
	  pb.y = pc.y - orientation * v.x;
	  
	  _add_arc_as_bezier3 (path, pc, pb);
	  _add_arc_as_bezier3 (path, pc, p1);
	}
      else
	/* subtended angle <= 0.51 * pi, so a single Bezier suffices */
	{
	  double halfangle, sinhalf, coshalf, kappa;
	  plPoint pc_bezier3, pd_bezier3;

	  halfangle = 0.5 * FABS(anglerange);
	  sinhalf = sin (halfangle);
	  coshalf = cos (halfangle);
	  /* compute kappa using either of two formulae, depending on
	     numerical stability */
	  if (FABS(sinhalf) < 0.5)
	    kappa = (4.0/3.0) * sinhalf / (1.0 + coshalf);
	  else
	    kappa = (4.0/3.0) * (1.0 - coshalf) / sinhalf;
	  
	  pc_bezier3.x = p0.x - kappa * orientation * v0.y;
	  pc_bezier3.y = p0.y + kappa * orientation * v0.x;
	  pd_bezier3.x = p1.x + kappa * orientation * v1.y;
	  pd_bezier3.y = p1.y - kappa * orientation * v1.x;
	  _add_bezier3 (path, pc_bezier3, pd_bezier3, p1);
	}
    }
}

#define KAPPA_FOR_QUARTER_CIRCLE 0.552284749825

void 
_add_ellarc_as_bezier3 (plPath *path, plPoint pc, plPoint p1)
{ 
  plPoint p0, pc_bezier3, pd_bezier3;
  plVector v0, v1;
		  
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
      
  /* determine starting point */
  p0 = path->segments[path->num_segments - 1].p;

  /* vectors to starting, ending points */
  v0.x = p0.x - pc.x;
  v0.y = p0.y - pc.y;
  v1.x = p1.x - pc.x;
  v1.y = p1.y - pc.y;
  
  /* replace by cubic Bezier, with computed control points */
  pc_bezier3.x = p0.x + KAPPA_FOR_QUARTER_CIRCLE * v1.x;
  pc_bezier3.y = p0.y + KAPPA_FOR_QUARTER_CIRCLE * v1.y;
  pd_bezier3.x = p1.x + KAPPA_FOR_QUARTER_CIRCLE * v0.x;
  pd_bezier3.y = p1.y + KAPPA_FOR_QUARTER_CIRCLE * v0.y;
  _add_bezier3 (path, pc_bezier3, pd_bezier3, p1);
}

/* Approximate a quadratic Bezier by a polyline: standard deCasteljau
   bisection algorithm.  However, we stop subdividing when an appropriate
   metric of the quadratic Bezier to be drawn is sufficiently small.  If
   (p0,p1,p2) defines the quadratic Bezier, we require that the length of
   p0-2*p1+p2 be less than REL_QUAD_FLATNESS times the distance between the
   endpoints of the original Bezier. */

void
_add_bezier2_as_lines (plPath *path, plPoint pc, plPoint p)
{
  plPoint r0[MAX_NUM_BEZIER2_SUBDIVISIONS + 1], r1[MAX_NUM_BEZIER2_SUBDIVISIONS + 1], r2[MAX_NUM_BEZIER2_SUBDIVISIONS + 1];
  int level[MAX_NUM_BEZIER2_SUBDIVISIONS + 1];
  int n = 0;	/* index of top of stack, < MAX_NUM_BEZIER2_SUBDIVISIONS */
  int segments_drawn = 0;
  plPoint p0;
  double sqdist, max_squared_length;
      
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
  
  /* determine starting point */
  p0 = path->segments[path->num_segments - 1].p;
  
  /* squared distance between p0 and p */
  sqdist = (p.x - p0.x) * (p.x - p0.x) + (p.y - p0.y) * (p.y - p0.y);
  max_squared_length = REL_QUAD_FLATNESS * REL_QUAD_FLATNESS * sqdist;

  r0[0] = p0;
  r1[0] = pc;
  r2[0] = p;
  level[0] = 0;
  while (n >= 0)		/* i.e. while stack is nonempty */
    {
      int current_level;
      plPoint q0, q1, q2;
      
      current_level = level[n];
      q0 = r0[n];
      q1 = r1[n];
      q2 = r2[n];
      
      if (current_level >= MAX_NUM_BEZIER2_SUBDIVISIONS) 
	/* to avoid stack overflow, draw as line segment */
	{
	  _add_line (path, q2);
	  segments_drawn++;
	  n--;
	}
      else
	/* maybe bisect the Bezier */
	{
	  plPoint qq0, qq1;
	  plPoint qqq0;
	  plVector vec1;
	  
	  vec1.x = q0.x - 2 * q1.x + q2.x;
	  vec1.y = q0.y - 2 * q1.y + q2.y;
	  
	  if (vec1.x * vec1.x + vec1.y * vec1.y < max_squared_length)
	    /* very flat Bezier, so draw as line segment */
	    {
	      _add_line (path, q2);
	      segments_drawn++;
	      n--;
	    }
	  else
	    /* split Bezier into pair and recurse */
	    /* level[n] >= n is an invariant */
	    {
	      qq0.x = MIDWAY(q0.x, q1.x);
	      qq0.y = MIDWAY(q0.y, q1.y);
	      qq1.x = MIDWAY(q1.x, q2.x);
	      qq1.y = MIDWAY(q1.y, q2.y);
	      
	      qqq0.x = MIDWAY(qq0.x, qq1.x);
	      qqq0.y = MIDWAY(qq0.y, qq1.y);
	      
	      /* first half, deal with next */
	      r0[n+1] = q0;
	      r1[n+1] = qq0;
	      r2[n+1] = qqq0;
	      level[n+1] = current_level + 1;
	      
	      /* second half, deal with later */
	      r0[n] = qqq0;
	      r1[n] = qq1;
	      r2[n] = q2;
	      level[n] = current_level + 1;
	      
	      n++;
	    }
	}
    }
}

/* Approximate a cubic Bezier by a polyline: standard deCasteljau bisection
   algorithm.  However, we stop subdividing when an appropriate metric of
   the cubic Bezier to be drawn is sufficiently small.  If (p0,p1,p2,p3)
   defines the cubic Bezier, we require that the lengths of p0-2*p1+p2 and
   p1-2*p2+p3 be less than REL_CUBIC_FLATNESS times the distance between
   the endpoints of the original Bezier. */

void
_add_bezier3_as_lines (plPath *path, plPoint pc, plPoint pd, plPoint p)
{
  plPoint r0[MAX_NUM_BEZIER3_SUBDIVISIONS + 1], r1[MAX_NUM_BEZIER3_SUBDIVISIONS + 1], r2[MAX_NUM_BEZIER3_SUBDIVISIONS + 1], r3[MAX_NUM_BEZIER3_SUBDIVISIONS + 1];
  int level[MAX_NUM_BEZIER3_SUBDIVISIONS + 1];
  int n = 0;	/* index of top of stack, < MAX_NUM_BEZIER3_SUBDIVISIONS */
  int segments_drawn = 0;
  plPoint p0;
  double sqdist, max_squared_length;
  
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments == 0)
    return;
  
  /* determine starting point */
  p0 = path->segments[path->num_segments - 1].p;
  
  /* squared distance between p0 and p */
  sqdist = (p.x - p0.x) * (p.x - p0.x) + (p.y - p0.y) * (p.y - p0.y);
  max_squared_length = REL_CUBIC_FLATNESS * REL_CUBIC_FLATNESS * sqdist;

  r0[0] = p0;
  r1[0] = pc;
  r2[0] = pd;
  r3[0] = p;
  level[0] = 0;
  
  while (n >= 0)		/* i.e. while stack is nonempty */
    {
      int current_level;
      plPoint q0, q1, q2, q3;
      
      current_level = level[n];
      q0 = r0[n];
      q1 = r1[n];
      q2 = r2[n];
      q3 = r3[n];
      
      if (current_level >= MAX_NUM_BEZIER3_SUBDIVISIONS) 
	/* draw line segment, to avoid stack overflow */
	{
	  _add_line (path, q3);
	  segments_drawn++;
	  n--;
	}
      else
	/* maybe bisect the Bezier */
	{
	  plPoint qq0, qq1, qq2;
	  plPoint qqq0, qqq1;
	  plPoint qqqq0;
	  plVector vec1, vec2;
	  
	  vec1.x = q0.x - 2 * q1.x + q2.x;
	  vec1.y = q0.y - 2 * q1.y + q2.y;
	  vec2.x = q1.x - 2 * q2.x + q3.x;
	  vec2.y = q1.y - 2 * q2.y + q3.y;
	  
	  if (vec1.x * vec1.x + vec1.y * vec1.y < max_squared_length
	      && vec2.x * vec2.x + vec2.y * vec2.y < max_squared_length)
	    /* very flat Bezier, so draw as line segment */
	    {
	      _add_line (path, q3);
	      segments_drawn++;
	      n--;
	    }
	  else
	    /* split Bezier into pair and recurse */
	    /* level[n] >= n is an invariant */
	    {
	      qq0.x = MIDWAY(q0.x, q1.x);
	      qq0.y = MIDWAY(q0.y, q1.y);
	      qq1.x = MIDWAY(q1.x, q2.x);
	      qq1.y = MIDWAY(q1.y, q2.y);
	      qq2.x = MIDWAY(q2.x, q3.x);
	      qq2.y = MIDWAY(q2.y, q3.y);
	      
	      qqq0.x = MIDWAY(qq0.x, qq1.x);
	      qqq0.y = MIDWAY(qq0.y, qq1.y);
	      qqq1.x = MIDWAY(qq1.x, qq2.x);
	      qqq1.y = MIDWAY(qq1.y, qq2.y);
	      
	      qqqq0.x = MIDWAY(qqq0.x, qqq1.x);
	      qqqq0.y = MIDWAY(qqq0.y, qqq1.y);
	      
	      /* first half, deal with next */
	      level[n+1] = current_level + 1;
	      r0[n+1] = q0;
	      r1[n+1] = qq0;
	      r2[n+1] = qqq0;
	      r3[n+1] = qqqq0;
	      
	      /* second half, deal with later */
	      level[n] = current_level + 1;
	      r0[n] = qqqq0;
	      r1[n] = qqq1;
	      r2[n] = qq2;
	      r3[n] = q3;
	      
	      n++;
	    }
	}
    }
}
  
void
_add_box_as_lines (plPath *path, plPoint p0, plPoint p1, bool clockwise)
{
  bool x_move_is_first;
  plPoint newpoint;
  
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments > 0)
    return;
  
  _add_moveto (path, p0);
  
  /* if counterclockwise, would first pen motion be in x direction? */
  x_move_is_first = ((p1.x >= p0.x && p1.y >= p0.y)
		     || (p1.x < p0.x && p1.y < p0.y) ? true : false);
  
  if (clockwise)
    /* take complement */
    x_move_is_first = (x_move_is_first == true ? false : true);
  
  if (x_move_is_first)
    {
      newpoint.x = p1.x;
      newpoint.y = p0.y;
    }
  else
    {
      newpoint.x = p0.x;
      newpoint.y = p1.y;
    }
  _add_line (path, newpoint);
  
  _add_line (path, p1);
  
  if (x_move_is_first)
    {
      newpoint.x = p0.x;
      newpoint.y = p1.y;
    }
  else
    {
      newpoint.x = p1.x;
      newpoint.y = p0.y;
    }
  _add_line (path, newpoint);
  
  _add_line (path, p0);
  
  path->primitive = true;	/* flag as flattened primitive */
}

void
_add_ellipse_as_bezier3s (plPath *path, plPoint pc, double rx, double ry, double angle, bool clockwise)
{
  plPoint startpoint, newpoint;
  double theta, costheta, sintheta;
  double xc, yc;
  
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments > 0)
    return;
  
  /* draw ellipse by drawing four elliptic arcs */
  theta = (M_PI / 180.0) * angle; /* convert to radians */
  costheta = cos (theta);
  sintheta = sin (theta);
  
  xc = pc.x;
  yc = pc.y;
  startpoint.x = xc + rx * costheta;
  startpoint.y = yc + rx * sintheta;
  _add_moveto (path, startpoint);
  
  if (clockwise)
    {
      newpoint.x = xc + ry * sintheta;
      newpoint.y = yc - ry * costheta;
    }
  else
    {
      newpoint.x = xc - ry * sintheta;
      newpoint.y = yc + ry * costheta;
    }
  _add_ellarc_as_bezier3 (path, pc, newpoint);
  
  newpoint.x = xc - rx * costheta;
  newpoint.y = yc - rx * sintheta;
  _add_ellarc_as_bezier3 (path, pc, newpoint);
  
  if (clockwise)
    {
      newpoint.x = xc - ry * sintheta;
      newpoint.y = yc + ry * costheta;
    }
  else
    {
      newpoint.x = xc + ry * sintheta;
      newpoint.y = yc - ry * costheta;
    }
  _add_ellarc_as_bezier3 (path, pc, newpoint);
  
  _add_ellarc_as_bezier3 (path, pc, startpoint);
  
  path->primitive = true;	/* flag as flattened primitive */
}

void
_add_ellipse_as_ellarcs (plPath *path, plPoint pc, double rx, double ry, double angle, bool clockwise)
{
  plPoint startpoint, newpoint;
  double theta, costheta, sintheta;
  double xc, yc;
  
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments > 0)
    return;
  
  /* draw ellipse by drawing four elliptic arcs */
  theta = (M_PI / 180.0) * angle; /* convert to radians */
  costheta = cos (theta);
  sintheta = sin (theta);
  
  xc = pc.x;
  yc = pc.y;
  startpoint.x = xc + rx * costheta;
  startpoint.y = yc + rx * sintheta;
  _add_moveto (path, startpoint);
  
  if (clockwise)
    {
      newpoint.x = xc + ry * sintheta;
      newpoint.y = yc - ry * costheta;
    }
  else
    {
      newpoint.x = xc - ry * sintheta;
      newpoint.y = yc + ry * costheta;
    }
  _add_ellarc (path, pc, newpoint);
  
  newpoint.x = xc - rx * costheta;
  newpoint.y = yc - rx * sintheta;
  _add_ellarc (path, pc, newpoint);
  
  if (clockwise)
    {
      newpoint.x = xc - ry * sintheta;
      newpoint.y = yc + ry * costheta;
    }
  else
    {
      newpoint.x = xc + ry * sintheta;
      newpoint.y = yc - ry * costheta;
    }
  _add_ellarc (path, pc, newpoint);
  
  _add_ellarc (path, pc, startpoint);
  
  path->primitive = true;	/* flag as flattened primitive */
}

void
_add_ellipse_as_lines (plPath *path, plPoint pc, double rx, double ry, double angle, bool clockwise)
{
  plPoint startpoint, newpoint;
  double theta, costheta, sintheta;
  double xc, yc;
  
  if (path == (plPath *)NULL)
    return;
  
  if (path->type != PATH_SEGMENT_LIST || path->num_segments > 0)
    return;
  
  /* draw ellipse by drawing four fake elliptic arcs */
  theta = (M_PI / 180.0) * angle; /* convert to radians */
  costheta = cos (theta);
  sintheta = sin (theta);
  
  xc = pc.x;
  yc = pc.y;
  startpoint.x = xc + rx * costheta;
  startpoint.y = yc + rx * sintheta;
  _add_moveto (path, startpoint);
  
  if (clockwise)
    {
      newpoint.x = xc + ry * sintheta;
      newpoint.y = yc - ry * costheta;
    }
  else
    {
      newpoint.x = xc - ry * sintheta;
      newpoint.y = yc + ry * costheta;
    }
  _add_ellarc_as_lines (path, pc, newpoint);
  
  newpoint.x = xc - rx * costheta;
  newpoint.y = yc - rx * sintheta;
  _add_ellarc_as_lines (path, pc, newpoint);
  
  if (clockwise)
    {
      newpoint.x = xc - ry * sintheta;
      newpoint.y = yc + ry * costheta;
    }
  else
    {
      newpoint.x = xc + ry * sintheta;
      newpoint.y = yc - ry * costheta;
    }
  _add_ellarc_as_lines (path, pc, newpoint);
  
  _add_ellarc_as_lines (path, pc, startpoint);
  
  path->primitive = true;	/* flag as flattened primitive */
}

void
_add_circle_as_bezier3s (plPath *path, plPoint pc, double radius, bool clockwise)
{
  if (path == (plPath *)NULL)
    return;
  
  _add_ellipse_as_bezier3s (path, pc, radius, radius, 0.0, clockwise);
  path->primitive = true;	/* flag as flattened primitive */
}

void
_add_circle_as_ellarcs (plPath *path, plPoint pc, double radius, bool clockwise)
{
  if (path == (plPath *)NULL)
    return;
  
  _add_ellipse_as_ellarcs (path, pc, radius, radius, 0.0, clockwise);
  path->primitive = true;	/* flag as flattened primitive */
}

void
_add_circle_as_lines (plPath *path, plPoint pc, double radius, bool clockwise)
{
  if (path == (plPath *)NULL)
    return;
  
  _add_ellipse_as_lines (path, pc, radius, radius, 0.0, clockwise);
  path->primitive = true;	/* flag as flattened primitive */
}

/* The _fakearc() subroutine below, which is called by _add_arc_as_lines()
   and _add_ellarc_as_lines(), contains a remote descendent of the
   arc-drawing algorithm of Ken Turkowski <turk@apple.com> described in
   Graphics Gems V.  His algorithm is a recursive circle subdivision
   algorithm, which relies on the fact that if s and s' are the (chordal
   deviation)/radius associated to (respectively) an arc and a half-arc,
   then s' is approximately equal to s/4.  The exact formula is s' = 1 -
   sqrt (1 - s/2), which applies for all s in the meaningful range, i.e. 0
   <= s <= 2.

   Ken's algorithm rotates the chord of an arc by 90 degrees and scales it
   to have length s'.  The resulting vector will be the chordal deviation
   vector of the arc, which gives the midpoint of the arc, and hence the
   endpoints of each half of the arc.  So this drawing technique is
   recursive.

   The problem with this approach is that scaling a vector to a specified
   length requires a square root, so there are two square roots in each
   subdivision step.  One can attempt to remove one of them by noticing
   that the chord half-length h always satisfies h = sqrt(s * (2-s))).  So
   one can rotate the chord vector by 90 degrees, and multiply its length
   by s/2h, i.e., s/2sqrt(s * (2-s)), to get the chordal deviation vector.
   This factor still includes a square root though.  Also one still needs
   to compute a square root in order to proceed from one subdivision step
   to the next, i.e. to compute s' from s.

   We can get around the square root problem by drawing only circular arcs
   with subtended angle of 90 degrees (quarter-circles), or elliptic arcs
   that are obtained from such quarter-circles by affine transformations
   (so-called quarter-ellipses).  To draw the latter, we need only replace
   the 90 degree rotation matrix mentioned above by an affine
   transformation that maps v0->-v1 and v1->v0, where v0 = p0 - pc and v1 =
   p1 - pc are the displacement vectors from the center of the ellipse to
   the endpoints of the arc.  If we do this, we get an elliptic arc with p0
   and p1 as endpoints. The vectors v0 and v1 are said lie along conjugate
   diameters of the quarter-ellipse.
   
   So for drawing quarter-ellipses, the only initial value of s we need to
   consider is the one for a quarter-circle, which is 1-sqrt(1/2).  The
   successive values of s/2h that will be encountered, after each
   bisection, are pre-computed and stored in a lookup table, found in
   g_arc.h.

   This approach lets us avoid, completely, any computation of square roots
   during the drawing of quarter-circles and quarter-ellipses.  The only
   square roots we need are precomputed.  We don't need any floating point
   divisions in the main loop either.  

   Of course for other angles than 90 degrees, we precompute a chord table
   and pass it to _fakearc().

   The implementation below does not use recursion (we use a local array,
   rather than the call stack, to store the sequence of generated
   points). */

static void 
_fakearc (plPath *path, plPoint p0, plPoint p1, int arc_type, const double *custom_chord_table, const double m[4])
{
  plPoint p[NUM_ARC_SUBDIVISIONS + 1], q[NUM_ARC_SUBDIVISIONS + 1];
  int level[NUM_ARC_SUBDIVISIONS + 1];
  int n = 0;	/* index of top of stack, < NUM_ARC_SUBDIVISIONS */
  int segments_drawn = 0;
  const double *our_chord_table;

  if (arc_type == USER_DEFINED_ARC)
    our_chord_table = custom_chord_table;
  else				/* custom_chord_table arg ignored */
    our_chord_table = _chord_table[arc_type];

  p[0] = p0;
  q[0] = p1;
  level[0] = 0;
  while (n >= 0)		/* i.e. while stack is nonempty */
    {
      if (level[n] >= NUM_ARC_SUBDIVISIONS) 
	{			/* draw line segment */
	  _add_line (path, q[n]);
	  segments_drawn++;
	  n--;
	}
      
      else			/* bisect line segment */
	{
	  plVector v;
	  plPoint pm, pb;
	  
	  v.x = q[n].x - p[n].x; /* chord = line segment from p[n] to q[n] */
	  v.y = q[n].y - p[n].y;
	  
	  pm.x = p[n].x + 0.5 * v.x; /* midpoint of chord */
	  pm.y = p[n].y + 0.5 * v.y;
	  
	  /* Compute bisection point.  If m=[0 1 -1 0] this just rotates
	     the chord clockwise by 90 degrees, and scales it to yield the
	     chordal deviation vector, which is used as an offset. */
	  
	  pb.x = pm.x + 
	    our_chord_table[level[n]] * (m[0] * v.x + m[1] * v.y);
	  pb.y = pm.y + 
	    our_chord_table[level[n]] * (m[2] * v.x + m[3] * v.y);
	  
	  /* replace line segment by pair; level[n] >= n is an invariant */
	  p[n+1] = p[n];
	  q[n+1] = pb;		/* first half, deal with next */
	  level[n+1] = level[n] + 1;
	  
	  p[n] = pb;
	  q[n] = q[n];		/* second half, deal with later */
	  level[n] = level[n] + 1;
	  
	  n++;
	}
    }
}

/* prepare_chord_table() computes the list of chordal deviation factors
   that _fakearc() needs when it is employed to draw a circular arc of
   subtended angle other than the default angles it supports */
static void
_prepare_chord_table (double sagitta, double custom_chord_table[TABULATED_ARC_SUBDIVISIONS])
{
  double half_chord_length;
  int i;

  half_chord_length = sqrt ( sagitta * (2.0 - sagitta) );
  for (i = 0; i < TABULATED_ARC_SUBDIVISIONS; i++)
    {
      custom_chord_table[i] = 0.5 * sagitta / half_chord_length;
      sagitta = 1.0 - sqrt (1.0 - 0.5 * sagitta);
      half_chord_length = 0.5 * half_chord_length / (1.0 - sagitta);
    }
}

/* Flatten a simple path into a path of segment list type, consisting only
   of line segments.  

   As supplied, the path may be perfectly general: it may be a segment list
   (not all segments necessarily being line segments), or be a closed
   primitive (box/circle/ellipse).  If supplied path already consists only
   of line segments (with an initial moveto and possibly a final
   closepath), it is returned unchanged; this can be tested for by
   comparing pointers for equality.  If a new path is returned, it must be
   freed with _delete_plPath(). */

plPath *
_flatten_path (const plPath *path)
{
  plPath *newpath;
  
  if (path == (plPath *)NULL)
    return (plPath *)NULL;

  switch (path->type)
    {
    case PATH_SEGMENT_LIST:
      {
	bool do_flatten = false;
	int i;

	for (i = 0; i < path->num_segments; i++)
	  {
	    if (path->segments[i].type != S_MOVETO
		&& path->segments[i].type != S_LINE
		&& path->segments[i].type != S_CLOSEPATH)
	      {
		do_flatten = true;
		break;
	      }
	  }
	
	if (do_flatten == false)
	  newpath = (plPath *)path; /* just return original path */
	else
	  {
	    newpath = _new_plPath ();
	    for (i = 0; i < path->num_segments; i++)
	      {
		switch ((int)(path->segments[i].type))
		  {
		  case (int)S_MOVETO:
		    _add_moveto (newpath, path->segments[i].p);
		    break;
		  case (int)S_LINE:
		    _add_line (newpath, path->segments[i].p);
		    break;
		  case (int)S_CLOSEPATH:
		    _add_closepath (newpath);
		    break;

		    /* now, the types of segment we flatten: */

		  case (int)S_ARC:
		    _add_arc_as_lines (newpath, 
				       path->segments[i].pc, 
				       path->segments[i].p);
		    break;
		  case (int)S_ELLARC:
		    _add_ellarc_as_lines (newpath, 
					  path->segments[i].pc, 
					  path->segments[i].p);
		    break;
		  case (int)S_QUAD:
		    _add_bezier2_as_lines (newpath, 
					   path->segments[i].pc, 
					   path->segments[i].p);
		    break;
		  case (int)S_CUBIC:
		    _add_bezier3_as_lines (newpath, 
					   path->segments[i].pc, 
					   path->segments[i].pd, 
					   path->segments[i].p);
		    break;
		  default:	/* shouldn't happen */
		    break;
		  }
	      }
	  }
	break;
      }
    case PATH_CIRCLE:
      newpath = _new_plPath ();
      _add_circle_as_lines (newpath, 
			    path->pc, path->radius, path->clockwise);
      break;
    case PATH_ELLIPSE:
      newpath = _new_plPath ();
      _add_ellipse_as_lines (newpath, 
			     path->pc, path->rx, path->ry, path->angle,
			     path->clockwise);
      break;
    case PATH_BOX:
      newpath = _new_plPath ();
      _add_box_as_lines (newpath, path->p0, path->p1, path->clockwise);
      break;
    default:			/* shouldn't happen */
      newpath = _new_plPath ();
      break;
    }
  return newpath;
}

/**********************************************************************/

/* The code below exports the _merge_paths() function, which munges an
   array of plPath objects and returns a new array.  Heuristic
   "path-merging" of this sort is performed in g_endpath.c when filling a
   compound path (i.e., a multi-plPath path), if the output driver supports
   only the filling of single plPaths.  That is the case for nearly all of
   libplot's output drivers.

   `Child' paths are merged into their `parents', so each location in the
   returned array where a child was present will contain NULL.  Also, any
   non-child that had no children will be returned without modification.

   You should take this into account when freeing the returned array of
   plPaths.  Only the elements that are (1) non-NULL, and (2) differ from
   the corresponding elements in the originally passed array should have
   _delete_plPath() invoked on them.  The array as a whole may be
   deallocated by calling free().

   The _merge_paths() function was inspired by a similar function in
   Wolfgang Glunz's pstoedit, which was originally written by Burkhard
   Plaum <plaum@ipf.uni-stuttgart.de>. */

/* Note: a well-formed plPath has the form:
   { moveto { line | arc }* { closepath }? }

   The _merge_paths function was written to merge _closed_ plPath's,
   i.e. ones whose endpoint is the same as the startpoint (possibly
   implicitly, i.e. closepath is allowed).  However, libplot applies it to
   open paths too, in which case an `implicit closepath' is added to the
   path to close it.

   NOTE: The current release of libplot does not yet support `closepath'
   segments at a higher level.  So we regard a pass-in plPath as `closed'
   if its last defining vertex is the same as the first.  THIS CONVENTION
   WILL GO AWAY. */

/* ad hoc structure for an annotated plPath, in particular one that has
   been flattened into line segments and annotated; used only in this file,
   for merging purposes */

typedef struct subpath_struct
{
  plPathSegment *segments;	/* segment array */
  int num_segments;		/* number of segments */

  struct subpath_struct **parents; /* array of pointers to possible parents */
  struct subpath_struct *parent; /* pointer to parent path */
  struct subpath_struct **children; /* array of pointers to child paths */
  int num_children;		/* number of children */

  int num_outside;		/* number of subpaths outside this one */

  double llx, lly, urx, ury;    /* bounding box of the subpath */
  bool inserted;		/* subpath has been inserted into result? */
} subpath;

/* forward references */

/* 0. ctors, dtors */
static subpath * new_subpath (void);
static subpath ** new_subpath_array (int n);
static void delete_subpath (subpath *s);
static void delete_subpath_array (subpath **s, int n);

/* 1. functions that act on a subpath, i.e. an `annotated path' */
static bool is_inside_of (const subpath *s, const subpath *other);
static double _cheap_lower_bound_on_distance (const subpath *path1, const subpath *path2);
static void linearize_subpath (subpath *s);
static void read_into_subpath (subpath *s, const plPath *path);

/* 2. miscellaneous */
static void find_parents_in_subpath_list (subpath **annotated_paths, int num_paths);
static void insert_subpath (plPathSegment *parent_segments, const plPathSegment *child_segments, int parent_size, int child_size, int parent_index, int child_index);
static void _compute_closest (const plPathSegment *p1, const plPathSegment *p2, int size1, int size2, double *distance, int *index1, int *index2);

/**********************************************************************/

/* ctor for subpath class */
static subpath * 
new_subpath (void)
{
  subpath *s;
  
  s = (subpath *)_pl_xmalloc (sizeof (subpath));

  s->segments = (plPathSegment *)NULL;
  s->num_segments = 0;
  s->parents = (subpath **)NULL;
  s->parent = (subpath *)NULL;
  s->children = (subpath **)NULL;
  s->num_children = 0;
  s->num_outside = 0;
  s->llx = DBL_MAX;
  s->lly = DBL_MAX;
  s->urx = -DBL_MAX;
  s->ury = -DBL_MAX;
  s->inserted = false;

  return s;
}
  
/* corresponding ctor for a subpath array */
static subpath **
new_subpath_array (int n)
{
  int i;
  subpath **s;
  
  s = (subpath **)_pl_xmalloc (n * sizeof (subpath *));
  for (i = 0; i < n; i++)
    s[i] = new_subpath ();

  return s;
}
  
/* dtor for subpath class */
static void
delete_subpath (subpath *s)
{
  if (s)
    {
      if (s->segments)
	free (s->segments);
      if (s->children)
	free (s->children);
      if (s->parents)
	free (s->parents);

      free (s);
    }
}

/* corresponding dtor for a subpath array */
static void
delete_subpath_array (subpath **s, int n)
{
  int i;

  if (s)
    {
      for (i = 0; i < n; i++)
	delete_subpath (s[i]);
      free (s);
    }
}

/* replace every segment in a subpath by a lineto (invoked only on a child
   subpath, i.e. a subpath with an identified parent) */
static void 
linearize_subpath (subpath *s)
{
  /* replace first segment (moveto) with a lineto */
  s->segments[0].type = S_LINE;

  /* if final segment is a closepath, also replace with a lineto, back to
     point #0 */
  if (s->segments[s->num_segments-1].type == S_CLOSEPATH)
    {
      s->segments[s->num_segments-1].type = S_LINE;
      s->segments[s->num_segments-1].p = s->segments[0].p;
    }
}

/* Read a sequence of plPathSegments from a plPath into a previously empty
   annotated subpath.  (This is called only after the plPath has been
   flattened, so the segments include no arcs.)

   Because the way in which _merge_paths() is currently called in libplot,
   we need to handle the possibility that the plPath may not be closed.  If
   it isn't, we add a closepath.

   At present, we allow a final lineto to the start vertex to serve the
   same purpose.  THIS IS A LIBPLOT CONVENTION THAT WILL GO AWAY. */

static void
read_into_subpath (subpath *s, const plPath *path)
{
  bool need_to_close = false;
  int i;
  
  /* sanity check */
  if (path->type != PATH_SEGMENT_LIST)
    return;

  /* allocate space for segment array of subpath; add 1 extra slot for
     manual closure, if needed */
  s->segments = (plPathSegment *)_pl_xmalloc((path->num_segments + 1) * sizeof (plPathSegment));
  s->num_segments = path->num_segments;

  /* sanity check */
  if (path->num_segments == 0)
    return;

  /* Is this path closed?  If not, we'll close manually the annotated path
     that we'll construct.  WE CURRENTLY TREAT FINAL = INITIAL AS
     INDICATING CLOSURE. */
  if (path->segments[path->num_segments - 1].type != S_CLOSEPATH
      &&
      (path->segments[path->num_segments - 1].p.x != path->segments[0].p.x
       || path->segments[path->num_segments - 1].p.y != path->segments[0].p.y))
    need_to_close = true;

  /* copy the segments, updating bounding box to take each juncture point
     into account */
  for (i = 0; i < path->num_segments; i++)
    {
      plPathSegment e;
      
      e = path->segments[i];
      s->segments[i] = e;

      if (e.p.x < s->llx)
	s->llx = e.p.x;
      if (e.p.y < s->lly)
	s->lly = e.p.y;
      if (e.p.x > s->urx)
	s->urx = e.p.x;
      if (e.p.y > s->ury)
	s->ury = e.p.y;
    }

  if (need_to_close)
    {
#if 0
      s->segments[path->num_segments].type = S_CLOSEPATH;
#else  /* currently, use line segment instead of closepath */
      s->segments[path->num_segments].type = S_LINE;
#endif
      s->segments[path->num_segments].p = path->segments[0].p;
      s->num_segments++;
    }
}

/* check if a subpath is inside another subpath */
static bool 
is_inside_of (const subpath *s, const subpath *other)
{
  int inside = 0;
  int outside = 0;
  int i;
  
  /* if bbox fails to lie inside the other's bbox, false */
  if (!((s->llx >= other->llx) && (s->lly >= other->lly) &&
	(s->urx <= other->urx) && (s->ury <= other->ury)))
    return false;
  
  /* otherwise, check all juncture points */
  for (i = 0; i < s->num_segments; i++)
    {
      bool point_is_inside;

      if (s->segments[i].type == S_CLOSEPATH)
	/* should have i = num_segments - 1, no associated juncture point */
	continue;

      /* Check if the vertex s->segments[i].p is inside `other'.  Could be
	 done in a separate function, but we inline it for speed. */
      {
	/* These two factors should be small positive floating-point
	   numbers.  They should preferably be incommensurate, to minimize
	   the probability of a degenerate case occurring: two line
	   segments intersecting at the endpoint of one or the other. */
#define SMALL_X_FACTOR (M_SQRT2 * M_PI)
#define SMALL_Y_FACTOR (M_SQRT2 + M_PI)

	/* argument of the now-inlined function (besides `other') */
	plPoint p;
	/* local variables of the now-inlined function */
	int k, crossings;
	/* (x1,y1) is effectively the point at infinity */
	double x1, y1;
	/* (x2,y2) is specified point */
	double x2, y2;
	
	/* argument of the now-inlined function (besides `other') */
	p = s->segments[i].p;
  
	/* (x1,y1) is effectively the point at infinity */
	x1 = (DMAX(p.x, other->urx) 
	      + SMALL_X_FACTOR * (DMAX(p.x, other->urx) 
				  - DMIN(p.x, other->llx)));
	y1 = (DMAX(p.y, other->ury) 
	      + SMALL_Y_FACTOR * (DMAX(p.y, other->ury) 
				  - DMIN(p.y, other->lly)));
	
	/* (x2,y2) is specified point */
	x2 = p.x;
	y2 = p.y;
	
	crossings = 0;
	for (k = 0; k < other->num_segments; k++)
	  {
	    int j;
	    double x3, y3, x4, y4, det, det1, det2;
	    
	    if (other->segments[k].type == S_CLOSEPATH) /* k > 0 */
	      {
		x3 = other->segments[k-1].p.x;
		y3 = other->segments[k-1].p.y;
	      }
	    else
	      {
		x3 = other->segments[k].p.x;
		y3 = other->segments[k].p.y;
	      }
	    
	    j = (k == other->num_segments - 1 ? 0 : k + 1);
	    if (other->segments[j].type == S_CLOSEPATH)
	      continue;
	    
	    x4 = other->segments[j].p.x;
	    y4 = other->segments[j].p.y;
	    
	    /* (x3,y3)-(x4,y4) is a line segment in the closed path */
	    
	    /* Check whether the line segments (x1,y1)-(x2,y2) and
	       (x3-y3)-(x4,y4) cross each other.
	       
	       System to solve is:
	       
	       [p1 + (p2 - p1) * t1] - [p3 + (p4 - p3) * t2] = 0
	       
	       i.e.
	       
	       (x2 - x1) * t1 - (x4 - x3) * t2 = x3 - x1;
	       (y2 - y1) * t1 - (y4 - y3) * t2 = y3 - y1;
	       
	       Solutions are: t1 = det1/det
	                      t2 = det2/det
	       
	       The line segments cross each other (in their interiors) if
	       0.0 < t1 < 1.0 and 0.0 < t2 < 1.0 */
      
	    det = (x2 - x1) * (-(y4 - y3)) - (-(x4 - x3)) * (y2 - y1);
	    if (det == 0.0)
	      /* line segments are parallel; ignore the degenerate case
		 that they might overlap */
	      continue;
      
	    det1 = (x3 - x1) * (-(y4 - y3)) - (-(x4 - x3)) * (y3 - y1);
	    det2 = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1);
	    
	    if ((det<0.0 && (det1>0.0 || det2>0.0 || det1<det || det2<det))
		||
		(det>0.0 && (det1<0.0 || det2<0.0 || det1>det || det2>det)))
	      /* solution for at least one of t1 and t2 is outside the
		 interval [0,1], so line segments do not cross */
	      continue;
       
	    /* We ignore the possibility that t1, t2 are both in the interval
	       [0,1], but
	       (t1 == 0.0) || (t1 == 1.0) || (t2 == 0.0) || (t2 == 1.0).

	       t1 == 0.0 should never happen, if p1 is effectively
	       the point at infinity.

	       So this degenerate case occurs only if the line segment
	       (x1,y1)-(x2,y2) goes through either (x3,y3) or (x4,y4), or
	       the specified point (x2,y2) lies on the line segment
	       (x3,y3)-(x4,y4) that is part of the path. */
      
	    crossings++;
	  }
	
	/* our determination of whether the point is inside the path;
	   before we inlined this function, this was the return value */
	point_is_inside = (crossings & 1) ? true : false;
      }

      /* increment inside,outside depending on whether or not the juncture
	 point was inside the other path */
      if (point_is_inside)
	inside++;
      else
	outside++;
    }

  /* make a democratic decision as to whether the path as a whole is inside
     the other path */
  return (inside > outside ? true : false);
}

/* Find parent (if any) of each subpath in a list of subpaths.  When this
   is invoked, each subpath should consist of an initial moveto, at least
   one lineto, and a closepath (not currently enforced). */

static void 
find_parents_in_subpath_list (subpath **annotated_paths, int num_paths)
{
  int i, j;
  subpath *parent;
  
  /* determine for each subpath the subpaths that are nominally outside it */
  for (i = 0; i < num_paths; i++)
    {
      annotated_paths[i]->parents = new_subpath_array (num_paths);
      for (j = 0; j < num_paths; j++)
	{
	  if (j != i)
	    {
	      if (is_inside_of (annotated_paths[i], annotated_paths[j]))
		{
		  annotated_paths[i]->parents[annotated_paths[i]->num_outside] = 
		    annotated_paths[j];
		  annotated_paths[i]->num_outside++;
		}
	    }
	}
    }

  /* Now find the real parent subpaths, i.e. the root subpaths.  A subpath
     is a parent subpath if the number of nominally-outside subpaths is
     even, and is a child subpath only if the number is odd.  An odd
     number, together with a failure to find a suitable potential parent,
     will flag a path as an isolate: technically a parent, but without
     children. */

  for (i = 0; i < num_paths; i++)
    {
      if ((annotated_paths[i]->num_outside & 1) == 0)
	/* an even number of subpaths outside, definitely a parent
	   (i.e. doesn't have a parent itself, may or may not have children) */
	{
	  /* allocate space for children (if any) */
	  annotated_paths[i]->children = new_subpath_array (num_paths);
	}
    }
  
  /* now determine which are children, and link them to their parents */

  for (i = 0; i < num_paths; i++)
    {
      if ((annotated_paths[i]->num_outside & 1) == 0)
	/* even number outside, definitely a parent subpath (whether it has
           children remains to be determined) */
	continue;
      else
	/* odd number outside, possibly a child, so search linearly through
	   possible parents until we get a hit; if so, this is a child; if
	   not, this is an isolate (classed as a parent) */
	{
	  for (j = 0; j < annotated_paths[i]->num_outside; j++)
	    {
	      if (annotated_paths[i]->num_outside == 
		  annotated_paths[i]->parents[j]->num_outside + 1)
		/* number outside is one more than the number outside a
		   potential parent; flag as a child, and add it to the
		   parent's child list */
		{
		  parent = annotated_paths[i]->parents[j];
		  annotated_paths[i]->parent = parent; /* give it a parent */
		  parent->children[parent->num_children] = annotated_paths[i];
		  parent->num_children++;
		  break;
		}
	    }
	}
    }
}

/* Compute closest vertices in two paths.  Indices of closest vertices, and
   (squared) distance between them, are returned via pointers.

   This is invoked in _merge_paths() only on paths that have been
   flattened, and have had the initial moveto and the optional final
   closepath replaced by line segments.  So when this is called, each
   segment type is S_LINE. */

static void
_compute_closest (const plPathSegment *p1, const plPathSegment *p2, int size1, int size2, double *distance, int *index1, int *index2)
{
  int best_i = 0, best_j = 0;	/* keep compiler happy */
  double best_distance = DBL_MAX;
  int ii, jj;
  
  for (ii = 0; ii < size1; ii++)
    {
      plPoint point1;
      
      point1 = p1[ii].p;
      for (jj = 0; jj < size2; jj++)
	{
	  double tmp1, tmp2, distance;
	  plPoint point2;
	  
	  point2 = p2[jj].p;
	  tmp1 = point1.x - point2.x;
	  tmp2 = point1.y - point2.y;
	  distance = tmp1 * tmp1 + tmp2 * tmp2;
	  if (distance < best_distance)
	    {
	      best_distance = distance;
	      best_i = ii;
	      best_j = jj;
	    }
	}
    }
  
  /* return the three quantities */
  *distance = best_distance;
  *index1 = best_i;
  *index2 = best_j;
}

/* Compute a cheap lower bound on the (squared) distance between two
   subpaths, by looking at their bounding boxes. */

static double
_cheap_lower_bound_on_distance (const subpath *path1, const subpath *path2)
{
  double xdist = 0.0, ydist = 0.0, dist;
  
  if (path1->urx < path2->llx)
    xdist = path2->llx - path1->urx;
  else if (path2->urx < path1->llx)
    xdist = path1->llx - path2->urx;    
    
  if (path1->ury < path2->lly)
    ydist = path2->lly - path1->ury;
  else if (path2->ury < path1->lly)
    ydist = path1->lly - path2->ury;    

  dist = xdist * xdist + ydist * ydist;

  return dist;
}

/* Insert a closed child subpath into a closed parent, by connecting the
   two, twice, at a specified vertex of the parent path and a specified
   vertex of the child path.  This is the key function invoked by
   _merge_paths().

   Both paths are supplied as segment lists, and all segments are lines;
   the final segment of each is a line back to the starting point.  I.e.,
   for both subpaths, the final vertex duplicates the start vertex.  So we
   ignore the final vertex of the child (but not that of the parent).
   I.e. if the child vertices are numbered 0..child_size-1, we map the case
   child_index = child_size-1 to child_index = 0.

   The new path has parent_size + child_size + 1 vertices, of which the
   last is a repetition of the first. */

  /* INDEX MAP: 

     PARENT -> NEW PATH
       i --> i                (if 0 <= i < parent_index + 1)
       i --> i+child_size+1   (if parent_index + 1 <= i < parent_size)

     CHILD -> NEW PATH
       i --> i+parent_index+child_size-child_index  (0 <= i < child_index+1)
       i --> i+parent_index-child_index+1   (child_index+1 <= i < child_size-1)
       		(0'th element of the child is same as child_size-1 element)

     NEW PATH                        CONTENTS

     0..parent_index	             
                                     0..parent_index of PARENT
     parent_index+1
                                     child_index of CHILD (i.e. ->join)
     parent_index+2..parent_index+child_size-child_index-1
                                     child_index+1..child_size-2 of CHILD
     parent_index+child_size-child_index..parent_index+child_size
                                     0..child_index of CHILD
     parent_index+child_size+1
                                     parent_index of PARENT (i.e. ->join)
     parent_index+child_size+2..parent_size+child_size
                                     parent_index+1..parent_size-1 of PARENT

  */

/* Macros that map from vertices in the child path and the parent path, to
   vertices in the merged path.  Here the argument `i' is the index in the
   original path, and each macro evaluates to the index in the merger.  */

/* The first macro should not be applied to i=child_size-1; as noted above,
   that vertex is equivalent to i=0, so apply it to i=0 instead. */

#define CHILD_VERTEX_IN_MERGED_PATH(i,parent_index,parent_size,child_index,child_size) ((i) <= (child_index) ? (i) + (parent_index) + (child_size) - (child_index) : (i) + (parent_index) - (child_index) + 1)
#define PARENT_VERTEX_IN_MERGED_PATH(i,parent_index,parent_size,child_index,child_size) ((i) <= (parent_index) ? (i) : (i) + (child_size) + 1)


static void 
insert_subpath (plPathSegment *parent, const plPathSegment *child, int parent_size, int child_size, int parent_index, int child_index)
{
  int i;
  plPathSegment e1, e2;
  int src_index;
  
  /* map case when joining vertex is final vertex of child to case when
     it's the 0'th vertex */
  if (child_index == child_size - 1)
    child_index = 0;

  /* move up: add child_size+1 empty slots to parent path */
  for (i = parent_size - 1; i >= parent_index + 1; i--)
    parent[i + child_size + 1] = parent[i];
  
  /* add a line segment from specified vertex of parent path to specified
     vertex of child path */
  e1 = child[child_index];
  e1.type = S_LINE;		/* unnecessary */
  parent[parent_index + 1] = e1;
  
  /* copy vertices of child into parent, looping back to start in child if
     necessary; note we skip the last (i.e. child_size-1'th) vertex, since
     the 0'th vertex is the same */
  src_index = child_index;
  for (i = 0; i < child_size - 1; i++)
    {
      src_index++;
      if (src_index == child_size - 1)
	src_index = 0;
      parent[parent_index + 2 + i] = child[src_index];
    }
  
  /* add a line segment back from specified vertex of child path to
     specified vertex of parent path */
  e2 = parent[parent_index];
  e2.type = S_LINE;
  parent[parent_index + child_size + 1] = e2;
}

/* The key function exported by this module, which is used by libplot for
   filling compound paths. */

plPath **
_merge_paths (const plPath **paths, int num_paths)
{
  int i;
  subpath **annotated_paths;
  plPath **flattened_paths;
  plPath **merged_paths;

  /* flatten every path to a list of line segments (some paths may come
     back unaltered; will be able to compare pointers to check for that) */
  flattened_paths = (plPath **)_pl_xmalloc (num_paths * sizeof(plPath *));
  for (i = 0; i < num_paths; i++)
    {
      flattened_paths[i] = _flatten_path (paths[i]);
#ifdef DEBUG
      fprintf (stderr, "path %d: %d segments, flattened to %d segments\n",
	       i, paths[i]->num_segments, flattened_paths[i]->num_segments);
#endif
    }

  /* Copy each flattened path into a corresponding annotated path
     (`subpath').  Manual closure, if necessary (see above) is performed,
     i.e. we always add a final closepath to close the path.  At this stage
     bounding boxes are computed. */
  annotated_paths = new_subpath_array (num_paths);
  for (i = 0; i < num_paths; i++)
    read_into_subpath (annotated_paths[i], flattened_paths[i]);

  /* Flattened paths no longer needed, so delete them carefully (some may
     be the same as the original paths, due to _flatten_path() having
     simply returned its argument) */
  for (i = 0; i < num_paths; i++)
    if (flattened_paths[i] != paths[i])
      _delete_plPath (flattened_paths[i]);

  /* determine which subpaths are parents, children */
  find_parents_in_subpath_list (annotated_paths, num_paths);

  /* in each child, replace each moveto/closepath by a lineto */
  for (i = 0; i < num_paths; i++)
    if (annotated_paths[i]->parent != (subpath *)NULL)
      /* child path */
      linearize_subpath (annotated_paths[i]);

  /* create array of merged paths: parent paths will have child paths
     merged into them, and child paths won't appear */

  /* allocate space for new array, to be returned */
  merged_paths = (plPath **)_pl_xmalloc (num_paths * sizeof(plPath *));

  for (i = 0; i < num_paths; i++)
    {
      int j, k, num_segments_in_merged_path;
      subpath *parent;
      plPath *merged_path;
      double *parent_to_child_distances;
      int *child_best_indices, *parent_best_indices;

      if (annotated_paths[i]->parent != (subpath *)NULL)
	/* child path; original path will be merged into parent */
	{
	  merged_paths[i] = (plPath *)NULL;
	  continue;
	}

      if (annotated_paths[i]->num_children == 0)
	/* no parent, but no children either, so no merging done; in output
	   path array, place original unflattened path */
	{
	  merged_paths[i] = (plPath *)paths[i];
	  continue;
	}

      /* this path must be a parent, with one or more children to be merged
	 into it; so create new empty `merged path' with segments array
	 that will hold it, and the merged-in children */
      parent = annotated_paths[i];
      num_segments_in_merged_path = parent->num_segments;
      for (j = 0; j < parent->num_children; j++)
	num_segments_in_merged_path 
	  += (parent->children[j]->num_segments + 1);

      merged_path = _new_plPath ();
      merged_path->segments = (plPathSegment *)_pl_xmalloc(num_segments_in_merged_path * sizeof (plPathSegment));
      merged_path->num_segments = 0;
      merged_path->segments_len = num_segments_in_merged_path;

      /* copy parent path into new empty path, i.e. initialize the merged
         path */
      for (j = 0; j < parent->num_segments; j++)
	merged_path->segments[j] = parent->segments[j];
      merged_path->num_segments = parent->num_segments;
      
      /* Create temporary storage for `closest vertex pairs' and inter-path
	 distances.  We first compute the shortest distance between each
	 child path.  We also keep track of the shortest distance between
	 each child and the merged path being constructed, and update it
	 when any child is added.  */

      parent_to_child_distances = (double *)_pl_xmalloc(parent->num_children * sizeof (double));
      parent_best_indices = (int *)_pl_xmalloc(parent->num_children * sizeof (int));
      child_best_indices = (int *)_pl_xmalloc(parent->num_children * sizeof (int));

      /* compute closest vertices between merged path (i.e., right now, the
	 parent) and any child; these arrays will be updated when any child
	 is inserted into the merged path */
      for (j = 0; j < parent->num_children; j++)
	_compute_closest (parent->segments,
			  parent->children[j]->segments,
			  parent->num_segments,
			  parent->children[j]->num_segments,
			  &(parent_to_child_distances[j]),
			  &(parent_best_indices[j]),
			  &(child_best_indices[j]));
      
      for (k = 0; k < parent->num_children; k++)
	/* insert a child (the closest remaining one!) into the built-up
           merged path; and flag the child as having been inserted so that
           we don't pay attention to it thereafter */
	{
	  double min_distance;
	  int closest = 0; /* keep compiler happy */
	  double *new_parent_to_child_distances;
	  int *new_child_best_indices, *new_parent_best_indices;

	  /* allocate storage for arrays that will be used to update the
	     three abovementioned arrays, with each pass through the loop */
	  new_parent_to_child_distances = (double *)_pl_xmalloc(parent->num_children * sizeof (double));
	  new_parent_best_indices = (int *)_pl_xmalloc(parent->num_children * sizeof (int));
	  new_child_best_indices = (int *)_pl_xmalloc(parent->num_children * sizeof (int));

	  /* initially, they're the same as the current arrays */
	  for (j = 0; j < parent->num_children; j++)
	    {
	      new_parent_to_child_distances[j] = parent_to_child_distances[j];
	      new_parent_best_indices[j] = parent_best_indices[j];
	      new_child_best_indices[j] = child_best_indices[j];
	    }

	  /* find closest child to merged path, which has not yet been
             inserted */
	  min_distance = DBL_MAX;
	  for (j = 0; j < parent->num_children; j++)
	    {
	      if (parent->children[j]->inserted) /* ignore this child */
		continue;
	      
	      if (parent_to_child_distances[j] < min_distance)
		{
		  closest = j;
		  min_distance = parent_to_child_distances[j];
		}
	    }
	  
	  /* closest remaining child has index `closest'; it will be
	     inserted into the current merged path */

	  /* loop over all children, skipping inserted ones and also
	     skipping `closest', the next child to be inserted */
	  for (j = 0; j < parent->num_children; j++)
	    {
	      double inter_child_distance;
	      int inter_child_best_index1, inter_child_best_index2;
	      double lower_bound_on_inter_child_distance;
	      bool compute_carefully;

	      if (parent->children[j]->inserted) /* ignore */
		continue;
	      
	      if (j == closest)	/* ignore */
		continue;
	      
	      /* compute distance (and closest vertex pairs) between
		 `closest' and the j'th child; result is only of interest
		 if the distance is less than parent_to_child_distances[j],
		 so we first compute a cheap lower bound on the result by
		 looking at bounding boxes. */

	      lower_bound_on_inter_child_distance = 
		_cheap_lower_bound_on_distance (parent->children[j],
						parent->children[closest]);
	      compute_carefully = 
		(lower_bound_on_inter_child_distance < 
		 parent_to_child_distances[j]) ? true : false;

	      if (compute_carefully)
		/* compute accurate inter-child distance; also which two
		   vertices yield the minimum distance */
		_compute_closest (parent->children[j]->segments,
				  parent->children[closest]->segments,
				  parent->children[j]->num_segments,
				  parent->children[closest]->num_segments,
				  &inter_child_distance,
				  &inter_child_best_index1, /* vertex in j */
				  &inter_child_best_index2); /* in `closest' */
	      
	      /* fill in j'th element of the new arrays
		 parent_to_child_distances[], parent_best_indices[] and
		 child_best_indices[] so as to take the insertion of the
		 child into account; but we don't update the old arrays
		 until we do the actual insertion */

	      if (compute_carefully &&
		  inter_child_distance < parent_to_child_distances[j])
		/* j'th child is nearer to a vertex in `closest', the child
		   to be inserted, than to any vertex in the current merged
		   path, so all three arrays are affected */
		{
		  int nearest_index_in_closest_child;

		  new_parent_to_child_distances[j] = inter_child_distance;
		  new_child_best_indices[j] = inter_child_best_index1;
		  nearest_index_in_closest_child = inter_child_best_index2;
		  
		  /* Compute new value of parent_best_indices[j], taking
		     into account that `closest' will be inserted into the
		     merged path, thereby remapping the relevant index in
		     `closest'.  The macro doesn't perform correctly if its
		     first arg takes the maximum possible value; so
		     instead, we map that possibility to `0'.  See comment
		     above, before the macro definition. */

		  if (nearest_index_in_closest_child == 
		      parent->children[closest]->num_segments - 1)
		    nearest_index_in_closest_child = 0;
		  new_parent_best_indices[j] = 
		    CHILD_VERTEX_IN_MERGED_PATH(nearest_index_in_closest_child,
						parent_best_indices[closest],
						merged_path->num_segments, 
						child_best_indices[closest],
						parent->children[closest]->num_segments);
		}
	      else
		/* j'th child is nearer to a vertex in the current merged
		   path than to any vertex in `closest', the child to be
		   inserted into the merged path */
		{
		  int nearest_index_in_parent;

		  nearest_index_in_parent = parent_best_indices[j];

		  /* compute new value of parent_best_indices[j], taking
		     into account that `closest' will be inserted into the
		     merged path, thereby remapping the relevant index in
		     the merged path */
		  new_parent_best_indices[j] = 
		    PARENT_VERTEX_IN_MERGED_PATH(nearest_index_in_parent,
						 parent_best_indices[closest],
						 merged_path->num_segments, 
						 child_best_indices[closest],
						 parent->children[closest]->num_segments);
		}
	    }
	  
	  /* do the actual insertion, by adding a pair of lineto's between
             closest vertices; flag child as inserted */
	  insert_subpath (merged_path->segments, 
			  parent->children[closest]->segments, 
			  merged_path->num_segments, 
			  parent->children[closest]->num_segments,
			  parent_best_indices[closest],
			  child_best_indices[closest]);
	  merged_path->num_segments += 
	    (parent->children[closest]->num_segments + 1);
	  parent->children[closest]->inserted = true;

	  /* update the old arrays to take insertion into account: replace
             them by the new ones */
	  for (j = 0; j < parent->num_children; j++)
	    {
	      parent_to_child_distances[j] = new_parent_to_child_distances[j];
	      parent_best_indices[j] = new_parent_best_indices[j];
	      child_best_indices[j] = new_child_best_indices[j];
	    }

	  free (new_parent_to_child_distances);
	  free (new_parent_best_indices);
	  free (new_child_best_indices);
	}
      /* End of loop over all children of parent subpath; all >=1 children
	 have now been inserted into the parent, i.e. into the `merged
	 path' which the parent initialized.  However, the merged path's
	 segments are all lines; so change the first to a moveto. */

      merged_path->segments[0].type = S_MOVETO;
      merged_paths[i] = merged_path;

      /* NOTE: SHOULD ALSO REPLACE LAST LINE SEGMENT BY A CLOSEPATH! */

      /* delete temporary storage for `closest vertex pairs' and inter-path
         distances */
      free (parent_to_child_distances);
      free (parent_best_indices);
      free (child_best_indices);
    }
  /* end of loop over parent subpaths */

  /* no more annotated paths needed */
  delete_subpath_array (annotated_paths, num_paths);

  return merged_paths;
}