Random Bits of Open Code

Check-in [163f87e51a]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Cleanup
Timelines: family | ancestors | trunk
Files: files | file ages | folders
SHA1:163f87e51a8d68a13fbc5d307e309fe40d57952c
User & Date: matt 2019-01-02 04:44:33
Context
2019-01-02
04:44
Cleanup Leaf check-in: 163f87e51a user: matt tags: trunk
04:38
fixed couple dumb bugs in geolib check-in: 7fea4e7d8b user: matt tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Deleted geolib/Makefile.

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
# Copyright 2007-2010, Matthew Welland.
#
#  This program is made available under the GNU GPL version 2.0 or
#  greater. See the accompanying file COPYING for details.
#
#  This program is distributed WITHOUT ANY WARRANTY; without even the
#  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#  PURPOSE.

# TARGDIR = $(shell csi -e "(print (car \#\#sys\#include-pathnames))(exit)")

all : uptodate.log tests.log # $(TARGDIR)/geolib.so

uptodate.log : geolib.scm geolib.setup compgeom.scm macros.scm
	chicken-setup | tee uptodate.log

$(TARGDIR)/geolib.so : geolib.so
	@echo installing to $(TARGDIR)
	cp geolib.so $(TARGDIR)

geolib.so : geolib.scm
	csc -s geolib.scm

tests.log : tests.scm uptodate.log
	csi -b tests.scm | tee tests.log
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































Added geolib/README.



>
1
All moved to vg egg

Deleted geolib/compgeom.meta.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
(
; Your egg's license:
(license "LGPL")

; Pick one from the list of categories (see below) for your egg and enter it
; here.
(category misc)

; A list of eggs mpeg3 depends on.  If none, you can omit this declaration
; altogether. If you are making an egg for chicken 3 and you need to use
; procedures from the `files' unit, be sure to include the `files' egg in the
; `needs' section (chicken versions < 3.4.0 don't provide the `files' unit).
; `depends' is an alias to `needs'.
;; (needs sandbox syntax-case)

; A list of eggs required for TESTING ONLY.  See the `Tests' section.
(test-depends test)

(author "Matt Welland")
(synopsis "Primitive argument processor."))
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted geolib/compgeom.scm.

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

;; (declare (unit laedlib))

;; This could really speed things up but does it mess up the gui system?
;; (number-type fixnum)

(use regex srfi-4 extras ezxdisp srfi-1)
(require-library qtree)

;; WARNING These are often overwritten in user code!!

;; TODO
;; 
;; Compile time conditional code for testing for valid input types including:
;;   polygons
;;   layers
;;   polygon lists
;;   point lists

(define *debug* #f)
(define ezx #f)
(define *curr-poly-number* 0)

;; *debug* is either #f or a debug level roughly following the following
;; guidelines

(define (debug-help)
  (print "Debug levels

   bit  adder  purpose
   ---  -----  -------
    1       1  user code
    2       2  top level routines
    3       4  mid level routines
    4       8  low level routines
    5      16  noisy stuff, seldom needed hopefully
    6      32  display work for top level routines
    7      64  display work for mid level routines
    8     128  parameter testing
    9     256  continue on error

Common combinations
    256+128+64      -> 448 mid level display, parameter testing, continue on error
    256+128+64+32   -> 480 all the above and low level display
    256+128+64+32+4 -> 484
"))

(include "macros.scm")

(define *disp-y-scale* -1)
(define *disp-x-scale* 1)
(define *disp-x-offset* 100) 
(define *disp-y-offset* 50) 
;; (debug-run 32 (lambda ()
(define *green*  (make-ezx-color 0 1 0)) 
(define *blue*   (make-ezx-color 0 0 1)) 
(define *black*  (make-ezx-color 0 0 0)) 
(define *red*    (make-ezx-color 1 0 0))
(define *white*  (make-ezx-color 1 1 1))
(define *yellow* (make-ezx-color 1 1 0))
;; ))

;; Data structures and signatures expected

;; Signatures
;;
;; Point (length p) => 2
;; Segment (and (length p) ((car p .... ???
;; Polygon (assq 'points) => #t
;; Layer   (assq 'polys)  => #t
;; Layout  (assq 'layers) => #t

;; Data structures
;;
;; Point    (x y)
;; Segment ((x1 y1) (x2 y2))
;; Polygon (('points ((x1 y1) (x2 y2) ... ))
;;          ('attrib (("net" "n0") ("size" "20x100")))
;;          ('name   ""))
;; Layer   (('polys  (list of polys))
;;          ('attrib (("deleted" "yes")))
;;          ('name   "polyw")
;;          ('color  "0xffee00")
;;          ('stipple "fine dots"))
;; Layout  (('layers ("well" (name "well" ...))) ;; list of layer name layer pairs
;;          ('name   "layout1")
;;          ('attrib (list of attrib)))


;;======================================================================
;; INLINED -- all have been make non-inline 
;;======================================================================
(define (point? pt)
  (if (list? pt)
      (if (eq? 2 (length pt))
          (and (number? (car pt))
               (number? (cadr pt)))
          #f)
      #f))

(define (point-list? lst)
  (if (list? lst)
      (every point? lst)
      #f))

;; We want the offset defined in terms of screen units
(define (internal->screen-x x)
  (+ *disp-x-offset* (* *disp-x-scale* x)))

(define (internal->screen-y y)
  (+ *disp-y-offset* (* *disp-y-scale* y)))

(define (screen->internal-x x)
  (/ (- x *disp-x-offset*) *disp-x-scale*))

(define (screen->internal-y y)
  (/ (- y *disp-y-offset*) *disp-y-scale*))

;;======================================================================
;; UTILS
;;======================================================================

(use regex srfi-4 extras ezxdisp srfi-1)

;; Get the name of any object
(define (get-field obj field)
  (debug-check-param list? obj "ERROR: get-field obj is not a list\n     obj=" obj)
  ;; (debug-print 8 "get-field obj=" obj ",field=" field)
  (let ((key-val (assoc field obj)))
    (if key-val
        (cadr key-val)
        #f)))

(define (delete-field obj field)
  (debug-print 8 "delete-field obj=" obj ",field=" field)
  (if (null? obj)
      obj
      (let loop ((head (car obj))
                 (tail (cdr obj))
                 (result '()))
        (if (null? tail)
            (if (eqv? (car head) field)
                result
                (cons head result))
            (loop (car tail)
                  (cdr tail)
                  (if (eqv? (car head) field)
                      result
                      (cons head result)))))))

(define (set-field obj field value)
  (debug-print 8 "set-field field=" field ",value=" value)
  (cons (list field value) (delete-field obj field)))

(define (keys obj)
  (if (null? obj) '()
      (map car obj)))

(define (in-range-exclusive? a b val)
  (if (> a b)
      (and (< val a)
           (> val b))
      (and (> val a)
           (< val b))))

(define (in-range? a b val)
  (if (> a b)
      (and (<= val a)
           (>= val b))
      (and (>= val a)
           (<= val b))))

(define (unique lst)
  (if (null? lst) '()
      (reverse
       (let loop ((head (car lst))
                  (tail (cdr lst))
                  (result '()))
         (if (null? tail)
             (if (member head result)
                 result
                 (cons head result))
             (loop (car tail)
                   (cdr tail)
                   (if (member head result)
                       result
                       (cons head result))))))))

(define (remove-points lst points)
  (if (null? points)
      lst
      (let loop ((head (car points))
                 (tail (cdr points))
                 (result lst))
        (if (null? tail)
            (delete head result)
            (loop (car tail)(cdr tail)(delete head result))))))

(define (mark-points points color)
  (for-each (lambda (pt)
              (mark-point ezx pt color))
            points))

(define (sort-points points)
  (sort points
   (lambda (a b)
           (< (apply + a) (apply + b)))))

(define (sort-polys polys)
  (sort polys
	(lambda (a b)
	  (< (apply + (car (get-field a 'points))) 
	     (apply + (car (get-field b 'points)))))))

;; NOTE: This is a closed list and only works properly for 
;; an even number of points
(define (list->segments points)
  (debug-check-param point-list? points 
                     "ERROR: list->segments points not a list of points.\n" 
                     "    points=" points)
  (if (< (length points) 2) '()
      (let ((first-point (car points)))
        (let loop ((head (cadr points))
                   (prev (car points))
                   (tail (cddr points))
                   (result '()))
          ;; (print "head=" head ",prev=" prev ",tail=" tail)
          (if (null? tail)
              (begin
                (reverse (cons (list head first-point) 
                               (cons (list prev head)
                                     result))))
              (begin
                (loop (car tail)
                      head
                      (cdr tail)
                      (cons (list prev head) result))))))))

(define (list->points lst)
  (if (> (length lst) 1)
      (let ((x (car lst))
            (y (cadr lst))
            (rem (cddr lst)))
        (append (list (list x y)) (list->points rem)))
      lst))

(define (disp-keep)
  (ezx-redraw ezx)
  (let loop ()
    (let-values ([(b x y) (ezx-sensebutton ezx)])
                (when (not (and (> x 800) (> y 500)))
                      (set! x (inexact->exact (* 5 (round (/ x 5)))))
                      (set! y (inexact->exact (* 5 (round (/ y 5)))))
                      (let ((x-val (screen->internal-x x))
                            (y-val (screen->internal-y y)))
                        (ezx-select-layer ezx 6)
                        (ezx-wipe-layer ezx 6)
                        (ezx-str-2d ezx x y 
                                    (string-append "(" 
                                                   (number->string x-val) "," 
                                                   (number->string y-val) ")")
                                    *black*))
                      (ezx-redraw ezx)
                      (loop))))
    (let loop ()
      (let-values ([(b _ _) (ezx-pushbutton ezx)])
                  (when (zero? b) (loop))))
    (ezx-quit ezx))

;;======================================================================
;; P O I N T S
;;======================================================================

(define (points-good lst)
  (if (null? lst) lst
      (let loop ((head (car lst))
                 (tail (cdr lst))
                 (result '()))
        (if (null? tail)
            (if (point? head)
                (reverse (cons head result))
                (reverse lst))
            (loop (car tail)
                  (cdr tail)
                  (if (point? head)
                      (cons head result)
                      result))))))

(define (mark-point disp pt color)
  (ezx-circle-2d disp (internal->screen-x (car pt)) (internal->screen-y (cadr pt)) 5 color 1))

(define (point-dist pt1 pt2)
  #f)

;;======================================================================
;; S E G M E N T S
;;======================================================================
(define (segment? seg)  
  (if (list? seg)
      (if (eq? 2 (length seg))
          (and (point? (car seg))
               (point? (cadr seg))))))

(define (segment-list? lst)
  (if (list? lst)
      (every segment? lst)
      #f))

(define (draw-segment disp segment color)
  ;; (print "drawing segment " segment)
  (let* ((p1 (car segment))
         (p2 (cadr segment))
         (x1 (internal->screen-x (car p1)))
         (y1 (internal->screen-y (cadr p1)))
         (x2 (internal->screen-x (car p2)))
         (y2 (internal->screen-y (cadr p2))))
    (ezx-line-2d disp x1 y1 x2 y2 color 1)))

(define (draw-list-of-points disp points color)
  (let ((segments (list->segments points)))
    (for-each 
     (lambda (seg)
       (draw-segment disp seg color))
     segments)))

(define (segment-vert? seg)
  (eq? (caar seg) (caadr seg)))

(define (segment-horiz? seg)
  (eq? (cadar seg) (cadadr seg)))

(define (segment-value-in-range-x-exclusive? seg x)
  (in-range-exclusive? (caar seg) (caadr seg) x))

(define (segment-value-in-range-y-exclusive? seg y)
  (in-range-exclusive? (cadar seg) (cadadr seg) y))

(define (segment-value-in-range-x? seg x)
  (in-range? (caar seg) (caadr seg) x))

(define (segment-value-in-range-y? seg y)
  (in-range? (cadar seg)(cadadr seg) y))

(define (segment-cross-points seg1 seg2)
  (debug-check-param segment? seg1
                     "ERROR: segment-cross-points called with seg1 not a segment\n"
                     "    seg1=" seg1)
  (debug-check-param segment? seg2
                     "ERROR: segment-cross-points called with seg2 not a segment\n"
                     "    seg2=" seg2)
  (let* ((a1 (car seg1))
         (a2 (cadr seg1))
         (b1 (car seg2))
         (b2 (cadr seg2))
         (ax1 (car  a1))
         (ay1 (cadr a1))
         (ax2 (car  a2))
         (ay2 (cadr a2))
         (bx1 (car  b1))
         (by1 (cadr b1))
         (bx2 (car  b2))
         (by2 (cadr b2)))
    (if (segment-vert? seg1)
        (if (segment-horiz? seg2) ;; i.e. perpendicular
            (if (and (segment-value-in-range-x? seg2 ax1) 
                     (segment-value-in-range-y? seg1 by1))
                (list (list ax1 by1))
                '())
            (segment-parallel-cross-points seg1 seg2))
        (if (segment-vert? seg2)
            (if (and (segment-value-in-range-x? seg1 bx1)
                     (segment-value-in-range-y? seg2 ay1))
                (list (list bx1 ay1))
                '())
            (segment-parallel-cross-points seg1 seg2)))))

(define (segment-point-on? seg pt)
  (and (segment-value-in-range-x? seg (car pt))
       (segment-value-in-range-y? seg (cadr pt))))

(define (segment-contains-points seg ptlst)
   ;; (print "segment-contains-points seg=" seg ",ptlst=" ptlst)
   (if (or (null? ptlst) (null? seg)) '()
       (let loop ((head (car ptlst))
                  (tail (cdr ptlst))
                  (result '()))
         (let ((pt_in (segment-point-on? seg head))
               (done (null? tail)))
           (cond
            ((and (not done) pt_in)
             (loop (car tail)(cdr tail) (cons pt_in result)))
            ((and done pt_in)
             (cons pt_in result))
            ((not done)
             (loop (car tail) (cdr tail) result))
            (else
             result))))))

(define (segment-parallel-cross-points seg1 seg2)
  ;; (print "segment-parallel-cross-points seg1=" seg1 ",seg2=" seg2)
  (let* ((a1 (car seg1))
         (a2 (cadr seg1))
         (b1 (car seg2))
         (b2 (cadr seg2))
         (ax1 (car  a1))
         (ay1 (cadr a1))
         (ax2 (car  a2))
         (ay2 (cadr a2))

         (bx1 (car  b1))
         (by1 (cadr b1))
         (bx2 (car  b2))
         (by2 (cadr b2)))
    (if (not (or (eq? ax1 bx1) (eq? ay1 by1))) 
        '()
        (unique
         (let loop ((head (car seg1))
                    (tail (append (cdr seg1) seg2))
                    (result '()))
           (if (null? tail)
               (if (and (segment-point-on? seg1 head)
                        (segment-point-on? seg2 head))
                   (cons head result)
                   result)
               (loop (car tail)
                     (cdr tail)
                     (if (and (segment-point-on? seg1 head)
                              (segment-point-on? seg2 head))
                         (cons head result)
                         result))))))))

(define (segment-rhs-in? poly seg)
  (let* ((p1 (car seg))
         (p2 (cadr seg))
         (x1 (car p1))
         (y1 (cadr p1))
         (x2 (car p2))
         (y2 (cadr p2))
         (mid-y #f)
         (mid-x #f)
         (vert (equal? x1 x2))
         (horz (equal? y1 y2)))
    (cond
     ((equal? p1 p2) (set! mid-x #f))
     ((and vert horz) (set! mid-x #f))
      ;; (print "ERROR: Shouldn't get here points: " seg)
     (vert
      (begin
        (set! mid-y (+ (min y1 y2) (/ (abs (- y1 y2)))))
        (set! mid-x (if (< y1 y2) 
                        (+ x1 0.5)
                        (- x1 0.5)))))
     (horz
      (begin
        (set! mid-x (+ (min x1 x2) (/ (abs (- x1 x2)))))
        (set! mid-y (if (< x1 x2)
                        (- y1 0.5)
                        (+ y1 0.5))))))
    (if (and mid-x mid-y)
        (let ((result (poly-point-in? poly (list mid-x mid-y))))
          ;; (print  "seg=" seg " segment-rhs-in? " vert " " horz " " mid-x " " mid-y " with result=" result)
          result)
        #f)))

;;======================================================================
;; P O L Y G O N S
;;======================================================================

;; Complete this... (not debugged nor does it check that the polygon is closed
(define (polygon? poly)
  (if (and (list? poly) (> (length poly) 2))
      (if (and (assq 'points poly)
               (assq 'name  poly)
               (assq 'attrib poly)) ;; all fields required
          (let ((points (get-field poly 'points)))
            ;; (print "Got here with points=" points " (list? points)=" (list? points) " (length points)=" (length points))
            (if (list? points)
                (> (length points) 3)
                #f))
          #f)
      #f))

(define (polygon-list? lst)
  (if (list? lst)
      (every polygon? lst)
      #f))

(define (rect->poly rect) ;; rect is a diagonal segment ((x1 y1)(x2 y2))
  (let* ((p1 (car rect))
         (p2 (cadr rect))
         (x1 (car p1))
         (y1 (cadr p1))
         (x2 (car p2))
         (y2 (cadr p2)))
    (make-polygon (list p1 (list x1 y2) p2 (list x2 y1)))))

;; Draw a polygon on disp
(define (draw-poly disp poly color)
  (for-each (lambda (seg)
              (draw-segment disp seg color))
            (poly-get-segments poly)))

;; Draw a polygon on disp
(define (draw-polys disp polys color)
  (for-each (lambda (p)
              (draw-poly disp p color))
            polys))

(define (label-poly disp poly color)
  (let* ((name   (get-field poly 'name))
         (points (get-field poly 'points))
         (first-pt (car points))
         (x      (car first-pt))
         (y      (cadr first-pt)))
    (ezx-str-2d disp x y name color)))

;; Make a polygon from a list of points
(define (make-polygon points)
  (let* ((segments (list->segments points))
	 (vert-segs (vertical-segments segments)))
    (list (list 'points points) 
	  (list 'segments segments)
	  (list 'vert-segments vert-segs)
	  (list 'name "") 
	  (list 'attrib '()))))

;; Add a point to a polygon 
(define (poly-add-point poly pt)
  (print "WARNING: INCOMPLETE ROUTINE poly-add-point BEING USED!")
  (let ((points (cadr (assq 'points poly)))
        (attrib (cadr (assq 'attrib poly)))
        (name   (cadr (assq 'name   poly))))
    (list (list 'points (append points (list pt)))
          (list 'attrib attrib)
          (list 'name   name))))

(define (poly-extents poly)
  (let* ((points (get-field poly 'points))
         (firstpt (car points))
         (x1   (car firstpt))
         (y1   (cadr firstpt))
         (minx x1)
         (miny y1)
         (maxx x1)
         (maxy y1))
    (for-each 
     (lambda (p)
       (let ((x (car p))
             (y (cadr p)))
         (if (< x minx) (set! minx x))
         (if (< y miny) (set! miny y))
         (if (> x maxx) (set! maxx x))
         (if (> y maxy) (set! maxy y))))
     points)
    (list (list minx miny)(list maxx maxy))))

(define (poly-offset poly x y)
  (debug-check-param polygon? poly
                     "ERROR: poly-offset poly not a polygon.\n"
                     "    poly=" poly)
  (debug-check-param number? x
                     "ERROR: poly-offset x not a number.\n"
                     "    x=" x)
  (debug-check-param number? y
                     "ERROR: poly-offset y not a number.\n"
                     "    y=" y)
  (let ((points (get-field poly 'points)))
    (if (null? points) '()
        (let loop ((head (car points))
                   (tail (cdr points))
                   (result '()))
          (let* ((done (null? tail))
                 (x1   (car head))
                 (y1   (cadr head))
                 (new  (list (+ x1 x) (+ y1 y))))
            (cond
             (done
	      (let* ((new-points (cons new result))
		     (new-segments (list->segments new-points)))
		(set-field 
		 (set-field poly 'points new-points)
		 'segments new-segments)))
             (else
              (loop (car tail) (cdr tail) (cons new result)))))))))
      
(define (poly-get-segments poly)
  (debug-print 4 "poly-get-segments poly=" poly)
  (get-field poly 'segments))

;; add a qtree with x=10 and y from each segment
;; used by point-in-poly?
(define (poly-add-ytree poly)
  (let ((segments (poly-get-segments poly))
	(ytree    (make-qtree:data 0 0 (apply max (apply append (poly-extents poly))))))
    (for-each (lambda (segment)
		(print "segment: " segment)
		(let* ((ys      (sort (map cadr segment) <))
		       (extents (list 10 (car ys) 11 (cadr ys))))
		  (print "ys: " ys " extents: " extents)
		  (qtree:add-obj ytree segment extents)))
	      segments)
    (append poly (list (list 'ytree ytree)))))

(define (poly-crossing-points poly1 poly2)
  (debug-check-param polygon? poly1
                     "ERROR: poly-crossing-points poly1 not a polygon.\n"
                     "    poly1=" poly1)
  (debug-check-param polygon? poly2
                     "ERROR: poly-crossing-points poly2 not a polygon.\n"
                     "    poly2=" poly2)
  (let ((p1-segments (get-field poly1 'segments))
        (p2-segments (get-field poly2 'segments))
        (results '()))
    (for-each 
     (lambda (seg1)
       (for-each 
        (lambda (seg2)
          (set! results (append results (segment-cross-points seg1 seg2))))
        p2-segments))
     p1-segments)
    (unique results)))

;; get list of points from poly2 that are inside poly1
(define (poly-enclosed-points poly1 poly2)
  (let ((points (get-field poly2 'points)))
    (let loop ((head (car points))
               (tail (cdr points))
               (result '()))
      (let ((point-in      (poly-point-in? poly1 head))
            (tail-not-null (not (null? tail))))
        (cond 
         ((and point-in tail-not-null)
          (loop (car tail) (cdr tail) (cons head result)))
         ((and point-in (not tail-not-null))
          (cons head result))
         (tail-not-null (loop (car tail) (cdr tail) result))
         (else result))))))

;; get list of points from poly2 that are inside poly1
;; TODO: rename me and all references...
(define (poly-enclosed-points-inclusive poly1 poly2)
  (let ((points (get-field poly2 'points)))
    (let loop ((head (car points))
               (tail (cdr points))
               (result '()))
      (let ((point-in      (poly-point-touching? poly1 head))
            (tail-not-null (not (null? tail))))
        (cond 
         ((and point-in tail-not-null)
          (loop (car tail) (cdr tail) (cons head result)))
         ((and point-in (not tail-not-null))
          (cons head result))
         (tail-not-null (loop (car tail) (cdr tail) result))
         (else result))))))

(define (poly-vert-segments poly)
  (get-field poly 'vert-segments))

(define (vertical-segments segments)
  (if (null? segments) '()
      (sort 
       (let loop ((head (car segments))
		  (tail (cdr segments))
		  (result '()))
	 (if (null? tail)
	     (if (segment-vert? head) 
		 (cons head result)
		 result)
	     (loop (car tail)
		   (cdr tail)
		   (if (segment-vert? head)
		       (cons head result)
		       result))))
       (lambda (a b)
	 (< (caar a)(caar b))))))

;; point is in (but not on edge), converted to handle non-ortho polygons 
(define (poly-point-in? poly pt)
  (debug-check-param polygon? poly "ERROR: poly-point-in? poly not a polygon\n" "" poly)
  (debug-check-param point? pt "ERROR: poly-point-in? pt is not a point\n" "" pt)
  (let* ((x        (car pt))
         (y        (cadr pt))
	 (segments (filter (lambda (seg)
			     (segment-value-in-range-y? seg y))
			   (poly-get-segments poly)))
	 (extents  (poly-extents poly))
	 (xmin     (- (caar extents)  100))
	 (xmax     (+ (caadr extents) 100))
	 (refline  (list xmin y xmax y))
	 (intersects (map (lambda (segment)
			    (geolib:intersection (apply append segment) refline))
			  segments))
	 (x-intersects (map car (filter (lambda (x) x) intersects)))
	 (intersects-lt-pt-x (filter (lambda (xval)
				       (< x xval)) 
				     x-intersects)))
    (odd? (length intersects-lt-pt-x))))

;; point is in (but not on edge)
(define (orth-poly-point-in? poly pt)
  (debug-check-param polygon? poly "ERROR: poly-point-in? poly not a polygon\n" "" poly)
  (debug-check-param point? pt "ERROR: poly-point-in? pt is not a point\n" "" pt)
  (let* ((vert-segments (poly-vert-segments poly))
         (first-segment (car vert-segments))
         (x (car pt))
         (y (cadr pt)))
    (let loop ((head (car vert-segments))
               (tail (cdr vert-segments))
               (ord 0))
      (let* ((in-range  (segment-value-in-range-y-exclusive? head y))
             (x-less    (< x (caar head)))
             (on-line   (eq? x (caar head)))
             (even-line (even? ord))
             (odd-line  (odd? ord));; not even-line)) ;; (eq? 0 (modulo ord 2))))
             (not-null  (not (null? tail))))
        (debug-print 64 "poly-point-in? ord=" ord ",head=" head ",in-range=" in-range 
                     ",even-line=" even-line ",x-less=" x-less)
        (cond
         ((and in-range on-line) #f)
         ((and in-range x-less even-line) #f)  ;; this is the case of a point to the left of a polygon
         ((and in-range x-less odd-line)  #t)  ;; point is inside 
         ((and not-null in-range)
          (loop (car tail)(cdr tail)(+ ord 1)))
         ((null? tail) #f)   ;; end of the road - must not be in
         (else (loop (car tail) (cdr tail) ord)))))))

;; point is in or touching poly
(define (poly-point-touching? poly pt)
  (let* ((vert-segments (poly-vert-segments poly))
         (sorted-vert-segments (sort vert-segments
                                     (lambda (a b)
                                       (< (caar a)(caar b)))))
         (first-segment (car sorted-vert-segments))
         (x (car pt))
         (y (cadr pt)))
    (let loop ((head (car sorted-vert-segments))
               (tail (cdr sorted-vert-segments))
               (ord 0))
      (let ((in-range  (segment-value-in-range-y? head y))
            (x-less    (< x (caar head)))
            (even-line (eq? 0 (modulo ord 2)))
            (odd-line  (not (eq? 0 (modulo ord 2))))
            (not-null  (not (null? tail))))
        (cond
         ((and in-range x-less even-line) #f)  ;; this is the case of a point to the left of a polygon
         ((and in-range x-less odd-line)  #t)  ;; point is inside 
         ((and not-null in-range)
          (loop (car tail)(cdr tail)(+ ord 1)))
         ((null? tail) #f)   ;; end of the road - must not be in
         (else (loop (car tail) (cdr tail) ord)))))))

;; point inside polygon (but not on edge)
(define (poly-point-in-exclusive? poly pt)
  (let* ((vert-segments (poly-vert-segments poly))
         (sorted-vert-segments (sort vert-segments
                                     (lambda (a b)
                                       (< (caar a)(caar b)))))
         (first-segment (car sorted-vert-segments))
         (x (car pt))
         (y (cadr pt)))
    (let loop ((head (car sorted-vert-segments))
               (tail (cdr sorted-vert-segments))
               (ord 0))
      (let ((in-range  (segment-value-in-range-y-exclusive? head y))
            (x-less    (< x (caar head)))
            (even-line (eq? 0 (modulo ord 2)))
            (odd-line  (not (eq? 0 (modulo ord 2))))
            (not-null  (not (null? tail))))
        (cond
         ((and in-range x-less even-line) #f)  ;; this is the case of a point to the left of a polygon
         ((and in-range x-less odd-line)  #t)  ;; point is inside 
         ((and not-null in-range)
          (loop (car tail)(cdr tail)(+ ord 1)))
         ((null? tail) #f)   ;; end of the road - must not be in
         (else (loop (car tail) (cdr tail) ord)))))))

(define (best-segment-endpoint-and poly1 poly2 start points)
  (let* ((first (car points))
         (remaining (delete start points)))
    ;; (print "first=" first ",remaining=" remaining)
    ;; (print "   points=" points)
    (let loop ((head first)     ;; (car points))
               (tail remaining) ;; (cdr points))
               (alternate #f))
      (let* ((segment (list start head))
             (x       (car start))
             (y       (cadr start))
             (same    (eq? start head))
             (horiz   (segment-horiz? segment))
             (vert    (segment-vert?  segment))
             (rh_in1  (segment-rhs-in? poly1 segment))
             (rh_in2  (segment-rhs-in? poly2 segment)) 
             (double  (and (and (segment-rhs-in? poly1 (reverse segment))
                                rh_in1)
                           (and (segment-rhs-in? poly2 (reverse segment))
                                rh_in2)))
             (clean   (null? (segment-contains-points segment (delete start (delete head points)))))
             (rh_in   (and rh_in1 rh_in2))
             (done    (null? tail)))
        (debug-run 64
                   (lambda ()
                     (ezx-select-layer ezx 2)
                     (ezx-str-2d ezx x y (string-append "(" (number->string x) "," (number->string y) ")") *black*)
                     (draw-segment ezx segment *red*)
                     (ezx-redraw ezx)
                     (dsleep 0.01)
                     (ezx-wipe-layer ezx 2)
                     (ezx-select-layer ezx 0)
                     (print "segment: " segment " same: " same " horiz: "
                            horiz " vert: " vert " rh_in: " rh_in)))
        (cond
         ((and rh_in clean (not double)) ;; choose this one!
          head)
         ((and rh_in clean double (not done))       ;; put this one in the queue if nothing else found
          (loop (car tail)(cdr tail) head))
         ((not done)
          (loop (car tail)(cdr tail) alternate))
         (else
          (if alternate alternate #f))))))) ;; no valid endpoint was found in the list

;; returns
(define (poly-and poly1 poly2)
  (let* ((crossing-points  (poly-crossing-points poly1 poly2))
         (vertex-points    (append (get-field poly1 'points) 
                                   (get-field poly2 'points)))
         (enclosed-points1 (poly-enclosed-points-inclusive poly1 poly2))
         (enclosed-points2 (poly-enclosed-points-inclusive poly2 poly1)))
    ;; We know that all these points *must* be included in the 
    ;; final polys created
    (debug-run
     64 (lambda ()
       ;; (print "crossing-points=" crossing-points)
       ;; (print "vertex-points=" vertex-points)
       (mark-points   (append crossing-points enclosed-points1 enclosed-points2) *black*)
       (draw-poly ezx poly1 *green*)
       (draw-poly ezx poly2 *blue*)))
    (if (and (null? crossing-points)(null? enclosed-points1)(null? enclosed-points2))
        '()
        (begin
          (let loop0 ((all-polys '())
                      (all-points  (append crossing-points enclosed-points1 enclosed-points2)))
            (let loop ((head (car all-points)) ;; create a single polygon in each loop and add it 
                       (leftover (cdr all-points))
                       (first-pt (car all-points))
                       (this-poly (list (car all-points))))
              (let* ((best-pt (best-segment-endpoint-and poly1 poly2 head (cons first-pt leftover)))
                     (done-poly (or (null? leftover) ;; (or (null? tail)           ;; all points accounted for?
                                    (eq? best-pt first-pt) ;; close the polygon
                                    (not best-pt)))        ;; this is where there is no best point
                     (next-leftover (delete best-pt leftover))
                     (done-all  (null? next-leftover))
                     (tmp-polygon (if best-pt (cons best-pt this-poly)
                                      this-poly))
                     (poly-good   (> (length tmp-polygon) 2))
                     (new-polygon (if poly-good tmp-polygon '())))
                (debug-run
                 64 (lambda ()
                      (if (and best-pt head)
                          (draw-segment ezx (list head best-pt) *black*))
                      ;; (print "first-pt=" first-pt ",this-poly=" this-poly ",done-poly=" done-poly ",done-all=" done-all ",best-pt=" best-pt ",head=" head)
                      (ezx-redraw ezx)
                      ;; (system "sleep 0.01")
                      ))
                (cond
                 ((and done-poly done-all)
                  ;; (print "done-poly done-all; next-leftover=" next-leftover)
                  (map make-polygon (cons new-polygon all-polys)))
                 ((and done-poly (not done-all))
                  ;; (print "NOTE: done-poly (not done-all); next-leftover=" next-leftover)
                  (loop0 (cons tmp-polygon all-polys) next-leftover))
                 ((and (not done-poly) (not done-all))
                  ;; (print "(and (not done-poly)(not done-all)); next-leftover=" next-leftover)
                  (loop best-pt next-leftover first-pt tmp-polygon))
                 ((and done-all (not done-poly))
                  ;; (print "done-all (not done-poly) leftover=" leftover ",best-pt=" best-pt ",first-pt=" first-pt)
                  (map make-polygon (if poly-good (cons new-polygon all-polys) all-polys)))
                 (else 
                  (print "ERROR in poly-and done-all=" done-all ",done-poly=" done-poly))))))))))

(define (poly-cut-holes poly holes)
  (debug-check-param polygon? poly "ERROR: poly-cut-holes poly not a polygon " poly)
  (debug-check-param polygon-list? holes "ERROR: poly-cut-holes holes not a list of polygons " holes)
  (debug-print 64 "poly-cut-holes poly=" poly ",holes=" holes)
  (if (null? holes) poly
      (let loop ((hole (car holes))
                 (tail (cdr holes))
                 (result poly))
        (cond
         ((null? tail)
          (poly-cut-hole result hole))
         (loop (car tail) (cdr tail) (poly-cut-hole result hole))))))

;; for now this assumes an existing point in poly to connect the hole to
(define (poly-cut-hole poly hole-poly)
  (debug-check-param polygon? poly "ERROR: poly-cut-hole poly not a polygon " poly)
  (debug-check-param polygon? hole-poly "ERROR: poly-cut-hole hole not a polygon " hole-poly)
  (let ((points  (get-field poly 'points))
        (holes   (get-field hole-poly 'points)))
    (let loop0 ((poly-point (car points))
                (tail0      (cdr points))
                (result    '()))
      (let loop1 ((hole-point (car holes))
                  (tail1      (cdr holes))
                  (new-head  '()))
        (let* ((connecting-segment (list poly-point hole-point))
               (clean (null? (segment-contains-points connecting-segment (delete poly-point (delete hole-point points)))))
               (valid (and (or (segment-horiz? connecting-segment)
                               (segment-vert?  connecting-segment))
                           clean))
               (done-hole (null? tail1))
               (done      (null? tail0)))
          ;; (debug-print 64 "clean=" clean ",connecting-segment=" connecting-segment ",valid=" valid ",done-hole=" done-hole ",done=" done)
          ;; (debug-print 64 "  tail0=" tail0 ",poly-point=" poly-point ",result=" result)
          ;; (debug-print 64 "  tail1=" tail1 ",hole-point=" hole-point ",new-head=" new-head)
          ;; (debug-run 
          ;;  64 (lambda ()
          ;;       (draw-list-of-points ezx result *black*)
          ;;       (draw-list-of-points ezx tail1  *blue*)
          ;;       (draw-list-of-points ezx tail0  *yellow*)))
          (cond 
           (valid
            (set-field poly 'points
                       (append result (list poly-point hole-point) tail1 new-head (list hole-point poly-point) tail0)))
           (done
            (debug-print 64 "ERROR: Shouldn't get here. 123") ;; really? why not?
            poly)
           (done-hole
            (loop0 (car tail0)(cdr tail0)(append result (list poly-point))))
           ((and (not done)(not done-hole))
            (loop1 (car tail1)(cdr tail1)(append (list new-head hole-point))))
           (else 
            (print "ERROR: Shouldn't get here eh"))))))))

;; trim out all the "closest" point crap
(define (best-segment-endpoint-or poly1 poly2 start points)
  (debug-check-param polygon? poly1 "ERROR: best-segment-endpoint-or poly1 not a polygon\n" "" poly1)
  (debug-check-param polygon? poly2 "ERROR: best-segment-endpoint-or poly2 not a polygon\n" "" poly2)
  (let loop ((head (car points))
             (tail (cdr points))
             (alternate #f))
    (let* ((segment (list start head))
           (x       (car start))
           (y       (cadr start))
           (same    (eq? start head))
           (horiz   (segment-horiz? segment))
           (vert    (segment-vert?  segment))
           (rh_in1  (segment-rhs-in? poly1 segment))
           (rh_in2  (segment-rhs-in? poly2 segment)) 
           (r_rh_in1 (segment-rhs-in? poly1 (reverse segment)))
           (r_rh_in2 (segment-rhs-in? poly2 (reverse segment)))
           (double  (and (and r_rh_in1 rh_in1)(and r_rh_in2 rh_in2)))
           (clean   (null? (segment-contains-points segment (delete start (delete head points)))))
           (outside (or (and rh_in1 (not rh_in2) (not r_rh_in2)) ;; case 1 segment of poly1 not including poly2
                        (and rh_in2 (not rh_in1) (not r_rh_in1)) ;; case 2 segment of poly2 not including poly1
                        (and rh_in1 (not r_rh_in1) rh_in2 (not r_rh_in2))))                    ;; case 3 rh_in for both 
           (done    (null? tail)))
      (debug-run
       64 (lambda ()
            (ezx-select-layer ezx 2)
            (ezx-str-2d ezx x y (string-append "(" (number->string x) "," (number->string y) ")") *black*)
            (draw-segment ezx segment *red*)
            (ezx-redraw ezx)
            (dsleep .05)
            (ezx-wipe-layer ezx 2)
            (ezx-select-layer ezx 0)
            (debug-print 64 "segment: " segment " same: " same " horiz: " horiz " vert: " vert " outside: " outside " double: " double " rh_in1: "  rh_in1 " rh_in2: " rh_in2)))
      (cond
       ((and (or same (not clean) (not (or horiz vert))) (not done))
        (loop (car tail) (cdr tail) alternate))
       ((and (or horiz vert) clean outside (not double)) ;; valid segment!!
        head)
       ((and (not done) (or horiz vert) clean outside double) ;; potentially valid segment!!
        (loop (car tail) (cdr tail) head))
       ((not done) 
        (loop (car tail) (cdr tail) alternate))
       (else
        (if alternate alternate #f))))))

(define (poly-or poly1 poly2)
  (debug-check-param polygon? poly1 "ERROR: poly-or poly1 not a polygon\n" "" poly1)
  (debug-check-param polygon? poly2 "ERROR: poly-or poly2 not a polygon\n" "" poly2)
  (if (eq? poly1 poly2) poly1
      (let* ((crossing-points  (poly-crossing-points poly1 poly2))
             (all-points       (sort-points (delete-duplicates (append crossing-points (get-field poly1 'points) (get-field poly2 'points)))))
             (outer-poly       '()))
        (debug-run
         32 (lambda ()
              (begin
                (mark-points all-points *black*)
                (draw-poly ezx poly1 *green*)
                (draw-poly ezx poly2 *yellow*)
                (ezx-redraw ezx)
                )))
        (let loop ((first-pt (car all-points))  (curr-pt (car all-points))  (tail (cdr all-points))
                   (holes    '())
                   (outer-poly '())
                   (unused   '())
                   (outer     #t)
                   (this-poly '())) ;; (list (car all-points))))
            (let* ((leftover (append unused tail))
                   (best-pt (best-segment-endpoint-or poly1 poly2 curr-pt (cons first-pt leftover)))
                   (done-poly (or (null? tail)
                                  (eq? best-pt first-pt))) ;; close the polygon
                              ;;    (not best-pt)))        ;; this is where there is no best point
                   (remaining (delete best-pt leftover))
                   (done-all  (null? remaining))
                   (new-poly  (if best-pt (cons curr-pt this-poly) this-poly)))
              (debug-run 32 (lambda () 
                              (if best-pt (draw-segment ezx (list curr-pt best-pt) *black*))
                              (ezx-redraw ezx)(dsleep .11)))
              (cond
               ((and done-all (not done-poly)) ;; this is the case of a simple polygon result
                (make-polygon new-poly))
               ((and done-poly done-all)
                (if (null? holes) 
                    (make-polygon outer-poly)
                    (let* ((all-holes (map make-polygon (if (null? new-poly) holes (cons new-poly holes))))
                           (final-poly (poly-cut-holes (make-polygon outer-poly) all-holes)))
                      ;; (debug)
                      final-poly)))
               ((and best-pt done-poly (not done-all)) ;; valid poly
                ;; (debug)
                ;; (let ((adj-poly (if (equal? first-pt (car new-poly)) new-poly (cons first-pt new-poly))))
                (loop (car remaining) (car remaining) (cdr remaining)
                      (if outer holes (cons new-poly holes))
                      (if outer new-poly outer-poly) ;; add first-point which is lost due to this being a hole !???
                      '()
                      #f ;; always must switch to holes mode
                      '()))
               ((and best-pt (not done-poly) (not done-all))
                (loop first-pt best-pt remaining ;; best-pt becomes curr-pt
                      holes
                      outer-poly
                      unused
                      outer
                      new-poly))
               ((not best-pt) ;; this point doesn't connect to anything
                (loop (car remaining) (car remaining) (cdr remaining)
                      holes
                      outer-poly
                      unused
                      outer
                      this-poly))
               (else 
                (print "ERROR poly-or: done-all=" done-all ",done-poly=" done-poly))))))))
            
(define (poly-or-prev poly1 poly2)
  (debug-check-param polygon? poly1 "ERROR: poly-or poly1 not a polygon\n" "" poly1)
  (debug-check-param polygon? poly2 "ERROR: poly-or poly2 not a polygon\n" "" poly2)
  (if (eq? poly1 poly2) poly1
      (let* ((crossing-points  (poly-crossing-points poly1 poly2))
             (orig-all-points  (append crossing-points (get-field poly1 'points) (get-field poly2 'points)))
             (enclosed-points  (append (poly-enclosed-points poly1 poly2) (poly-enclosed-points poly2 poly1)))
             (clean-points     (delete-duplicates (sort-points orig-all-points))) ;; (remove-points orig-all-points enclosed-points))))
             (outer-poly       '()))
        ;; (print "poly-or poly1=" poly1 ",poly2=" poly2)
        ;; (print "clean-points=" clean-points ",all-points=" all-points ",enclosed-points=" enclosed-points)
        (debug-run
         64 (lambda ()
              (begin
                (mark-points clean-points *black*)
                (draw-poly ezx poly1 *green*)
                (draw-poly ezx poly2 *yellow*)
                (ezx-redraw ezx)
                )))
        (let loop0 ((holes '())
                    (all-points clean-points)
                    (outer #t))
          (let loop ((head (car all-points)) ;; create a single polygon in each loop and add it 
                     (leftover (cdr all-points))
                     (first-pt (car all-points))
                     (this-poly (list (car all-points))))
            (let* ((best-pt (best-segment-endpoint-or poly1 poly2 head (cons first-pt leftover)))
                   (done-poly (or (null? leftover) ;; (or (null? tail)           ;; all points accounted for?
                                  (eq? best-pt first-pt) ;; close the polygon
                                  (not best-pt)))        ;; this is where there is no best point
                   (next-leftover (delete best-pt leftover))
                   (done-all  (null? next-leftover)))
              (debug-run
               64 (lambda ()
                    (if (and best-pt head)
                        (draw-segment ezx (list head best-pt) *black*))
                    (print "first-pt=" first-pt ",this-poly=" this-poly ",done-poly=" done-poly ",done-all=" done-all ",best-pt=" best-pt ",head=" head)
                    (ezx-redraw ezx)
                    (dsleep .8)
                    ))
              (cond
               ((and done-all (not done-poly)) ;; this is the case of a simple polygon result
                (debug-print 64 "done-all (not done-poly) holes=" holes)
                (let ((new-poly (make-polygon (if best-pt (cons best-pt this-poly) this-poly))))
                  new-poly))
               ((and done-poly done-all)
                (debug-print 64 "done-all; next-leftover=" next-leftover ",outer-poly=" outer-poly ",holes=" holes ",this-poly=" this-poly)
                (let* ((all-holes  (polys-good 
                                    (map make-polygon
                                         (cons (if best-pt (cons best-pt this-poly) this-poly)  holes))))
                       (final-poly (poly-cut-holes (make-polygon outer-poly) all-holes)))
                  (debug-print 64 "final-poly=" final-poly ",all-holes=" all-holes)
                  (debug-print 64 "BUG!: non-valid points are being introduced by cut-holes")
                  (make-polygon (points-good (get-field final-poly 'points))))) ;; fix the bug and replace this line with final-poly
               ((and done-poly (not done-all))
                (debug-print 64 "NOTE: done-poly (not done-all); next-leftover=" next-leftover)
                (let ((newly-created-poly (if best-pt (cons best-pt this-poly) this-poly)))
                  (debug-print 64 "newly-created-poly=" newly-created-poly ",this-poly=" this-poly)
                  (if outer
                      (begin
                        (set! outer-poly newly-created-poly)
                        (loop0 holes next-leftover #f))
                      ;; the next stanza is where outer is complete and holes are being accounted for
                      (loop0 (cons newly-created-poly holes)
                             next-leftover
                             #f))))
               ((and (not done-poly) (not done-all))
                (debug-print 64 "(and (not done-poly)(not done-all)); next-leftover=" next-leftover ",this-poly=" this-poly ",holes=" holes)
                (loop best-pt next-leftover first-pt (if best-pt (cons best-pt this-poly))))
               (else 
                (print "ERROR poly-or: done-all=" done-all ",done-poly=" done-poly)))))))))
            
;;======================================================================
;; L A Y E R S
;;======================================================================
(define (layer? lay) 
  (if (list? lay)
      (get-field lay 'layers)
      #f))

;; Make a layer from a list of polygons, a name and a list of attributes
(define (make-layer polys name attrib)
  (list (list 'polys polys)
        (list 'attrib attrib)
        (list 'name name)))

(define (draw-layer layer)
  ;; (print "draw-layer layer=" layer)
  (let* ((polys    (get-field layer 'polys))
         (setcolor (get-field layer 'color))
         (color    (if setcolor setcolor *red*)))
    (for-each
     (lambda (p)
       (draw-poly ezx p color))
     polys)))

;; Clean out the invalid polygons on a layer
(define (layer-valid-polys layer)
  (let* ((polys (get-field layer 'polys)))
    (if (null? polys) layer
        (let loop ((poly (car polys))
                   (tail (cdr polys))
                   (new-polys '()))
          (if (null? tail) 
              (if (polygon? poly) 
                  (set-field layer 'polys (cons poly new-polys))
                  (set-field layer 'polys new-polys))
              (if (polygon? poly)
                  (loop (car tail)(cdr tail)(cons poly new-polys))
                  (loop (car tail)(cdr tail) new-polys)))))))

(define (polys-good polys)
  (if (null? polys) polys
      (let loop ((poly (car polys))
                 (tail (cdr polys))
                 (new-polys '()))
        (if (null? tail) 
            (if (polygon? poly) 
                (cons poly new-polys)
                new-polys)
            (if (polygon? poly)
                (loop (car tail)(cdr tail)(cons poly new-polys))
                (loop (car tail)(cdr tail) new-polys))))))

;; Add a polygon to a layer
(define (layer-add-polygon layer poly)
  (set-field layer 'polys (cons poly (get-field layer 'polys))))

;; Add a polygon to a layer
(define (layer-add-polygons layer newpolys)
  ;; (print "layer-add-polygon layer=" layer ",poly=" poly)
  (set-field layer 'polys (append (get-field layer 'polys) newpolys)))

;; only puts all the polys into the same list - doesn't merge polys
(define (layer-merge-layers l1 l2)
  (debug-print 4 "layer-merge-layers l1=" l1 ",l2=" l2)
  (let* ((polys1 (get-field l1 'polys))
         (polys2 (get-field l2 'polys))
         (all-polys (cond
                     ((and polys1 polys2) (append polys1 polys2))
                     (polys1 polys1)
                     (polys2 polys2)
                     (else '())))
         (attrib1 (get-field l1 'attrib))
         (attrib2 (get-field l2 'attrib))
         (attrib  (attrib-merge attrib1 attrib2)))
    (set-field (set-field (if l1 l1 l2) 'attrib attrib) 'polys all-polys)))

;; return a list of polys where all touching have been merged
(define (polys-or polys1 polys2) 
  (debug-check-param polygon-list? polys1 "ERROR: polys-or polys1 not a poly list\n" "" polys1)
  (debug-check-param polygon-list? polys2 "ERROR: polys-or polys2 not a poly list\n" "" polys2)
  (debug-print 32 "Got here! polys-or")
  (let* ((allpolys (polys-auto-name (append polys1 polys2))))
    ;; for each poly in list if touching merge
    (let loop ((master    (car allpolys))
               (curr-poly (cadr allpolys))
               (tail      (cddr allpolys))
               (to-scan   (cddr allpolys))
               (scanned   '())
               (result    '()))
      (let* ((touching (poly-touching? master curr-poly))
             (new-master (if touching (poly-auto-name (poly-or master curr-poly)) curr-poly))
             (done-one (null? to-scan))
             (done (and done-one (null? tail))))
        (debug-print 32 "master=" (if master (get-field master 'name) #f) ",curr-poly=" (get-field curr-poly 'name)
                     ",touching=" touching ",done-one=" done-one ",done=" done)
        (debug-print 32 "   to-scan="(debug-print-some-names to-scan) ",scanned=" (debug-print-some-names scanned))
        (debug-run 32 (lambda ()
                        (ezx-wipe ezx)
                        (draw-polys ezx result *black*)
                        (draw-poly ezx master *blue*)
                        (draw-poly ezx curr-poly *green*)
                        (ezx-redraw ezx)
                        (if touching
                            (begin
                              (print "Put result polys on screen")
                              (dsleep .5)
                              (draw-poly ezx new-master *red*)
                              (ezx-redraw ezx)
                              (dsleep .5)))
                        ))
        (cond
         ((and done touching) ;; last one. i.e. the exit point
          (debug-print 32 "(and done touching)")
          (cons new-master result))
         ((and done (not touching))
          (debug-print 32 "(and done (not touching))")
          result)
         ((and done-one touching) ;; do a useless cycle through so we don't have to deal with requiring a list of length 2
          (debug-print 32 "(and done-one touching) tail=" (debug-print-some-names tail) )
          (let ((new-tail (cons curr-poly scanned)))
            (loop (car new-tail) (car new-tail) (cdr new-tail) (cdr new-tail) '() (cons new-master result))))
         ((and done-one (not touching))
          (debug-print 32 "(and done-one (not touching))")
          (let ((new-tail (cons curr-poly scanned)))
            (loop (car new-tail) (car new-tail) (cdr new-tail) (cdr new-tail) '() (cons master result))))
         ((and (not done-one) touching)
          (debug-print 32 "(and (not done-one) touching)")
          (loop new-master (car to-scan) tail (cdr to-scan) scanned result))
         ((and (not done-one) (not touching))
          (debug-print 32 "(and (not done-one) (not touching))")
          (loop master (car to-scan) tail (cdr to-scan) (cons curr-poly scanned) result))
         (else
          (print "ERROR: Shouldn't get here!")))))))
          

;; return a list of polys where all touching have been merged
(define (polys-or-prev polys1 polys2) 
  (let* ((polys1 (polys-auto-name polys1))
         (polys2 (polys-auto-name polys2))
         (polys-by-name (make-hash-table equal?))
         (results '()))
    (for-each 
     (lambda (poly)
       (hash-table-set! polys-by-name (get-field poly 'name) poly))
     (append polys2 polys1)) ;; lazy bugger
    (let ((curr-polys (hash-table-values polys-by-name)))
      (print "curr-polys=" (debug-print-some-names curr-polys))
      (let loop ((head (car curr-polys))
                 (next (cadr curr-polys))
                 (scan (cddr curr-polys))
                 (tail (cddr curr-polys)))
        (print "head=" (get-field head 'name) ",next=" (get-field next 'name)
;; <<<<<<< .mine
               ",scan=" (debug-print-some-names scan)
               ",tail=" (debug-print-some-names tail))
        (cond
         ((and head next (poly-touching? head next))
          (let* ((same (equal? head next))
                 (new-poly (poly-auto-name (poly-or head next)))
                 (new-name (get-field new-poly 'name)))
            (print "block 0, new-poly=" new-name)
            (hash-table-delete! polys-by-name (get-field head 'name))
            (hash-table-delete! polys-by-name (get-field next 'name))
            (hash-table-set!    polys-by-name new-name new-poly)
            (let ((new-polys (hash-table-values polys-by-name)))
              ;; (print "new-polys=" (map (lambda (p) (get-field p 'name)) new-polys))
              (if (< (length new-polys) 2) 
                  (hash-table-values polys-by-name)
                  (loop (car  new-polys)
                        (cadr new-polys)
                        (cddr new-polys)
                        (cddr  new-polys))))))
         ((and (null? scan)(null? tail)) ;; we are truly done
          (print "block 1")
          (hash-table-values polys-by-name))
         ((null? scan)

          (print "block 2")
          (loop next (car tail)(cdr tail) tail))
         ((null? tail)
          (print "block 3")
          (loop (car scan)(cdr scan) tail tail))
         (else
          (print "block 4") ;;  scan=" (map (lambda (p) (get-field p 'name)) scan) ",cdr scan=" (cdr scan))
          (loop head (car scan)(cdr scan)(cdr tail))))))))
;; head next (rem1 rem2 rem3 rem4 ...)
;; =======
;;                ",scan=" (debug-print-some-names scan)
;;                ",tail=" (debug-print-some-names tail))
;;         (cond
;;          ((and head next (poly-touching? head next))
;;           (let* ((same (equal? head next))
;;                  (new-poly (poly-auto-name (poly-or head next)))
;;                  (new-name (get-field new-poly 'name)))
;;             (print "block 0, new-poly=" new-name)
;;             (hash-table-remove! polys-by-name (get-field head 'name))
;;             (hash-table-remove! polys-by-name (get-field next 'name))
;;             (hash-table-set!    polys-by-name new-name new-poly)
;;             (let ((new-polys (hash-table-values polys-by-name)))
;;               ;; (print "new-polys=" (map (lambda (p) (get-field p 'name)) new-polys))
;;               (if (< (length new-polys) 2) 
;;                   (hash-table-values polys-by-name)
;;                   (loop (car  new-polys)
;;                         (cadr new-polys)
;;                         (cddr new-polys)
;;                         (cddr  new-polys))))))
;;          ((and (null? scan)(null? tail)) ;; we are truly done
;;           (print "block 1")
;;           (hash-table-values polys-by-name))
;;          ((null? scan)
;; 
;;           (print "block 2")
;;           (loop next (car tail)(cdr tail) tail))
;;          ((null? tail)
;;           (print "block 3")
;;           (loop (car scan)(cdr scan) tail tail))
;;          (else
;;           (print "block 4") ;;  scan=" (map (lambda (p) (get-field p 'name)) scan) ",cdr scan=" (cdr scan))
;;           (loop head (car scan)(cdr scan)(cdr tail))))))))
;; ;; head next (rem1 rem2 rem3 rem4 ...)
;; >>>>>>> .r28
     
(define (layer-extents layer)
  (debug-check-param layer? layer "ERROR: layer-extents layer not a layer\n" "" layer)
  (let ((polys (get-field layer 'polys)))
    (polys-extents polys)))

(define (polys-extents polys)
  (debug-check-param polygon-list? polys "ERROR: polys-extents polys not a poly list\n" "" polys)
  (let ((minx #f)
	(miny #f)
	(maxx #f)
	(maxy #f)
	(firsttime #t))
    (if (and polys (null? polys)) #f
	(for-each 
	 (lambda (poly)
	   (if (and (list? poly) (not (null? poly)))
	       (let* ((extents (poly-extents poly))
		      (minxy (car extents))
		      (maxxy (cadr extents))
		      (new-minx  (car  minxy))
		      (new-miny  (cadr minxy))
		      (new-maxx  (car  maxxy))
		      (new-maxy  (cadr maxxy)))
		 ;; (print "extents=" extents ",new-minx=" new-minx ",new-miny=" new-miny
		 ;; 	   ",new-maxx=" new-maxx ",new-maxy=" new-maxy)
		 ;; (print "firsttime=" firsttime ",minx=" minx ",miny=" miny ",maxx=" maxx ",maxy=" maxy)
		 (if firsttime
		     (begin
		       ;; (print "firsttime")
		       (set! minx new-minx)
		       (set! miny new-miny)
		       (set! maxx new-maxx)
		       (set! maxy new-maxy)
		       (if (and (number? minx)(number? miny)(number? maxx)(number? maxy))
			   (set! firsttime #f)))
		     (begin
		       ;; (print "not firsttime")
		       (if (< new-minx minx) (set! minx new-minx))
		       (if (< new-miny miny) (set! miny new-miny))
		       (if (> new-maxx maxx) (set! maxx new-maxx))
		       (if (> new-maxy maxy) (set! maxy new-maxy)))))))
	 polys)) ;; already processed the first one
    (list (list minx miny)(list maxx maxy))))

(define (slice-poly-to-layer layer poly slice-width)
  (let* ((extents (poly-extents poly))
         (p1 (car extents))
         (p2 (cadr extents))
         (x1 (- (car p1) slice-width)) ;; start to the left by one slice
         (y1 (cadr p1))
         (x2 (+ (car p2) slice-width)) ;; finish to the right by one slice
         (y2 (cadr p2))
         (delta-x (- x2 x1))
         (num-rect (inexact->exact (round (/ (+ delta-x slice-width) slice-width)))))
    (let loop ((rx1 x1)
               (rx2 (+ x1 slice-width))
               (count 0)
               (lay  layer)) ;; the resulting layout
    (let* ((polys (poly-and poly
                            (rect->poly (list (list rx1 y1)(list rx2 y2))))))
      (if (< count num-rect)
          (loop (+ rx1 slice-width)
                (+ rx2 slice-width)
                (+ count 1)
                (layer-add-polygons lay polys))
          lay)))))

(define (poly-grid x1 y1 x2 y2 x-slice y-slice)
  ;; (ezx-wipe ezx)
  (let* ((xdelta (- x2 x1))
	 (ydelta (- y2 y1))
	 (xn (inexact->exact (round (/ (+ xdelta x-slice) x-slice))))
	 (yn (inexact->exact (round (/ (+ ydelta y-slice) y-slice)))))
    ;; (print "xdelta=" xdelta ",ydelta=" ydelta ",xn=" xn ",yn=" yn)
    (let loop ((rx1 x1)
	       (ry1 y1)
	       (rx2 (+ x-slice x1))
	       (ry2 (+ y-slice y1))
	       (result '())
	       (col-count 0)
	       (row-count 0))
      (let ((new-poly (rect->poly (list (list rx1 ry1)(list rx2 ry2)))))
	;; (draw-poly ezx new-poly *blue*)
	;; (ezx-redraw ezx)
	;; (print "rx1=" rx1 ",ry1=" ry1 ",rx2=" rx2 ",ry2=" ry2 ",row-count=" row-count ",col-count=" col-count ",new-poly=" new-poly)
	;; (system "sleep 1")
	(cond
	 ((> row-count yn) ;; we are done!
	  result)
	 ((< col-count xn) ;; next in x direction
	  (loop rx2 ry1 (+ rx2 x-slice) ry2 (cons new-poly result) (+ col-count 1) row-count))
	 ((>= col-count xn) ;; next row
	  (loop x1 ry2 (+ x1 x-slice)(+ ry2 y-slice) (cons new-poly result) 0 (+ row-count 1)))
	 (else (print "ERROR: Shouldn't get here!")))))))

(define (poly-touch-matrix x1 y1 x2 y2 x-slice y-slice)
  ;; (ezx-wipe ezx)
  (let* ((xdelta (- x2 x1))
	 (ydelta (- y2 y1))
	 (xn (inexact->exact (round (/ (+ xdelta x-slice) x-slice))))
	 (yn (inexact->exact (round (/ (+ ydelta y-slice) y-slice)))))
    ;; (print "xdelta=" xdelta ",ydelta=" ydelta ",xn=" xn ",yn=" yn)
    (let loop ((rx1 x1)
	       (ry1 y1)
	       (rx2 (+ x-slice x1))
	       (ry2 (+ y-slice y1))
	       (result '())
	       (col-count 0)
	       (row-count 0))
      (let ((new-poly (rect->poly (list (list rx1 ry1)(list rx2 ry2)))))
	;; (draw-poly ezx new-poly *blue*)
	;; (ezx-redraw ezx)
	;; (print "rx1=" rx1 ",ry1=" ry1 ",rx2=" rx2 ",ry2=" ry2 ",row-count=" row-count ",col-count=" col-count ",new-poly=" new-poly)
	;; (system "sleep 1")
	(cond
	 ((> row-count yn) ;; we are done!
	  result)
	 ((< col-count xn) ;; next in x direction
	  (loop rx2 ry1 (+ rx2 x-slice) ry2 (cons new-poly result) (+ col-count 1) row-count))
	 ((>= col-count xn) ;; next row
	  (loop x1 ry2 (+ x1 x-slice)(+ ry2 y-slice) (cons new-poly result) 0 (+ row-count 1)))
	 (else (print "ERROR: Shouldn't get here!")))))))

(define (snap val grid)
  (inexact->exact (* grid (round (/ val grid)))))

;; put all the polygons in sliced-area that are not north, south, east or west of a polygon
;; in end-points
(define (poly-grid-by-vertex route x-slice y-slice end-points)
  (let* ((extents (poly-extents route))
	 (x-half (/ x-slice 2))
	 (y-half (/ y-slice 2))
	 (p1 (car extents))
	 (p2 (cadr extents))
	 (x1 (car p1))  ;; (+ xoffset (snap (- (car p1)  x-half) x-slice)))
	 (y1 (cadr p1)) ;; (+ yoffset (snap (- (cadr p1) y-half) y-slice)))
	 (x2 (car p2))  ;; (+ xoffset (snap (+ (car p2)  x-half) x-slice)))
	 (y2 (cadr p2)) ;; (+ yoffset (snap (+ (cadr p2) y-half) y-slice)))
	 (gridded-mask (poly-grid x1 y1 x2 y2 x-slice y-slice)))
    (let loop ((head (car gridded-mask))
	       (tail (cdr gridded-mask))
	       (result '()))
      (let* ((anded (poly-and route head))
	     (new-result (append result anded)))
	(if (null? tail) new-result
	    (loop (car tail)
		  (cdr tail)
		  new-result))))))


;; we will snap the grid to the origin + x|y offset
(define (poly-grid-route route x-slice y-slice xoffset yoffset)
  (let* ((extents (poly-extents route))
	 (x-half (/ x-slice 2))
	 (y-half (/ y-slice 2))
	 (p1 (car extents))
	 (p2 (cadr extents))
	 (x1 (car p1))  ;; (+ xoffset (snap (- (car p1)  x-half) x-slice)))
	 (y1 (cadr p1)) ;; (+ yoffset (snap (- (cadr p1) y-half) y-slice)))
	 (x2 (car p2))  ;; (+ xoffset (snap (+ (car p2)  x-half) x-slice)))
	 (y2 (cadr p2)) ;; (+ yoffset (snap (+ (cadr p2) y-half) y-slice)))
	 (gridded-mask (poly-grid x1 y1 x2 y2 x-slice y-slice)))
    (let loop ((head (car gridded-mask))
	       (tail (cdr gridded-mask))
	       (result '()))
      (let* ((anded (poly-and route head))
	     (new-result (append result anded)))
	(if (null? tail) new-result
	    (loop (car tail)
		  (cdr tail)
		  new-result))))))

(define (polys-remove-with-tag polys tag value)
  (if (null? polys) polys
      (let loop ((head (car polys))
                 (tail (cdr polys))
                 (result '()))
        ;; (print "looking at poly " poly)
        (let* ((new-result (if (equal? (get-field head tag) value)
                               result 
                               (cons head result)))
               (done (null? tail)))
          ;; (print "new-result=" new-result ",head=" head)
          (if done new-result
              (loop (car tail)(cdr tail) new-result))))))

(define (polys-matching-tag polys tag value)
  (if (null? polys) polys
      (let loop ((head (car polys))
                 (tail (cdr polys))
                 (result '()))
         ;; (print "looking at poly " poly)
        (let* ((new-result (if (equal? (get-field head tag) value)
                               (cons head result)
                               result))
               (done (null? tail)))
          ;; (print "new-result=" new-result ",head=" head)
          (if done new-result
              (loop (car tail)(cdr tail) new-result))))))


;; all polys in polys2 must be found in polys1
;; checking is done by name and points equality
(define (ensure-connection-points-exist-by-name polys1 polys2)
  (debug-check-param polygon-list? polys1
                     "ERROR: ensure-connection-points-exist-by-name polys1 not a list of polygons.\n"
                     "    polys1=" polys1)
  (debug-check-param polygon-list? polys2
                     "ERROR: ensure-connection-points-exist-by-name polys2 not a list of polygons.\n"
                     "    polys2=" polys2)
  (let ((count 0)
	(refcount 0))
    (for-each 
     (lambda (p2)
       (let* ((name       (get-field p2 'name ))
              (name-match (polys-matching-tag polys1 'name name)))
         ;; (print "name=" name ",name-match=" name-match)
	 (set! refcount (+ 1 refcount))
         (if (and (not (equal? name ""))
                  (not (null? name-match)))
             (set! count (+ 1 count)))))
     polys2)
    ;; (print "count=" count "refcount=" refcount "(length polys1=" (length polys2))
    (eq? count refcount))) ;; (length polys2))))

(define (poly->target poly shrink-delta)
  (let* ((extents (poly-extents poly))
         (pt1     (car extents))
         (pt2     (cadr extents))
         (x1      (car pt1))
         (y1      (cadr pt1))
         (x2      (car pt2))
         (y2      (cadr pt2))
         (deltax  (- x2 x1))
         (deltay  (- y2 y1))
         (d
          (if (or (< (* 2 shrink-delta) deltax) (< (* 2 shrink-delta)))
              shrink-delta (min deltax deltay))))
    (rect->poly (list (list (- x1 d) (- y1 d)) (list (- x2 d) (- y2 d))))))

;; Give all polygons with no name a name "poly-n" where n is 0,1,2,3....
(define (polys-auto-name polys)
  (debug-check-param polygon-list? polys
                     "ERROR: polys-auto-name polys not a list of polygons.\n"
                     "    polys=" polys)
    (map
     (lambda (p)
       (set! *curr-poly-number* (+ 1 *curr-poly-number*))
       (if (equal? "" (get-field p 'name))
           (set-field p 'name (string-append "poly-" (number->string *curr-poly-number*)))
           p))
     polys))

(define (poly-auto-name p)
  (debug-check-param polygon? p "ERROR: poly-auto-name, p not a polygon " p)
  (set! *curr-poly-number* (+ 1 *curr-poly-number*))
  (if (equal? "" (get-field p 'name))
      (set-field p 'name (string-append "poly-" (number->string *curr-poly-number*)))
      p))

(define (polys-prefix-name prefix polys)
  (debug-check-param polygon-list? polys
                     "ERROR: polys-auto-name polys not a list of polygons.\n"
                     "    polys=" polys)
    (map
     (lambda (p)
       (set! *curr-poly-number* (+ 1 *curr-poly-number*))
       (if (equal? "" (get-field p 'name))
           (set-field p 'name (string-append prefix (number->string *curr-poly-number*)))
           p))
     polys))

(define (bad-neighborhood-router routable-area bad-neighborhoods end-points width slice-height)
  (debug-check-param polygon? routable-area
                     "ERROR: bad-neighborhood-router routable-area not a polygon\n    routable-area=" routable-area)
  (debug-check-param polygon-list? end-points 
                     "ERROR: bad-neibhborhood-router end-points not a list of polygons\n    end-points=" end-points)
  (debug-check-param polygon-list? bad-neighborhoods
                     "ERROR: bad-neighborhood-router end-points not a list of polygons\n    bad-neighborhoods="  bad-neighborhoods)
  (debug-check-param number? width "ERROR: first-pass-clean-route width not a number\n    width=" width)
  (cond
   ((eq? (length end-points) 0) '())
   ((eq? (length end-points) 1)
    (if (poly-touching? (car end-points) routable-area) end-points '()))
   ((not (andmap (lambda (p) (poly-touching? p routable-area)) end-points)) '()) ;; one contact doesn't touch
   (else ;; ok, so our inputs are good...
    (let* ((named-end-points (polys-prefix-name "via" end-points))
	   (sliced-route (polys-auto-name 
			  (get-field 
			   (layer-valid-polys (make-layer 
					       (poly-grid-route routable-area width slice-height 0 0) ;; (/ width 2) (/ width 2))
					       "nada" '()))
			   'polys)))
	   ;;(sliced-route (polys-auto-name 
	   ;;		      (get-field 
	   ;;		       (layer-valid-polys 
	   ;;			(slice-poly-to-layer 
	   ;;			 (make-layer '() "new-route" '())
	   ;;			 routable-area width)) 
	   ;;		       'polys)))
	   (touching-bad (if (null? bad-neighborhoods) '()
			     (multi-touching-polys sliced-route bad-neighborhoods)))
	   (master-end-point (car named-end-points))
	   (remaining-end-points (cdr named-end-points))
	   (polys-by-name (make-hash-table equal?))
	   (curr-group touching-bad)
	   (route-extents (poly-extents routable-area))
	   (route-x1 (- (caar route-extents) 100))
	   (route-x2 (+ (caadr route-extents) 100))
	   (debug-this-routine 64))
      (debug-print debug-this-routine "bad-neighborhood-route end-points=" (polys-get-names named-end-points))
      (debug-print debug-this-routine "     sliced-route=" (polys-get-names sliced-route))
      (debug-print debug-this-routine "     master-end-point=" (get-field master-end-point 'name) ",remaining-end-points=" (polys-get-names remaining-end-points))
      (debug-run
       debug-this-routine (lambda ()
			    (ezx-select-layer ezx 0)
			    (draw-polys ezx sliced-route *black*)
			    (ezx-redraw ezx)
			    (dsleep 0.5)))
      ;; fill up the hash table with each poly
      (for-each 
       (lambda (p)(hash-table-set! polys-by-name (get-field p 'name) p)) sliced-route)
      ;; (debug-print 1 "sliced polys in polys-by-name=" (hash-table-keys polys-by-name))
      ;; now for the real work
      (for-each 
       (lambda (mode) ;; bad->bad neighborhood, all=adjust all
	 (if (eq? mode 'bad)
	     (set! curr-group touching-bad)
	     (set! curr-group (hash-table-values polys-by-name)))
	 ;; first try removing the polys
	 (for-each
	  (lambda (p)
	    (let* ((poly-name (get-field p 'name))
		   (all-remaining (polys-remove-with-tag 
				   (hash-table-values polys-by-name) 'name poly-name))
		   (rem-route (sort-polys (append all-remaining remaining-end-points))) ;; all but the head
		   (touching  (touching-polys rem-route master-end-point))
		   (connected (ensure-connection-points-exist-by-name touching remaining-end-points)))
	      (debug-print debug-this-routine "poly removal: touching=" (polys-get-names touching))
	      (debug-print debug-this-routine "   rem-route=" (polys-get-names rem-route) ",connected=" connected)
	      (debug-print debug-this-routine "   poly-name=" poly-name ",all-remaining=" (polys-get-names all-remaining))
	      (debug-run
	       debug-this-routine (lambda ()
				    (ezx-wipe ezx)
				    (draw-poly ezx master-end-point *yellow*)
				    (draw-polys ezx remaining-end-points *black*)
				    (draw-polys ezx rem-route *blue*)
				    (draw-poly ezx p (if connected *red* *green*))
				    (ezx-redraw ezx)
				    ;;(dsleep .1)
				    ))
	      (if connected ;; if connected delete this one from the hash table and loop with new 
		  (begin
		    (debug-print debug-this-routine "removing poly " poly-name " from the route")
		    (hash-table-remove! polys-by-name poly-name)))))
	  curr-group)
	 (debug-run 
	  debug-this-routine (lambda ()
			       (ezx-wipe ezx)
			       (draw-polys ezx (hash-table-values polys-by-name) *blue*)
			       (ezx-redraw ezx)
			       ;;(dsleep .1)
			       ))
	 ;; remake curr-group by filtering out those no longer in the hash table
	 (let ((new '()))
	   (for-each 
	    (lambda (p)
	      (if (hash-table-ref polys-by-name (get-field p 'name))
		  (set! new (cons p new))))
	    curr-group)
	   (set! curr-group new))
	 (for-each 
	  (lambda (p)
	    (let* ((poly-name (get-field p 'name))
		   (extents (poly-extents p))
		   (e-y1 (cadar extents))
		   (e-y2 (cadadr extents))
		   (all-remaining (polys-remove-with-tag
				   (hash-table-values polys-by-name) 'name poly-name)))
	      (let loop ((top e-y2)
			 (bot e-y1)
			 (last-top e-y2)
			 (last-bot e-y1)
			 (mode 'both)
			 (prev p)) ;; trimming the top or the bottom
		(let* ((mask      (rect->poly (list (list route-x1 bot) (list route-x2 top))))
		       (new-poly  (set-field (car (poly-and mask p)) 'name poly-name))
		       (rem-route (append (list new-poly) (list new-poly) all-remaining remaining-end-points))
		       (touching  (touching-polys rem-route master-end-point))
		       (connected (ensure-connection-points-exist-by-name touching remaining-end-points)))
		  (debug-run 
		   debug-this-routine (lambda ()
					(print "poly trimming: touching=" (polys-get-names touching) ",extents=" extents)
					(print "   connected=" connected ",top=" top ",bot=" bot ",mode=" mode ",master-end-point=" (get-field master-end-point 'name))
					(print "   rem-route=" (polys-get-names rem-route))
					(print "   all-remaining=" (polys-get-names all-remaining))
					(print "   touching=" (polys-get-names touching))
					(ezx-wipe-layer ezx 2)
					(ezx-select-layer ezx 2)
					(draw-poly ezx mask *yellow*)
					(draw-poly ezx new-poly *red*)
					(ezx-redraw ezx)
					;;(dsleep .1)
					))
		  (cond
		   ((and connected (> top bot))
		    (debug-print debug-this-routine "connected (> top bot) and mode=" mode)
		    (cond
		     ((eq? mode 'top)
		      (loop (- top width) bot top bot 'top new-poly))
		     ((eq? mode 'bot)
		      (loop top (+ bot width) top bot 'bot new-poly))
		     ((eq? mode 'both)
		      (loop (- top width)(+ bot width) top bot 'both new-poly))
		     (else (print "Bad mode, mode=" mode))))
		   ;; ((and connected (<= top bot)) ;; Hmmmppp. don't need this one apparently
		   ;;  (debug-print debug-this-routine "connected (<= top bot)")
		   ;;  (hash-table-remove! polys-by-name poly-name))
		   ((or (not connected)(<= top bot)) ;; better keep prev
		    (debug-print debug-this-routine "(not connected) mode=" mode)
		    (cond 
		     ((eq? mode 'top)
		      (loop last-top  (+ bot width) last-top last-bot 'bot prev))              ;; NOTE: revert top
		     ((eq? mode 'bot)
		      (hash-table-set! polys-by-name poly-name prev)) ;; don't loop again - we are done
		     ((eq? mode 'both)
		      (debug-print  debug-this-routine "mode both")
		      (loop last-top last-bot last-top last-bot 'top p))))
		   (else (print "ERROR: Shouldn't get here eh!?")))))))
	  curr-group))
       (list 'bad 'normal)) ;; 'bad 'normal 'normal))
      (hash-table-values polys-by-name)))))

(define (multi-touching-polys poly-list target-list)
  (debug-check-param polygon-list? poly-list
                     "ERROR: multi-touching-polys - poly-list is not a list of polygons\n    poly-lst=" poly-list)
  (debug-check-param polygon-list? target-list
                     "ERROR: multi-touching-polys - target is not a list of polygons\n   target-list=" target-list)
  (let ((result '()))
    (for-each 
     (lambda (target)
       (let ((touching (touching-polys poly-list target)))
         (set! result (append result))))
       target-list)
    (unique result)))

;; GOLDEN ONE THAT WORKS!
(define (touching-polys poly-lst target)
  (debug-check-param polygon-list? poly-lst
                     "ERROR: touching-polys - poly-lst is not a list of polygons\n    poly-lst=" poly-lst)
  (debug-check-param polygon? target
                     "ERROR: touching-polys - target is not a polygon\n   target=" target)
  (debug-run 
   64 (lambda ()
        (draw-polys ezx poly-lst *blue*)
        (draw-poly  ezx target   *yellow*)))
  (let ((targ           target)
        (good-ones         '()) ;; (list target)) ;; fully scanned and touching
        (touched          '())  ;; found touching but not fully scanned
        (pending      poly-lst)  ;; pending processing
        (found-one    #t)
        (the-one-found #f)
        (pending-fixed poly-lst))
    (let loop ((targ targ)
               (touched '())
               (pending pending-fixed))
      (debug-print 64 "targ=" (get-field targ 'name) ", good-ones=" (map (lambda (p) (get-field p 'name)) good-ones)
                   ",touched=" (map (lambda (p) (get-field p 'name)) touched)
                   ",found-one=" found-one ",pending=" (map (lambda (p) (get-field p 'name)) pending))
      (for-each
       (lambda (p2)
         (let* ((good-p2 (polygon? p2))
                (result (and good-p2 targ (poly-touching-conservative? targ p2))))
           (debug-print 64 "touching-polys, this poly: " result)
           (debug-run 
            64 (lambda ()
                 (ezx-wipe-layer ezx 6)
                 (ezx-select-layer ezx 6)
                 (if result
                     (draw-poly ezx p2 *red*)
                     (draw-poly ezx p2 *green*))
                 (ezx-redraw ezx)
                 (print "good-p2=" good-p2)
                 (dsleep .5)))
           (if result
               (begin
                 (debug-print 64 "touched)=" (map (lambda (p) (get-field p 'name)) touched))
                 (set! the-one-found p2)
                 (set! touched (cons p2 touched))
                 (set! pending-fixed (delete p2 pending))
                 (set! good-ones (unique (cons p2 good-ones)))
                 (set! found-one #t))
               (begin
                 (set! found-one #f)))))
       pending)
      (debug-run
       64 (lambda ()
	    (draw-polys ezx good-ones *yellow*)
            (print "touched=" (map (lambda (p) (get-field p 'name)) touched))))
      (let ((done (null? touched)))
        (cond
         (done        
	  (debug-print 64 "Final result, good-ones=" (map (lambda (p) (get-field p 'name)) good-ones))
	  (unique good-ones)) ;; no more touched polys return touching
         (found-one             ;; so put this guy in touching
          ;; (print "found-one")
          (loop (car touched)
                (cdr touched)
                pending-fixed))
         (else ;; (null? pending) 
          (debug-print 64 "else") ;; "(null? pending)")
          (loop (car touched)
                (cdr touched)
                pending-fixed)))))))

(define (poly-touching? p1 p2)
  (debug-check-param polygon? p1 "ERROR: poly-touching? p1 not a polygon " p1)
  (debug-check-param polygon? p2 "ERROR: poly-touching? p2 not a polygon " p2)
  ;; (print "poly-touching? p1=" (get-field p1 'name) ",p2=" (get-field p2 'name))
  ;; (print "poly-touching? p1=" p1 ",p2=" p2)
  (let ((points1 (get-field p1 'points))
	(is-poly-p1 (polygon? p1))
        (is-poly-p2 (polygon? p2))
        ;; (points1 (get-field p1 'points))
        (points2 (get-field p2 'points)))
    ;; (print "points1=" points1)
    ;; (print "points2=" points2)
    (if (poly-point-touching? p2 (car points1))
        #t
        (let ((segments1 (get-field p1 'segments)) ;; (list->segments points1))
              (segments2 (get-field p2 'segments))) ;; (list->segments points2)))
          ;; (print "segments1=" segments1)
          ;; (print "segments2=" segments2)
          (let loop1 ((seg1 (car segments1))
                      (tail1 (cdr segments1)))
            (let loop2 ((seg2 (car segments2))
                        (tail2 (cdr segments2)))
              (let* ((cross-pts (segment-cross-points seg1 seg2))
                     (not-touching  (null? cross-pts))
                     (touching      (not not-touching))
                     (done1 (null? tail1))
                     (done2 (null? tail2)))
                (cond
                 (touching #t)
                 ((and (not done1) (not done2))
                  (loop2 (car tail2)(cdr tail2)))
                 ((and done2 (not done1))
                  (loop1 (car tail1)(cdr tail1)))
                 ((and done1 (not done2))
                  (loop2 (car tail2)(cdr tail2)))
                 ((and done1 done2) #f)
                 (else
                  (print "ERROR: Shouldn't get here! touching=" 
                         touching ",done1=" done1 ",done2=" done2))
                         ))))))))
;; 
;; =======
;;     (cond
;; 	((or (not is-poly-p1)(not is-poly-p2))
;; 	 #f)
;; 	((poly-point-touching? p2 (car points1))
;; 	   #t)
;; 	(else
;; 	 (let ((segments1 (list->segments points1))
;; 	       (segments2 (list->segments points2)))
;; 	   ;; (print "segments1=" segments1)
;; 	   ;; (print "segments2=" segments2)
;; 	   (let loop1 ((seg1 (car segments1))
;; 		       (tail1 (cdr segments1)))
;; 	     (let loop2 ((seg2 (car segments2))
;; 			 (tail2 (cdr segments2)))
;; 	       (let* ((cross-pts (segment-cross-points seg1 seg2))
;; 		      (not-touching  (null? cross-pts))
;; 		      (touching      (not not-touching))
;; 		      (done1 (null? tail1))
;; 		      (done2 (null? tail2)))
;; 		 (cond
;; 		  (touching #t)
;; 		  ((and (not done1) (not done2))
;; 		   (loop2 (car tail2)(cdr tail2)))
;; 		  ((and done2 (not done1))
;; 		   (loop1 (car tail1)(cdr tail1)))
;; 		  ((and done1 (not done2))
;; 		   (loop2 (car tail2)(cdr tail2)))
;; 		  ((and done1 done2) #f)
;; 		  (else
;; 		   (print "ERROR: Shouldn't get here! touching=" 
;; 			  touching ",done1=" done1 ",done2=" done2))
;; 		  )))))))))
  
(define (polys-get-names plst)
  (map (lambda (p) (get-field p 'name)) plst))

(define (poly-touching-conservative? p1 p2)
  (debug-check-param polygon? p1 "ERROR: poly-touching-conservative? p1 not a polygon" "")
  (debug-check-param polygon? p2 "ERROR: poly-touching-conservative? p2 not a polygon" "")
  (let ((result #f)
	(points1 (get-field p1 'points))
	(points2 (get-field p2 'points))
	(num-crossing-points (length (poly-crossing-points p1 p2))))
    (if (> num-crossing-points 1) 
	#t ;; we are done!!!
	(let ((num-enclosed-points-p1 (length (poly-enclosed-points p1 p2))))
	  (if (> num-enclosed-points-p1 0) 
	      #t
	      (let ((num-enclosed-points-p2 (length (poly-enclosed-points p2 p1))))
		(if (> num-enclosed-points-p2 0) 
		    #t
		    #f)))))))

;; ;; note that the list of polys changes as polys are merged
(define (layer-merge-polys layer)
  (let* ((polys (get-field layer 'polys))
         (new-polys '()))
    ;; (print "layer-merge-polys layer=" layer "\n   polys=" polys)
    (for-each 
     (lambda (p1)
       (let ((flag #f))
         (for-each
          (lambda (p2)
            (let ((same (eq? p1 p2))
                  (touching (poly-touching? p1 p2)))
              (if (and (not same) touching)
                   (begin
                     ;; (print "poly1=" (get-field p1 'name) " poly2=" (get-field p2 'name))
                     (set! new-polys (cons (poly-or p1 p2) new-polys))
                     (set! flag #t)))))
          polys)
         (if (not flag) (set! new-polys (cons p1 new-polys)))))
     polys)
    new-polys))

;; this is brain dead FIXME!
(define (attrib-merge a1 a2)
  (cond
   ((and a1 a2 (eq? a1 a2) a1))
   ((and a1 a2) (list a1 a2))
   (a1 a1)
   (a2 a2)
   (else '())))

;;======================================================================
;; L A Y O U T
;;======================================================================

;; Make a layout from a list of layers
(define (make-layout layers name attrib)
  (list (list 'layers layers)
        (list 'attrib attrib)
        (list 'name   name)))

;; Is obj a layout?
(define (layout? obj)
  (list? obj))
       

;; Add a polygon to a layer in a layout
(define (layout-add-poly-to-layer layout layername poly)
  (let* ((layer (get-field layout layername))
         (polys (cons poly (get-field layer 'polys))))
    (set-field layout (set-field layer 'polys polys))))

;; Add a new layer to a layout, if it already exists then 
;; merge the new layer in with the old
(define (layout-add-layer layout layer)
  (debug-print 8 "layout-add-layer layout=" layout ",layer=" layer)
  (let* ((name       (get-field layer 'name))
         (prev-layer (layout-get-layer layout name))
         (new-layer  (layer-merge-layers prev-layer layer)))
    (layout-set-layer layout new-layer)))

(define (layout-set-layer layout layer)
  (debug-print 8 "layout-set-layer layout=" layout ",layer=" layer)
  (let* ((name   (get-field layer 'name))
         (layers (get-field layout 'layers))
         (new-layers (set-field layers name layer)))
    ;; (if *debug* (print "   name=" name ",layers=" layers ",new-layers=" new-layers))
    (set-field layout 'layers new-layers)))

;; Retrieve a layer by name
(define (layout-get-layer layout layername)
  ;; (print "layout-get-layer layout=" layout ",layername=" layername) ;;  ",layers=" layers)
  (let ((layers (get-field layout 'layers)))
    (get-field layers layername)))

(define (layout-extents layout)
  (debug-check-param layout? layout "ERROR: layout-extents layout not a layout\n" "" layout)
  (let ((layernames (map car (get-field layout 'layers)))
	(firsttime #t)
	(minx #f)
	(miny #f)
	(maxx #f)
	(maxy #f))
    (if (null? layernames) #f
	(for-each 
	 (lambda (layername)
	   ;; (print "processing layer with name=" layername)
	   (let* ((extents (layer-extents (layout-get-layer layout layername)))
		  (minxy (car extents))
		  (maxxy (cadr extents))
		  (new-minx  (car  minxy))
		  (new-miny  (cadr minxy))
		  (new-maxx  (car  maxxy))
		  (new-maxy  (cadr maxxy)))
	     (if firsttime
		 (begin
		   (set! minx new-minx)
		   (set! miny new-miny)
		   (set! maxx new-maxx)
		   (set! maxy new-maxy)
		   (if (and (number? minx)(number? miny)(number? maxx)(number? maxy))
		       (set! firsttime #f)))
		 (begin
		   (if (< new-minx minx) (set! minx new-minx))
		   (if (< new-miny miny) (set! miny new-miny))
		   (if (> new-maxx maxx) (set! maxx new-maxx))
		   (if (> new-maxy maxy) (set! maxy new-maxy))))))
	 layernames))
    (list (list minx miny)(list maxx maxy))))

(define (fit-extents extents)
  (let* ((sx1 50)       ;; remember the y axis of the screen increases going down
	 (sy1 550)      ;; s=screen
	 (sx2 850)
	 (sy2 50)
	 (p1 (car extents))  ;; lower left on layout 
	 (p2 (cadr extents)) ;; upper right on layout
	 (x1 (car p1))
	 (y1 (cadr p1))
	 (x2 (car p2))
	 (y2 (cadr p2))
         (dx (abs (- x2 x1)))
         (dy (abs (- y2 y1)))
         (sdx (abs (- sx2 sx1)))
         (sdy (abs (- sy2 sy1)))
         (xratio (/ sdx dx))
         (yratio (/ sdy dy))
         (ratio  (if (< xratio yratio) xratio yratio)))
    ;; keep in mind that y is multiplied by -1
    (set! *disp-x-scale* ratio)
    (set! *disp-y-scale* (- ratio))
    ;; map x1, y1 to 50,50
    (set! *disp-x-offset* (+ (* x1 ratio) sx1))
    (set! *disp-y-offset* (+ (* y1 ratio) sy1))
    (set! *disp-scale* ratio)
    (debug-print 64 "*disp-x-offset*=" *disp-x-offset* ",*disp-y-offset*=" *disp-y-offset* 
		 ",xratio=" xratio ",yratio=" yratio ",ratio=" ratio ",*disp-x-scale*=" *disp-x-scale* ",*disp-y-scale*=" *disp-y-scale*)))

(define (draw-layout layout)
  (let ((layers (map cadr (get-field layout 'layers))))
    (for-each 
     (lambda (l)
       (print "drawing layer " (get-field l 'name))
       (draw-layer l)
       (ezx-redraw ezx))
     layers)))

;;======================================================================
;; C I F
;;======================================================================

(define cif-end-of-statement-regex (regexp "^([^;]*);")) ;; WARNING lots of assumptions here
;; (define cif-prop-regexp (regexp "(\\\{.*\\\})")) ;; WARNING lots of assumptions here
(define cif-prop-regexp (regexp "(\\{.*\\})")) ;; WARNING lots of assumptions here
(define cif-layer-name  (regexp "L ([^ \t]+)\\s*$"))

;; e-o-s end-of-statement
(define (cif-read-one-entry port)
  (let loop ((l (read-line port))
             (state 'start)
             (result '()))
    (if (eof-object? l) result
        (let ((e-o-s (string-match cif-end-of-statement-regex l)))
          (if e-o-s
              (append result (list (cadr e-o-s)))
              (loop (read-line port)
                    'statement
                    (append result (list l))))))))

(define (cif-extract-poly dat)
  (let loop ((chunk (car dat))
             (tail  (cdr dat))
             (points '())
             (attrib '())
             (state 'start))
    ;; (print "extract-poly chunk=" chunk ",tail=" tail ",points=" points ",attrib=" attrib ",state=" state)
    (case state
      ((start)
       (let ((prop (string-match cif-prop-regexp chunk))) ;; a bug layeth here "P 123" won't work...
         (loop (car tail)(cdr tail) points (if prop (list (cadr prop)) '()) 'points)))
      ((points)
       (if (null? tail)
           (set-field (make-polygon (list->points (append (map string->number (string-split chunk)) points)))
                      'attrib attrib)
           (loop
            (car tail)
            (cdr tail)
            (append points (map string->number (string-split chunk)))
            attrib
            state)))
      (else (print "ERROR: Shouldn't get here")))))

(define (cif-read f)
  (let ((port (open-input-file f))
        (scale-factor #f)
        (have-scale-factor #f))

    (let loop ((layout (make-layout '() "" '()))
               (layer (make-layer '() "" '()))
               (curr-line (cif-read-one-entry port)))
      (if (null? curr-line)
          layout
          (begin
            (case (string-ref (car curr-line) 0)
              ((#\p #\P) ;; have polygon
               (let ((newpoly (cif-extract-poly curr-line)))
                 ;; (print "newpoly=" newpoly ",layer=" layer ",layout=" layout)
                 (loop layout
                       (layer-add-polygon layer newpoly)
                       (cif-read-one-entry port))))
              ((#\l #\L) ;; set the layer or add a new layer
               ;; first save the current layer for putting back into the layout
               (let* ((prev-layer layer) ;; don't forget to save this back into the layout
                      (layer-name (cadr (string-match cif-layer-name (car curr-line))))
                      (tmp (layout-get-layer layout layer-name))
                      (new-layer (if (and tmp (null? tmp)) tmp (make-layer '() layer-name '()))))
                 ;; (print "prev-layer=" prev-layer ",layer-name=" layer-name ",tmp=" tmp ",new-layer=" new-layer)
                 (loop (layout-add-layer (layout-add-layer layout prev-layer) new-layer)
                       new-layer
                       (cif-read-one-entry port))))
              (else
               (print "length curr-line=" (length curr-line) ",curr-line=" curr-line)
               (loop layout layer (cif-read-one-entry port)))))))))

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted geolib/geolib.meta.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
(
; Your egg's license:
(license "LGPL")

; Pick one from the list of categories (see below) for your egg and enter it
; here.
(category misc)

; A list of eggs mpeg3 depends on.  If none, you can omit this declaration
; altogether. If you are making an egg for chicken 3 and you need to use
; procedures from the `files' unit, be sure to include the `files' egg in the
; `needs' section (chicken versions < 3.4.0 don't provide the `files' unit).
; `depends' is an alias to `needs'.
;; (needs sandbox syntax-case)

; A list of eggs required for TESTING ONLY.  See the `Tests' section.
(test-depends test)

(author "Matt Welland")
(synopsis "Primitive argument processor."))
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted geolib/geolib.scm.

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
;; Copyright 2007-2010, Matthew Welland.
;;
;;  This program is made available under the GNU GPL version 2.0 or
;;  greater. See the accompanying file COPYING for details.
;;
;;  This program is distributed WITHOUT ANY WARRANTY; without even the
;;  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;  PURPOSE.

;; RENAME ME TO GEOMLIB!

;;======================================================================
;; circular functions
;;======================================================================

(define *pi*    (* 4 (atan 1)))
(define *pi/4*  (/ *pi* 4))
(define *pi/2*  (/ *pi* 2))
(define *2pi*   (* 2 *pi*))
(define *3pi*   (* 3 *pi*))
(define *3pi/4* (/ *3pi* 4))
(define *3pi/2* (/ *3pi* 2))

;; deprecated
(define (deg-to-rad t)
  (* *pi* (/ t 180)))

;; deprecated
(define (rad-to-deg r)
  (* 180 (/ r *pi*)))

(define (deg->rad t)
  (* *pi* (/ t 180)))

(define (rad->deg r)
  (* 180 (/ r *pi*)))


;;======================================================================
;; Miscellaneous routines, math, etc.
;;======================================================================

(define (mid-point x1 y1 x2 y2)
  (list (- x1 (/ (- x1 x2) 2))
	(- y1 (/ (- y1 y2) 2))))

(define (line-length line)
  (let* ((x0 (car line))
         (y0 (cadr line))
         (x1 (caddr line))
         (y1 (cadddr line))
         (dx (- x1 x0))
         (dy (- y1 y0)))
    (sqrt (+ (* dx dx) (* dy dy)))))

(define (in-range? a b x) ;; is x in the range from a to b
  (let ((upper (max a b))
        (lower (min a b)))
    (and (>= x lower) (<= x upper))))

;;======================================================================
;; Boxes
;;======================================================================


;; the idea here is to fake a simple object oriented like interface
;; that makes the routines work for lists or vectors (or anything else)
;; the user fills a vector with the accessor in 0 and the setter in 1
(define (geolib:box-getter v)(vector-ref v 0))
(define (geolib:box-setter v)(vector-ref v 1))

;; accessors for boxes as list
;; (define (geolib:box-as-list)
;;   (list->vector
;;    (list 
;;     list-ref        ;; access individual numbers
;;     (lambda (l i v) ;; set i-th to v
;;       (let ((vl (list->vector l)))
;; 	(vector->list 
;; 	 (begin
;; 	   (vector-set! 
;; 	    (if (> (- (vector-length vl) 1) i)
;; 		vl
;; 		(vector-resize vl (+ i 1)))
;; 	    i v)
;; 	   ))))))
    

(define (geolib:pt-in-box? x0 y0 x1 y1 ptx pty)
  (and (in-range? x1 x0 ptx)
       (in-range? y1 y0 pty)))

(define (geolib:box-in-box? x0 y0 x1 y1 ptx1 pty1 ptx2 pty2)
  (and (geolib:pt-in-box? x0 y0 x1 y1 ptx1 pty1)
       (geolib:pt-in-box? x0 y0 x1 y1 ptx2 pty2)))

(define (geolib:grow-box margin x0 y0 x1 y1)
  (list (- x0 margin)(- y0 margin)(+ x1 margin)(+ y1 margin)))

;; box1 and box2 are box vectors x0 y0 x1 y1
(define (geolib:box-overlap-box x0 y0 x1 y1 ptx1 pty1 ptx2 pty2)
  (let ((box1-va (list x0 y0 x0 y1))          ;; vert line "a"
	(box1-hb (list x0 y0 x1 y0))          ;; horz line "b"
	(box1-vc (list x1 y0 x1 y1))
	(box1-hd (list x0 y1 x1 y1))
	(box2-va (list ptx1 pty1 ptx1 pty2))  ;; vert line "e"
	(box2-hb (list ptx1 pty1 ptx1 pty1))) ;; horz line "h"
    (or
     (geolib:pt-in-box? x0 y0 x1 y1 ptx1 pty1) 
     (geolib:pt-in-box? x0 y0 x1 y1 ptx1 pty2)
     (geolib:pt-in-box? x0 y0 x1 y1 ptx2 pty1)
     (geolib:pt-in-box? x0 y0 x1 y1 ptx2 pty2)
     (geolib:pt-in-box? ptx1 pty1 ptx2 pty2 x0 y0) 
     (geolib:pt-in-box? ptx1 pty1 ptx2 pty2 x0 y1)
     (geolib:pt-in-box? ptx1 pty1 ptx2 pty2 x1 y0)
     (geolib:pt-in-box? ptx1 pty1 ptx2 pty2 x1 y1)
     (geolib:intersection box1-va box2-hb)
     (geolib:intersection box1-hb box2-va)
     (geolib:intersection box1-vc box2-hb)
     (geolib:intersection box1-hd box2-va))))

;;======================================================================
;; Lines
;;======================================================================

(define (geolib:intersection l1 l2) ;; x0 y0 x1 y1 x2 y2 x3 y3) ;; segments 0,1 and 2,3
  ;; (print "(intersection " x0 " " y0 " " x1 " " y1 " " x2 " " y2 " " x3 " " y3 ")")
  (let* ((x0 (exact->inexact (car l1)))
         (y0 (exact->inexact (cadr l1)))
         (x1 (exact->inexact (caddr l1)))
         (y1 (exact->inexact (cadddr l1)))
         (x2 (exact->inexact (car l2)))
         (y2 (exact->inexact (cadr l2)))
         (x3 (exact->inexact (caddr l2)))
         (y3 (exact->inexact (cadddr l2)))
	 (l1-delx (- x0 x1))
	 (l1-dely (- y0 y1))
	 (l2-delx (- x2 x3))
	 (l2-dely (- y2 y3))
	 (l1-vert (not (> (abs (- l1-delx 0)) 0))) ;; handle integer and float and rounding
	 (l2-vert (not (> (abs (- l2-delx 0)) 0)))
	 (l1-horz (not (> (abs (- l1-dely 0)) 0)))
	 (l2-horz (not (> (abs (- l2-dely 0)) 0))))
    ;; (print "l1-vert " l1-vert " l2-vert " l2-vert " l1-horz " l1-horz " l2-horz " l2-horz)
    (if (or (and l1-vert l1-horz) ;; i.e. the line is a point
	    (and l2-vert l2-horz))
	#f  ;; BUG the point may lay on the line, add that later
	(let* ((m1      (if (not l1-vert) (/ l1-dely l1-delx) #f))
	       (m2      (if (not l2-vert) (/ l2-dely l2-delx) #f))
	       (b1      (if (not l1-vert) (- y0 (* m1 x0)) #f))
	       (b2      (if (not l2-vert) (- y2 (* m2 x2)) #f))
	       (parll   (and m1 (equal?  m1 m2))))
	  ;; (print "m1=" m1 ", m2=" m2 ", b1=" b1 ", b2=" b2 ", l1-vert=" l1-vert ", l2-vert=" l2-vert ", parll=" parll)
	  (cond
	   ((and m1 m2 (not parll)) ;; neither line is vertical and lines are not parallel
	    (let* ((xi (/ (- b2 b1) (- m1 m2))) ;; the x intersection
		   (yi (+ (* m1 xi) b1)))       ;; the y intersection
	      (if (pt-in-range? xi yi x0 y0 x1 y1 x2 y2 x3 y3)
		  (list xi yi)
		  #f)))
	   (l1-vert
	    (let* ((xi x0)
		   (yi (+ (* m2 xi) b2)))
	      (if (pt-in-range? xi yi x0 y0 x1 y1 x2 y2 x3 y3)
		  (list xi yi)
		  #f)))
	   (l2-vert
	    (let* ((xi x2)
		   (yi (+ (* m1 xi) b1)))
	      (if (pt-in-range? xi yi x0 y0 x1 y1 x2 y2 x3 y3)
		  (list xi yi)
		  #f)))
	   (else #f))))))

(define intersection geolib:intersection)

(define (pt-in-range? xi yi x0 y0 x1 y1 x2 y2 x3 y3)
  (and (in-range? x0 x1 xi)
       (in-range? x2 x3 xi)
       (in-range? y0 y1 yi)
       (in-range? y2 y3 yi)))


;; Apply a procedure to each segment in a list of points
(define (process-line pt-list func)
  (let* ((prev-x (car pt-list))
	 (prev-y (cadr pt-list))
	 (pt-tail (cddr pt-list)))
    (let loop ((result '())
               (x0 prev-x)
	       (y0 prev-y)
	       (x1 (car pt-tail))
	       (y1 (cadr pt-tail))
	       (tail (cddr pt-tail)))
      (if (not (null? tail))
	  (loop (append (list (func x0 y0 x1 y1)) result)
                x1 y1
		(car tail)
		(cadr tail)
		(cddr tail))
          (append (list (func x0 y0 x1 y1)) result)))))

(define (process-line-until-true pt-list func)
  (let* ((prev-x (car pt-list))
	 (prev-y (cadr pt-list))
	 (pt-tail (cddr pt-list)))
    (let loop ((x0 prev-x)
	       (y0 prev-y)
	       (x1 (car pt-tail))
	       (y1 (cadr pt-tail))
	       (tail (cddr pt-tail)))
      (let ((res (func x0 y0 x1 y1)))
        (if res
            res
            (if (null? tail)
                #f
                (loop x1 y1
                      (car tail)
                      (cadr tail)
                      (cddr tail))))))))

;; offset a pt-list by xoff yoff
(define (geolib:offset-line lvec xoff yoff)
  (let ((maxy (- (vector-length lvec) 1)))
    (let loop ((xn 0)
	       (yn 1))
      (vector-set! lvec xn (+ (vector-ref lvec xn) xoff))
      (vector-set! lvec yn (+ (vector-ref lvec yn) yoff))
      (if (< yn maxy)
	  (loop (+ xn 2)(+ yn 2))))
    lvec))
		       
;; get point n from a list of points
(define (get-point-n pt-list n)
  (list
   (list-ref pt-list (* 2 n))
   (list-ref pt-list (+ 1 (* 2 n)))))

;; make a ray +/- r from point x y with angle theta
(define (make-ray x y r theta)
  (let* ((mr (- r))
         (cos-theta (cos theta))
         (sin-theta (sin theta))
         (x0 x) ;; (+ x (* mr sin-theta)))
         (y0 y) ;; (+ y (* mr cos-theta)))
         (x1 (+ x (* r cos-theta)))
         (y1 (+ y (* r sin-theta))))
    (list x0 y0 x1 y1)))

;; cir is (x y r)
(define (proj-circle cir t) ;; project a circle of radius r at point x y to a plane as viewed from angle t
  ;; (make-ray (car cir) (cadr cir) (caddr cir) (+ *pi/2* t)))
  (let* ((x (car cir))
         (y (cadr cir))
         (r (caddr cir))
         (dx (* r (sin t)))
         (dy (* r (cos t))))
    (list (- x dx) (+ y dy) (+ x dx) (- y dy))))
  ;; (make-ray (car cir) (cadr cir) (caddr cir) (- t  *3pi/4*)))

;;======================================================================
;; The ray calculations
;;======================================================================

;; measures clockwise from horizontal?
(define (line-angle line)
  (let* ((x0 (car line))
         (y0 (cadr line))
         (x1 (caddr line))
         (y1 (cadddr line))
         (delx (- x1 x0))
         (dely (- y1 y0))
         (vert (not (> (abs (- delx 0)) 0))) ;; handle integer and float and rounding
         (m1      (if (not vert) (/ dely delx) #f))
         (angle (if m1 (atan m1)
		    (if (> y0 y1) *pi/4* *3pi/4*))))
    (cond
     ((and (eq? delx 0) (>= dely 0)) *pi/2*)
     ((and (eq? delx 0) (< dely 0))  *3pi/4*)
     ((and (eq? dely 0) (>= delx 0)) 0)
     ((and (eq? dely 0) (<= delx 0)) *pi*)
     ((and (> delx 0)   (> dely 0)) angle) 
     ((and (> delx 0)   (< dely 0))(+ *2pi* angle))
     ((and (< delx 0)   (< dely 0))(+ *pi* angle))
     ((and (< delx 0)   (> dely 0))(+ *pi* angle));; (- *pi/2* angle))
     (else angle))))

(define (geomlib:trim-line line newlen) ;; trim from begining of line to newlen
  (let ((x (car line))
	(y (cadr line))
	(a (line-angle line)))
    (make-ray x y newlen a)))

;; find nearest surface ray reflected off and return the reflected ray
;; and the obj
;; (reflray . obj)
(define (geolib:reflect ray lst-o-mirrors)
  (if (null? lst-o-mirrors) #f
      (let* ((ray-xorig (car ray))
	     (ray-yorig (cadr ray)))
	(let loop ((hed (car lst-o-mirrors))
		   (tal (cdr lst-o-mirrors))
		   (len #f)
		   (res #f))
	  (let* ((refl   (ray-reflect ray hed))
		 (newlen (if refl
			     (line-length (list ray-xorig ray-yorig (car refl)(cadr refl)))
			     #f)))
	    (if (or (and refl newlen (not len)(> newlen 0.1))
		    (and newlen (> newlen 0.1)(< newlen len))) ;; heuristically speaking
		(if (null? tal)
		    (list refl hed)
		    (loop (car tal)(cdr tal) newlen (list refl hed)))
		(if (null? tal)
		    res
		    (loop (car tal)(cdr tal) len res))))))))

;; 
(define (normalize-vector vec)
  (let ((x0 (car vec))
        (y0 (cadr vec))
        (x1 (caddr vec))
        (y1 (cadddr vec)))
    (if (> x0 x1)
        (list x1 y1 x0 y0)
        vec)))

(define (horiz-mirror-reflect-get-angle ray-angle)
  (if ray-angle
      (if (< ray-angle *pi*)
	  (- *pi* ray-angle)
	  (- *3pi* ray-angle))
      #f))
	  
(define (ray-reflect ray mirr)
  (let* ((mirror (normalize-vector mirr))
         (ray-mirr-intersection (intersection ray mirror))) ;; always mirror goes left to right
    (if ray-mirr-intersection
        (let* ((ray-length     (line-length ray))
	       (mirr-angle     (let ((ma (line-angle mirror)))
			         (if (and ma (> ma *pi*))(- ma *pi*) ma)))
	       (mirr-adj       (- mirr-angle))
               (ray-angle      (line-angle ray))
	       (ray-angle-adj (+ ray-angle mirr-adj))
	       (reflect-angle  #f)
	       ) ;; adjust ray-angle for > *pi*
	  (if ray-angle-adj
	      (set! reflect-angle (- *2pi* ray-angle-adj mirr-adj))
	      (set! reflect-angle *pi*))
	  (if reflect-angle
	      (append ray-mirr-intersection 
		      (list 
		       (+ (car ray-mirr-intersection) ;; add to x0
			  (* 2 ray-length (cos reflect-angle)))
		       (+ (cadr ray-mirr-intersection)
			  (* 2 ray-length (sin reflect-angle)))))
	      #f))
        #f)))

;;======================================================================
;; Tests
;;======================================================================
	
(define (test-intersection l1  l2)
  (let ((intersection (intersection l1 l2))
        (x0 (car l1))
        (y0 (cadr l1))
        (x1 (caddr l1))
        (y1 (cadddr l1))
        (x2 (car l2))
        (y2 (cadr l2))
        (x3 (caddr l2))
        (y3 (cadddr l2)))
    (wipe)
    (ezx-line-2d ezx x0 y0 x1 y1  (make-ezx-color 1 0 0) 1)
    (ezx-line-2d ezx x2 y2 x3 y3  (make-ezx-color 0 1 0) 1)
    (if intersection
        (ezx-circle-2d ezx (car intersection) (cadr intersection) 10 (make-ezx-color 0 0 0) 1))
    (redraw)))

(define (scale val)
  (/ val 40))

(define (rect->polar x0 y0 x1 y1)
  (let* ((deltax (- x0 x1))
         (deltay (- y0 y1))
         (r (sqrt (+ (expt deltax 2)(expt deltay 2))))
         (t (atan (/ deltay deltax))))
    (list t r)))

(define (rotate-pt angle x y) ;; angle in _radians_
  (let ((sinval (sin angle))
        (cosval (cos angle)))
    (list (- (* x cosval)(* y sinval))
          (+ (* y cosval)(* x sinval)))))

(define (rotate-pt-around-pt angle x y ox oy)
  (let* ((newxy (rotate-pt angle (- x ox)(- y oy)))
         (newx  (car newxy))
         (newy  (cadr newxy)))
    (list (+ newx ox)(+ newy oy))))

(define (rotate-line angle l ox oy) ;; ox oy is the origin
  (let* ((vlen   (vector-length l))
         (numpts (quotient vlen 2))
	 (lastn  (- numpts 1))
         (lnew   (make-vector vlen)))
    (let loop ((indx0 0)
               (indx1 1)
	       (n     0))
      ;; (print "indx0 " indx0 " indx1 " indx1)
      (let ((newpt (rotate-pt-around-pt angle (vector-ref l indx0)(vector-ref l indx1) ox oy)))
        (vector-set! lnew indx0 (car newpt))
        (vector-set! lnew indx1 (cadr newpt))
        (if (< n lastn)
            (loop (+ indx0 2)(+ indx1 2)(+ n 1)))))
    lnew))

(define (rotate-lst-line a l x y)
  (vector->list (rotate-line a (list->vector l) x y)))

(define (rot-lst-ln l a)
  (vector->list (rotate-line (deg-to-rad a) (list->vector l) 0 0)))

; (load "sol.scm")(init)(all-ays testcollector)(redraw)
;; (print "all-rays=" (all-rays testcollector))

;; (set! *plot* #f)
;; (run init-spec)
;; (ga-run)
;; (set! *plot* #t)
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted geolib/geolib.setup.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
;; Copyright 2007-2010, Matthew Welland.
;;
;;  This program is made available under the GNU GPL version 2.0 or
;;  greater. See the accompanying file COPYING for details.
;;
;;  This program is distributed WITHOUT ANY WARRANTY; without even the
;;  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;  PURPOSE.

;;;; geolib.setup

;; compile the code into a dynamically loadable shared object
;; (will generate geolib.so)
(compile -s geolib.scm)
(compile -s compgeom.scm)

;; Install as extension library
(install-extension 'geolib "geolib.so")
(install-extension 'compgeom "compgeom.so")

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted geolib/macros.scm.

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
;; match bits and return #t #f
(define-inline (bitwise-match a b)
  (if (and a b)
      (not (eq? (bitwise-and a b) 0))
      #f))

(define-inline (debug-test-param code)
  (if *debug*
      (if (bitwise-match *debug* 128)
          (code))))
                
(define-inline (debug-print debug-level . msg)
  (if *debug*
      (if (bitwise-match debug-level *debug*)
          (apply print msg))))

;; Run code if debug level
(define-inline (debug-run debug-level code)
  (if *debug*
      (if (bitwise-match debug-level *debug*)
          (code))))

;; check parameters but be efficient about it.
(define-inline (debug-check-param code params . msg)
  (if *debug* ;; any debug setting other than #f 
;;      (if (bitwise-match *debug* 1)
          (if (not (code params))  ;; (force test)
              (apply print msg)))) ;; ) ;; (apply print msg))))))

;; decimal sleep
(define (dsleep sec)
  (let ((usec (round (* sec 1e6))))
    (system (string-append "usleep " (number->string usec)))))

(define (debug-set value)
  (if *debug*
      (set! *debug* (bitwise-ior *debug* value))
      (set! *debug* value)))

(define (debug-unset value)
  (set! *debug* (bitwise-and (bitwise-not value) *debug*)))

(define (debug-print-some-names poly-lst)
  (let ((len (length poly-lst))
        (names (map (lambda (p) (get-field p 'name)) poly-lst)))
    (if (> len 10)
        (let* ((left (take names 4))
               (right (take-right names 2)))
          (append left (list "...") right))
        names)))
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































Deleted geolib/tests.scm.

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
;; Copyright 2007-2010, Matthew Welland.
;;
;;  This program is made available under the GNU GPL version 2.0 or
;;  greater. See the accompanying file COPYING for details.
;;
;;  This program is distributed WITHOUT ANY WARRANTY; without even the
;;  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;  PURPOSE.

(require-library geolib)
(use test)

(test "deg-to-rad"     0.0    (deg-to-rad 0))
(test "get-point-n" '(5 6)    (get-point-n (list 1 2 3 4 5 6) 2))
(test "in-range?"       #t    (in-range? 15 5 7))
(test "intersection" '(10.0 10.0) (intersection '(5 5 15 15) '(15 5 5 15 )))
(test "line-angle"       45.0 (rad->deg (line-angle '(0 0 50 50))))
(test "line-length"     10.0    (line-length '(0 0 10 0)))
(test "make-ray"      '(0 0 100.0 0.0) (make-ray 0 0 100 0))
(test "mid-point"      '(0 0) (mid-point -100 0 100 0))
;; (test "normalize-vector" #f (normalize-vector  ))
;; (test "process-line" #f (process-line  ))
;; (test "process-line-until-true" #f (process-line-until-true  ))
;; (test "proj-circle" #f (proj-circle  ))

(test "pt-in-range?" #t (pt-in-range? 0 0 -10 -10 10 10 -20 -20 20 20 ))
;; (test "rad-to-deg" #f (rad-to-deg  ))
;; (test "ray-reflect" #f (ray-reflect  ))
;; (test "rect->polar" #f (rect->polar  ))
;; (test "reflect" #f (reflect  ))

(test "geolib:reflect" '(-100 0 100 0) (cadr (geolib:reflect'(100 100 -10 -10)
							    '( (100 10 500 20)
							       (-100 0 100 0)
							       (-100 -10 100 10)
							       ))))

(test "geolib:reflect (rev)" '(100 0 -100 0) (cadr (geolib:reflect'(-100 100 10 -10)
							    '( (100 10 500 20)
							       (100 0 -100 0)
							       (100 10 -100 -10)
							       ))))

(test "geolib:reflect problem case" '(100 0 -100 0) 
      (cadr (geolib:reflect'(100 100 -100 -10)
			   '( (100 10 500 20)
			      (100 0 -100 0)
			      (100 10 -100 -10)
			      ))))

(test "rotate-line  90" '(10 10 -10 10) (map inexact->exact 
					     (map round
						  (vector->list
						   (rotate-line 
						    (deg-to-rad 90) 
						    (list->vector (list 10 10 10 30))
						    10 10)))))
(test "rotate-line 180" '(10 10 10 -10) (map inexact->exact 
					     (map round
						  (vector->list
						   (rotate-line 
						    (deg-to-rad 180) 
						    (list->vector (list 10 10 10 30))
						    10 10)))))
(test "rotate-line 270" '(10 10 30 10) (map inexact->exact 
					     (map round
						  (vector->list
						   (rotate-line 
						    (deg-to-rad 270) 
						    (list->vector (list 10 10 10 30))
						    10 10)))))
(test "rotate-line 360" '(10 10 10 30) (map inexact->exact 
					    (map round
						 (vector->list
						  (rotate-line 
						   (deg-to-rad 360) 
						   (list->vector (list 10 10 10 30))
						   10 10)))))

(test "rotate-line  90" '(-30 10 -50 10) (map inexact->exact 
					     (map round
						  (vector->list
						   (rotate-line 
						    (deg-to-rad 90) 
						    (list->vector (list 10 10 10 30))
						    -10 -10)))))
(test "rotate-line 180" '(-30 -30 -30 -50) (map inexact->exact 
					     (map round
						  (vector->list
						   (rotate-line 
						    (deg-to-rad 180) 
						    (list->vector (list 10 10 10 30))
						    -10 -10)))))
(test "rotate-line 270" ' (10 -30 30 -30) (map inexact->exact 
					     (map round
						  (vector->list
						   (rotate-line 
						    (deg-to-rad 270) 
						    (list->vector (list 10 10 10 30))
						    -10 -10)))))
(test "rotate-line 360" '(10 10 10 30) (map inexact->exact 
					    (map round
						 (vector->list
						  (rotate-line 
						   (deg-to-rad 360) 
						   (list->vector (list 10 10 10 30))
						   -10 -10)))))

(test "rotate-pt  90" '(-10 10) (map inexact->exact
				     (map round (rotate-pt (deg-to-rad 90) 10 10) )))
(test "rotate-pt 180" '(-10 -10) (map inexact->exact
				      (map round (rotate-pt (deg-to-rad 180) 10 10) )))
(test "rotate-pt 270" '(10 -10) (map inexact->exact
				     (map round (rotate-pt (deg-to-rad 270) 10 10) )))
(test "rotate-pt 360" '(10 10) (map inexact->exact
				    (map round (rotate-pt (deg-to-rad 360) 10 10) )))

(test "rotate-pt-around-pt  90" '(-10 10) (map inexact->exact 
					       (map round (rotate-pt-around-pt (deg-to-rad  90) 10 30 10 10))))
(test "rotate-pt-around-pt 180" '(10 -10) (map inexact->exact 
					       (map round (rotate-pt-around-pt (deg-to-rad 180) 10 30 10 10))))
(test "rotate-pt-around-pt 270" '(30 10) (map inexact->exact 
					      (map round (rotate-pt-around-pt (deg-to-rad 270) 10 30 10 10))))
(test "rotate-pt-around-pt 360" '(10 30) (map inexact->exact 
					      (map round (rotate-pt-around-pt (deg-to-rad 360) 10 30 10 10))))

(test "geolib:offset-line" 
      '(11 22 13 24 15 26)
      (vector->list
       (geolib:offset-line (list->vector (list 1 2 3 4 5 6))
			   10 20)))


(test "geolib:box-overlap-box, no overlap" #f (geolib:box-overlap-box 10 10 20 20 30 30 40 40))
(test "geolib:box-overlap-box, overlap"    #t (geolib:box-overlap-box 10 10 20 20  5  5 40 40))
(test "geolib:box-overlap-box, overlap"    #t (geolib:box-overlap-box 10 10 20 20 19 19 40 40))
(test "geolib:box-overlap-box, overlap"    #t (geolib:box-overlap-box 10 10 20 20  5 15 40 40))


;; #|
;;    (let loop ((a 0))
;;      (plot-line 
;;       ;; (vector->list (rotate-line (deg-to-rad a) (list->vector (list 30 0 50 0)) 0 0))
;;       (let ((pt (rotate-pt-around-pt (d) eg-to-rad a) 50 0 20 20)))
;;          (list 20 20 (car pt)(cadr pt)))
;;       *red*)
;;      (if (< a 360)
;;	  (loop (+ a 45))))
;;
;; |#
;; (test "rotate-ray" #f (rotate-ray  ))
;; (test "scale" #f (scale  ))
;; (test "test-intersection" #f (test-intersection  ))
;; (test "to-int" #f (to-int  ))
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<