File: VPath.m

package info (click to toggle)
cenon.app 4.0.6%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 35,392 kB
  • sloc: objc: 74,441; ansic: 1,270; sh: 124; makefile: 35
file content (10975 lines) | stat: -rw-r--r-- 441,415 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
/* VPath.m
 * complex path
 *
 * Copyright (C) 1996-2016 by Cenon GmbH
 * Author:   Georg Fleischmann, Ilonka Fleischmann
 *
 * created:  1996-01-29
 * modified: 2016-09-30 (-getLastObjectOfSubPath2: 30.0 * TOLERANCE instead 15)
 *           2016-09-28 (-getFirstObjectOfSubPath: fixed also if first object have a distance)
 *           2016-09-21 (-directionOfSubPath:: now we check more than one point)
 *           2016-09-21 (-optimizeSubPathsToClosedPath:::: if ( j > k ) wrong - removed)
 *           2016-09-20 (-contour:inlay:splitCurves: inlay calculation both with splitCurves:YES works a lot better)
 *           2016-07-21 (-contourOpenLeftOrRight: inside correction => change direction to counter feed (against rotation))
 *           2016-03-07 (-removeFaultGraphicsInSubpaths:,-optimizeSubPathsToClosedPath::: subPathCnt added for resizing array
 *           2015-11-20 (-subPathInsidePath:: break also for second for loop by check pts with tpoints
 *           2015-07-30 (-create: add temporary lines to [DocView tmpGraphics], [self setNeedsDisplayInRect:], lockFocus removed)
 *           2015-07-24 (-uniteWith: bigger tol, and new removing part for ug)
 *           2015-01-08 (-drawWithPrincipal: division with zero - principal is nil scaleFactor fixed)
 *           2014-10-09 (-contourOpenLeftOrRight: new)
 *           2014-10-05 (-optimizeSubPathsToClosedPath: a lot fixes)
 *           2014-08-29 (orthPointAtBegOrEnd(), -contour:inlay:splitCurves: VFloat instead float)
 *           2014-02-17 (-optimizeSubPathsToClosedPath: some fixes)
 *           2014-02-18 (if (f && !width && (filled > 1 && antialias) ))
 *           2012-12-12 (-drawGraduatedWithPrincipal: alpha added, another rounding problem exposed)
 *           2012-10-25 (-optimizePath: change position of inserted line for one -closeGapBetween::)
 *           2012-08-14 (-subPathInsidePath:: on check alot better)
 *           2012-07-17 (*pts = NULL, *iPts = NULL initialized)
 *           2012-06-12 (-optimizePath:, -pointWithNumBecomeStartPoint: corrected for open paths)
 *           2012-01-19 (-contour:inlay:splitCurves: simplified sc cases in two locations)
 *           2011-08-25 (-contour:inlay:splitCurves: pathCopy, and Autorelease pool)
 *                      (-subPathInsidePath::, -intersectionsForPtInside:with:, both, memory leaks closed)
 *           2011-05-02 (-contour:inlay:splitCurves: calc parallel points with cut if possible)
 *           2011-04-14 (-contour:inlay:splitCurves: replace curves with same curvePts in start/end)
 *           2011-04-06 (-pointWithNumBecomeStartPoint: added)
 *                      (-removePointWithNum:): [self deselectAll];
 *                      (-join:): getDirection
 *           2010-07-08 (-transform: added)
 *           2010-03-03 (-contour:inlay:splitCurves: and copy, setDirectionCCW:)
 *           2008-12-18 (-contour:inlay:splitCurves:, [gThis length] < 15.0*TOLERANCE)
 *           2008-12-01 (axial filling, draw unfilled path with stroke color)
 *           2008-10-16 (-uniteWith:)
 *           2008-10-11 (-changeDirection - open paths added)
 *           2008-07-14 (-directionOfSubPath::, -subPathInsidePath::, 360 arc inside Path)
 *           2008-07-25 (-contour:inlay:removeLoops: does not call -contourWithPixel any more !)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Cenon Public License as
 * published by Cenon GmbH. Among other things, the
 * License requires that the copyright notices and this notice
 * be preserved on all copies.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the Cenon Public License for more details.
 *
 * You should have received a copy of the Cenon Public License along
 * with this program; see the file LICENSE. If not, write to Cenon.
 *
 * Cenon GmbH, Schwabstr. 45, 72108 Rottenburg a.N., Germany
 * eMail: info@Cenon.com
 * http://www.Cenon.de
 */

#include <AppKit/AppKit.h>
#include <math.h>
#include <VHFShared/vhfMath.h>
#include <VHFShared/vhf2DFunctions.h>
#include <VHFShared/vhfCommonFunctions.h>
#include <VHFShared/types.h>
#include "../App.h"
#include "../DocView.h"
#include "../DocWindow.h"
#include "VLine.h"
#include "VCurve.h"
#include "VPath.h"
#include "PathContour.h"
#include "VArc.h"
#include "HiddenArea.h"
#include "../Inspectors.h"

static float angleBetweenGraphicsInStartOrEnd(id g1, id g2, BOOL end);

/* Private methods
 */
@interface VPath(PrivateMethods)
- (void)addToClosestEnd:obj;
- (BOOL)closeGapBetween:(VGraphic*)g1 and:(VGraphic*)g2;
- (int)isPointInsideOrOn:(NSPoint)p dist:(float)dist;
- (int)isPointInsideOrOn:(NSPoint)p dist:(float)dist subPath:(int)begIx :(int)endIx;
- (int)getLastObjectOfSubPath:(int)startIx tolerance:(double)tolerance;
//- (int)directionOfSubPath:(int)startIx :(int)endIx;
- (void)optimize;
//- (BOOL)subPathInsidePath:(int)begIx :(int)endIx;
- (void)optimizeSubPathsToClosedPath:(VPath*)path :(float)w :(BOOL**)subPathSplitted :(int)subPathCnt;
- (void)removeFaultGraphicsInSubpaths:(VPath*)path :(float)w;
- (void)setDirectionCCW:(BOOL)ccw;
- (id)contourOpen:(float)w;
- (void)changeDirectionOfSubPath:(int)startIx :(int)endIx;

- (id)contourReal:(float)w inlay:(BOOL)inlay splitCurves:(BOOL)splitCurves; // TEST ONLY !
@end

@implementation VPath

/*
 * This sets the class version so that we can compatibly read
 * old VGraphic objects out of an archive.
 */
+ (void)initialize
{
    [VPath setVersion:3];
}

+ (VPath*)path
{
    return [[[VPath allocWithZone:[self zone]] init] autorelease];
}

+ (VPath*)pathWithBezierPath:(NSBezierPath*)bezierPath
{   int		i, cnt = [bezierPath elementCount];
    VPath	*path;
    id		g;
    NSPoint	p0, pts[3], startP = NSZeroPoint;

    if (!cnt)
        return nil;
    path = [VPath path];
    for (i=0; i<cnt; i++)
    {
        switch ([bezierPath elementAtIndex:i associatedPoints:pts])
        {
            case NSMoveToBezierPathElement:
                p0 = startP = pts[0];
                break;
            case NSLineToBezierPathElement:
                g = [VLine lineWithPoints:p0 :pts[0]];
                [[path list] addObject:g];
                p0 = pts[0];
                break;
            case NSCurveToBezierPathElement:
                g = [VCurve curveWithPoints:p0 :pts[0] :pts[1] :pts[2]];
                [[path list] addObject:g];
                p0 = pts[2];
                break;
            case NSClosePathBezierPathElement:
                g = [VLine lineWithPoints:p0 :startP];
                [[path list] addObject:g];
        }
    }
    return path;
}

- init
{
    [super init];
    selectedObject = -1;
    list = [[NSMutableArray allocWithZone:[self zone]] init];
    fillColor = [[NSColor blackColor] retain];
    endColor  = [[NSColor blackColor] retain];
    graduateAngle = 0.0;
    stepWidth = 7.0;
    radialCenter = NSMakePoint(0.5, 0.5);
    graduateList = nil;
    graduateDirty = YES;
    coordBounds = bounds = NSZeroRect;
//    numPoints = 0;
    return self;
}

/* deep copy
 *
 * created:  2001-02-15
 * modified: 2010-03-03 (setDirectionCCW:)
 */
- copy
{   VPath   *path;
    int		i, cnt = [list count];

    path = [[VPath allocWithZone:[self zone]] init];
    [path setFilled:filled optimize:NO];
    [path setDirectionCCW:isDirectionCCW];
    [path setWidth:width];
    [path setSelected:isSelected];
    [path setLocked:NO];
    [path setColor:color];
    [path setFillColor:fillColor];
    [path setEndColor:endColor];
    [path setGraduateAngle:graduateAngle];
    [path setStepWidth:stepWidth];
    [path setRadialCenter:radialCenter];
    for (i=0; i<cnt; i++)
        [[path list] addObject:[[[list objectAtIndex:i] copy] autorelease]];
    return path;
}

- (NSString*)description
{   NSRect  bnds = [self bounds];

    return [NSString stringWithFormat:@"VPath: %f %f %f %f", bnds.origin.x, bnds.origin.y, bnds.size.width, bnds.size.height];
}

- (NSString*)title		{ return @"Path"; }

/* whether we are a path object
 * eg. line, polyline, arc, curve, rectangle, path
 * group is not a path object because we don't know what is inside!
 */
- (BOOL)isPathObject	{ return YES; }

- (void)setRectangle:(NSPoint)ll :(NSPoint)ur
{   VLine	*line;
    NSPoint	p0, p1;

    if (!list)
        list = [[NSMutableArray allocWithZone:[self zone]] init];
    else
        [list removeAllObjects];

    line = [VLine line];
    [line setColor:color];
    [line setWidth:width];
    p0 = ll;
    p1.x = ur.x; p1.y = ll.y;
    [line setVertices:p0 :p1];
    [list addObject:line];

    line = [VLine line];
    [line setColor:color];
    [line setWidth:width];
    p0 = p1;
    p1 = ur;
    [line setVertices:p0 :p1];
    [list addObject:line];

    line = [VLine line];
    [line setColor:color];
    [line setWidth:width];
    p0 = p1;
    p1.x = ll.x; p1.y = ur.y;
    [line setVertices:p0 :p1];
    [list addObject:line];

    line = [VLine line];
    [line setColor:color];
    [line setWidth:width];
    p0 = p1;
    p1 = ll;
    [line setVertices:p0 :p1];
    [list addObject:line];
    dirty = YES;
}

/* create
 * modified: 2015-07-30 (add temporary lines to [DocView tmpGraphics], [self setNeedsDisplayInRect:], lockFocus removed)
 */
#define CREATEEVENTMASK NSLeftMouseDraggedMask|NSLeftMouseDownMask|NSLeftMouseUpMask|NSPeriodicMask
- (BOOL)create:(NSEvent *)event in:(DocView*)view
{   NSRect          viewBounds, gridBounds, drawBounds;
    NSPoint         start, last, gridPoint, drawPoint, lastPoint = NSZeroPoint;
    id              window = [view window];
    VPath           *drawPathGraphic;   // this is a shadow path showing the actual mouse position (off the grid)
    BOOL            ok = YES, dragging = NO, inTimerLoop = NO;
    VFloat          grid = 1.0 /*(float)[view rasterSpacing]*/;
    int             windowNum = [event windowNumber];
    NSColor         *col = [self color];
    NSMutableArray  *tmpGraphics = [[view class] tmpGraphics];

    [[(App*)NSApp inspectorPanel] loadGraphic:self];    /* set the values of the inspector to self */

    start = [event locationInWindow];
    start = [view convertPoint:start fromView:nil];     /* convert window to view coordinates */
    [view hitEdge:&start spare:self];                   /* snap to point */
    start = [view grid:start];                          /* set on grid */
    viewBounds = [view visibleRect];                    /* get the bounds of the view */
    //[view lockFocus];                                 /* and lock the focus on view */

    [self setRectangle:start :start];
    drawPathGraphic = [[self copy] autorelease];
    [drawPathGraphic setColor:[NSColor lightGrayColor]];
    gridBounds = [self extendedBoundsWithScale:[view scaleFactor]];

    last = start;

    event = [NSApp nextEventMatchingMask:CREATEEVENTMASK untilDate:[NSDate distantFuture] inMode:NSEventTrackingRunLoopMode dequeue:YES];
    StartTimer(inTimerLoop);
    /* now entering the tracking loop
     */
    while ( ((!dragging && [event type] != NSLeftMouseDown) || (dragging && [event type] != NSLeftMouseUp))
           && [event type] != NSAppKitDefined && [event type] != NSSystemDefined )
    {
        /* Since MouseMoved event is never send we use a periodic event instead */
        if ( [event type] == NSPeriodic )
            drawPoint = [[[self class] currentWindow] mouseLocationOutsideOfEventStream];
        else
            drawPoint = [event locationInWindow];

        /* display only if mouse has moved */
        if ( drawPoint.x != lastPoint.x || drawPoint.y != lastPoint.y )
        {
            lastPoint = drawPoint;

            /* delete line from screen */
            [view setNeedsDisplayInRect:gridBounds];    //[view drawRect:gridBounds];
            drawPoint = [view convertPoint:drawPoint fromView:nil];
            if ( ([event type] == NSLeftMouseDragged)&&(!dragging) )
                dragging = YES;
            /* if user is dragging we scroll the view */
            if (dragging)
            {   [view scrollPointToVisible:drawPoint];
                viewBounds = [view bounds];
            }
            /* snap to point */
            gridPoint = drawPoint;
            [view hitEdge:&gridPoint spare:self];
            /* fix position to grid */
            gridPoint = [view grid:gridPoint];

            [window displayCoordinate:gridPoint ref:NO];

            [self setColor:col];
            [self setRectangle:start :gridPoint];
            gridBounds = [self extendedBoundsWithScale:[view scaleFactor]];	// get bounds of the grid line
            [drawPathGraphic setRectangle:start :drawPoint];
            drawBounds = [drawPathGraphic extendedBoundsWithScale:[view scaleFactor]];
            /* the united rect of the two rect¬s we need to redraw the view */
            gridBounds = NSUnionRect(drawBounds, gridBounds);

            [tmpGraphics removeAllObjects];
            /* if path is  inside view draw it */
            if ( NSContainsRect(viewBounds, gridBounds) )	/* line inside view ? */
            {
                [tmpGraphics addObject:drawPathGraphic];    // shadow path
                [tmpGraphics addObject:self];               // on the grid
            }
            else
                drawPoint = gridPoint = start;
            /* the united rect of the two rects we need to redraw the view */
            gridBounds = NSUnionRect(drawBounds, gridBounds);

            [window flushWindow];
        }
        event = [NSApp nextEventMatchingMask:CREATEEVENTMASK untilDate:[NSDate distantFuture] inMode:NSEventTrackingRunLoopMode dequeue:YES];
    }
    StopTimer(inTimerLoop);
    [tmpGraphics removeAllObjects];

    last = gridPoint;
    if ( fabs(last.x-start.x) <= grid && fabs(last.y-start.y) <= grid )		/* no length -> not valid */
        ok = NO;
    else if ( (!dragging && [event type]==NSLeftMouseDown)||(dragging && [event type]==NSLeftMouseUp) )
    {   /* double click or out of window -> not valid */
        if ([event clickCount] > 1 || [event windowNumber] != windowNum)
            ok = NO;
        else
            ok = NSMouseInRect(gridPoint, viewBounds , NO);
    }

    if ([event type] == NSAppKitDefined || [event type] == NSSystemDefined)
        ok = NO;

    //[view unlockFocus];

    if (!ok)
    {	[view display];
        return NO;
    }

    dirty = YES;
    //[view cacheGraphic:self];	// add to graphic cache

    return YES;
}

/* copy subpath-lists to main list
 */
- (id)unnest
{   NSMutableArray	*pList = [NSMutableArray array];
    int             i, cnt = [self count];

    for ( i=0; i<cnt; i++ )
    {	int         j, jCnt;
        VGraphic	*g = [[self list] objectAtIndex:i];

        if ([g isKindOfClass:[VPath class]])
        {
            jCnt = [(VPath*)g count];
            for ( j=0; j<jCnt; j++ )
                [pList addObject:[[(VPath*)g list] objectAtIndex:j]];
            [[(VPath*)g list] removeAllObjects];
        }
        else
            [pList addObject:g];
    }
    [self setList:pList];
    return self;
}

- (NSMutableArray*)list
{
    return list;
}

/* set new list and return the old list
 */
- (void)setList:aList
{
    [self setList:aList optimize:YES];
}
- (void)setList:aList optimize:(BOOL)optimize
{
    if (list)
        [list release];
    list = [aList retain];
    if ( optimize )
        [self optimize];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
}

/* returns the endpoints of an open path
 */
- (void)getEndPoints:(NSPoint*)p1 :(NSPoint*)p2
{
    *p1 = [[list objectAtIndex:0] pointWithNum:0];
    *p2 = [[list objectAtIndex:[list count]-1] pointWithNum:MAXINT]; 
}

- (unsigned)count
{
    return [list count];
}

- (unsigned)countRecursive
{   int	i, cnt = [list count];

    for (i=[list count]-1; i>=0; i--)
    {	id	g = [list objectAtIndex:i];

        if ([g isKindOfClass:[VPath class]])
            cnt += [g countRecursive];
    }
    return cnt;
}

/* created:  24.09.95
 * modified: 
 * purpose:  deselect all planes
 */
- (void)deselectAll
{   int	i;

    for (i=[list count]-1; i>=0; i--)
        [[list objectAtIndex:i] setSelected:NO];
}

/*
 * returns the selected knob (0 or 1) or -1
 */
- (int)selectedKnobIndex
{
    if ( ![list count] || selectedObject < 0)
        return -1;

    {   int	i, cnt, pCnt = 0, prevPCnt = 0;

        for (i=0, cnt = [list count]; i<cnt; i++)
        {   pCnt += [[list objectAtIndex:i] numPoints];
            if ( i == selectedObject )
                break;		// this object is our selected object
            prevPCnt = pCnt;	// count of pts befor this gr
        }
        return prevPCnt + [[list objectAtIndex:i] selectedKnobIndex];
    }
    return -1;
}

/*
 * set selection
 */
- (void)setSelected:(BOOL)flag
{
    if (!flag)
    {
	if (selectedObject >= 0)
            [[list objectAtIndex:selectedObject] setSelected:NO];
        selectedObject = -1;
    }
    [super setSelected:flag];
}

- (BOOL)filled
{
    return filled;
}

- (void)setFilled:(BOOL)flag
{
    [self setFilled:flag optimize:YES];
}
- (void)setFilled:(BOOL)flag optimize:(BOOL)optimize
{
    if (flag && optimize)
    {   [self closePath];
        [self setDirectionCCW:[self isDirectionCCW]];
    }
    filled = flag;
    if (optimize)
        [self optimize];
    dirty = YES;
    graduateDirty = YES;
}

- (void)setWidth:(float)w
{   int	i, cnt;

    for (i=0, cnt = [list count]; i<cnt; i++)
        [(VGraphic*)[list objectAtIndex:i] setWidth:w];

    width = w;
    dirty = YES;
}

- (void)setFillColor:(NSColor*)col
{
    if (fillColor) [fillColor release];
    fillColor = [((col) ? col : [NSColor blackColor]) retain];
    dirty = YES;
    graduateDirty = YES;
}
- (NSColor*)fillColor			{ return fillColor; }

- (void)setEndColor:(NSColor*)col
{
    if (endColor) [endColor release];
    endColor = [((col) ? col : [NSColor blackColor]) retain];
    dirty = YES;
    graduateDirty = YES;
}
- (NSColor*)endColor                { return endColor; }

- (void)setGraduateAngle:(float)a   { graduateAngle = a; dirty = YES; graduateDirty = YES; }
- (float)graduateAngle              { return graduateAngle; }

- (void)setStepWidth:(float)sw      { stepWidth = sw; dirty = YES; graduateDirty = YES; }
- (float)stepWidth                  { return stepWidth; }

- (void)setRadialCenter:(NSPoint)rc { radialCenter = rc; dirty = YES; graduateDirty = YES; }
- (NSPoint)radialCenter             { return radialCenter; }

- (NSMutableArray*)graduateList     { return graduateList; }

/* length of sub-path
 * this returns the length of objects from index to index in list
 * frIndex <= index <= toIndex
 *
 * created:  2008-01-13
 * modified: 2008-01-17
 */
- (float)lengthFrom:(int)frIx to:(int)toIx
{   float   len = 0.0;
    int     i;

    if (toIx >= [list count])
        toIx = [list count] - 1;
    for(i=frIx; i<=toIx; i++)
    {   VGraphic    *g = [list objectAtIndex:i];
        len += [g length];
    }
    return len;
}

/*
 * add a list to our list
 * after the operation we are selected, all of our objects are deselected
 */
- (void)addList:(NSArray*)addList at:(int)index
{   int	i, cnt;

    if (!list)
        list = [[NSMutableArray allocWithZone:[self zone]] init];

    cnt = [addList count];
    for (i=0; i<cnt; i++)
    {	id	g = [addList objectAtIndex:i];

        [g setSelected:NO];
        if ([g isKindOfClass:[VPath class]])	/* we dont want a path inside a path ! */
            [self addList:[g list] at:[list count]];
        else
            [list insertObject:g atIndex:index++];
    }
    [self optimize];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
}

/* optimize subpaths inside list of path
 * inner subpaths before outer subpaths (smallest first)
 */
- (NSRect)boundsOfSubpathFrom:(int)beg to:(int)end
{   int		i;
    NSRect	rect, bbox;

    bbox = [[list objectAtIndex:0] bounds];
    for ( i=beg; i<end; i++ )
    {   id	g = [list objectAtIndex:i];

        rect = [g bounds];
        bbox = NSUnionRect(rect, bbox);
    }
    return bbox;
}
- (void)optimize
{   int             i, j, k, l, kcnt, cnt, beg1, end1, beg2, end2;
    NSMutableArray	*subpaths = [NSMutableArray array];
    NSMutableArray 	*array1 = [NSMutableArray array], *array2 = [NSMutableArray array];
    NSRect          bounds1, bounds2;

    if ( !filled )
        return;

    /* array of indexes of subpaths (0 - 3 - 8) */
    [subpaths addObject:[NSNumber numberWithInt:0]];
    for ( i=0, cnt=[list count]; i<cnt; i=j+1 )
    {
        j = [self getLastObjectOfSubPath:i];
        [subpaths addObject:[NSNumber numberWithInt:j+1]];
    }

    /* compare bounds of subpath -> exchange if necessary */
    for ( i=0; i < (int)[subpaths count]-2; i++ )
    {
        beg1 = [[subpaths objectAtIndex:i] intValue];
        end1 = [[subpaths objectAtIndex:i+1] intValue]-1;
        bounds1 = [self boundsOfSubpathFrom:beg1 to:end1];

        for ( j=i+1; j<(int)[subpaths count]-1; j++ )
        {
            beg2 = [[subpaths objectAtIndex:j] intValue];
            end2 = [[subpaths objectAtIndex:j+1] intValue]-1;
            bounds2 = [self boundsOfSubpathFrom:beg2 to:end2];
            if ( bounds1.size.width*bounds1.size.height > bounds2.size.width*bounds2.size.height )
            {   NSAutoreleasePool	*pool;

                /* swap subpaths in list */
                [array1 replaceObjectsInRange:NSMakeRange(0, [array1 count]) withObjectsFromArray:list range:NSMakeRange(beg1, end1-beg1+1)];
                [array2 replaceObjectsInRange:NSMakeRange(0, [array2 count]) withObjectsFromArray:list range:NSMakeRange(beg2, end2-beg2+1)];
                [list replaceObjectsInRange:NSMakeRange(beg2, end2-beg2+1) withObjectsFromArray:array1];
                [list replaceObjectsInRange:NSMakeRange(beg1, end1-beg1+1) withObjectsFromArray:array2];

                /* update array of indexes of subpaths (0 - 3 - 8) */
                [subpaths removeAllObjects];
                pool = [NSAutoreleasePool new];
                [subpaths addObject:[NSNumber numberWithInt:0]];
                for ( k=0, kcnt=[list count]; k<kcnt; k=l+1 )
                {
                    l = [self getLastObjectOfSubPath:k];
                    [subpaths addObject:[NSNumber numberWithInt:l+1]];
                }
                [pool release];
                dirty = YES;
                i--; j=cnt;
            }
        }
    }

/*
    for ( i=0, cnt=[list count]; i<cnt; i=j+1 )
    {
        j = [self getLastObjectOfSubPath:i];
        NSLog(@"b:%d n:%d", i, j-i+1);
    }
*/
}

/* end point of g1 must fit to start point of g2
 */
- (BOOL)closeGapBetween:(VGraphic*)g1 and:(VGraphic*)g2
{   NSPoint	p, p0, p1;

    if ( ![g1 isKindOfClass:[VArc class]] )		/* g1 != arc */
    {
        if ( [g1 isKindOfClass:[VLine class]] && ![g2 isKindOfClass:[VArc class]] )
        {   NSPoint	p2, p3;

            [(VLine*)g1 getVertices:&p0 :&p1];
            p2 = [g2 pointWithNum:0];
            p3 = [g2 pointWithNum:MAXINT];
            if ( Diff(p0.y, p1.y) < TOLERANCE ) // g1 horicontal
            {
                if ( Diff(p1.y, p2.y) > TOLERANCE )
                    [g2 movePoint:0 to:p1]; // correct y difference of g2
                else if ( Diff(p1.x, p2.x) > TOLERANCE )
                    [g1 movePoint:MAXINT to:p2]; // correct x difference
            }
            else if ( Diff(p0.x, p1.x) < TOLERANCE ) // g1 vertical
            {
                if ( Diff(p1.x, p2.x) > TOLERANCE )
                    [g2 movePoint:0 to:p1]; // correct x difference
                else if ( Diff(p1.y, p2.y) > TOLERANCE )
                    [g1 movePoint:MAXINT to:p2]; // correct y difference
            }
            else
            {   p = [g2 pointWithNum:0];
                [g1 movePoint:MAXINT to:p];
            }
        }
        else
        {   p = [g2 pointWithNum:0];
            [g1 movePoint:MAXINT to:p];
        }
    }
    else if ( ![g2 isKindOfClass:[VArc class]] )	/* g2 != arc - g1 is an arc */
    {
        p = [g1 pointWithNum:MAXINT];
        [g2 movePoint:0 to:p];
    }
    else					/* g1, g2 == arc -> insert line */
    {	p0 = [g1 pointWithNum:MAXINT];
        p1 = [g2 pointWithNum:0];
        if ( Diff(p0.x, p1.x) || Diff(p0.y, p1.y) )
        {   VLine	*line = [VLine line];
            [line setColor:[g1 color]];
            [line setWidth:[g1 width]];
            [line setVertices:p0 :p1];
            [list insertObject:line atIndex:[list indexOfObject:g1]+1];
            return YES;
        }
    }
    dirty = YES;
    return NO;
}

- (BOOL)closed
{   int		i, cnt = [list count];
    id		g0, g1 = 0;
    NSPoint	beg, p0, p1;

    if ( !cnt )
        return YES;
    g0 = [list objectAtIndex:0];
    beg = [g0 pointWithNum:0];
    for (i=1; i<cnt; i++)
    {	g1 = [list objectAtIndex:i];

        p0 = [g0 pointWithNum:MAXINT];
        p1 = [g1 pointWithNum:0];
        /* connected with next object -> ok, continue */
        if ( Diff(p0.x, p1.x)<TOLERANCE && Diff(p0.y, p1.y)<TOLERANCE )
        {   g0 = g1;
            continue;
        }
        /* connected with beg -> ok, p1 is our new beg, continue */
        else if ( Diff(p0.x, beg.x)<TOLERANCE && Diff(p0.y, beg.y)<TOLERANCE )
        {   g0 = g1;
            beg = p1;
            continue;
        }
        /* not connected -> open end */
        return NO;
    }
    /* last object connected with beg -> ok */
    p0 = [g0 pointWithNum:MAXINT];
    if ( Diff(p0.x, beg.x)<TOLERANCE && Diff(p0.y, beg.y)<TOLERANCE )
        return YES;
    return NO;
}

- (void)closePath
{   int         i, iCnt;
    VGraphic    *g0, *g1 = nil;
    NSPoint     beg, p0, p1;
    float       dx=0, dy=0, dx0=0, dy0=0;

    if ( ![list count] )
        return;
    g0 = [list objectAtIndex:0];
    beg = [g0 pointWithNum:0];
    for ( i=1, iCnt = [list count]; i<iCnt; i++ )
    {	g1 = [list objectAtIndex:i];

        p0 = [g0 pointWithNum:MAXINT];
        p1 = [g1 pointWithNum:0];
        /* gap */
        dx = Diff(p0.x, p1.x);
        dy = Diff(p0.y, p1.y);
        if ( dx > 10*TOLERANCE || dy > 10*TOLERANCE )
        {
            /* if this is the end of a closed subpath we add no line */
            dx0 = Diff(p0.x, beg.x);
            dy0 = Diff(p0.y, beg.y);
            if ( dx0 > TOLERANCE || dy0 > TOLERANCE )
            {   VLine	*line = [VLine line];

                [line setColor:[g1 color]];
                [line setWidth:[g1 width]];

                // gap to next graphic smaller than to startgraphic -> close to nextG
                if ( dx < dx0 && dy < dy0 && dx < dy0 && dy < dx0 )
                {
                    [line setVertices:p0 :p1];
                    [list insertObject:line atIndex:i];
                    dirty = YES;
                    graduateDirty = YES;
                    i++; iCnt++;
                    g0 = g1;
                    continue;
                }
                [line setVertices:p0 :beg];
                [list insertObject:line atIndex:i];
                dirty = YES;
                graduateDirty = YES;
                i++; iCnt++;
            }
            g0 = g1;
            beg = p1;
        }
        else
            g0 = g1;
    }

    p0 = [g0 pointWithNum:MAXINT];
    p1 = beg;
    if ( /*iCnt==1 ||*/ Diff(p0.x, p1.x)>TOLERANCE || Diff(p0.y, p1.y)>TOLERANCE )
    {   VLine	*line = [VLine line];

        [line setColor:[g1 color]];
        [line setWidth:[g1 width]];
        [line setVertices:p0 :beg];
        [list addObject:line];
        dirty = YES;
        graduateDirty = YES;
    }
}
#if 0
- (void)closePath
{   int		i, iCnt;
    id		g0, g1 = 0;
    NSPoint	beg, p0, p1;

    if ( ![list count] )
        return;
    g0 = [list objectAtIndex:0];
    beg = [g0 pointWithNum:0];
    for ( i=1, iCnt = [list count]; i<iCnt; i++ )
    {	g1 = [list objectAtIndex:i];

        p0 = [g0 pointWithNum:MAXINT];
        p1 = [g1 pointWithNum:0];
        /* gap */
        if ( Diff(p0.x, p1.x)>10*TOLERANCE || Diff(p0.y, p1.y)>10*TOLERANCE )
        {
            /* if this is the end of a closed subpath we add no line */
            if ( Diff(p0.x, beg.x)>TOLERANCE || Diff(p0.y, beg.y)>TOLERANCE )
            {   VLine	*line = [VLine line];

                [line setColor:[g1 color]];
                [line setWidth:[g1 width]];
                [line setVertices:p0 :beg];
                [list insertObject:line atIndex:i];
                dirty = YES;
                i++; iCnt++;
            }
            g0 = g1;
            beg = p1;
        }
        else
            g0 = g1;
    }

    p0 = [g0 pointWithNum:MAXINT];
    p1 = beg;
    if ( /*iCnt==1 ||*/ Diff(p0.x, p1.x)>TOLERANCE || Diff(p0.y, p1.y)>TOLERANCE )
    {   VLine	*line = [VLine line];

        [line setColor:[g1 color]];
        [line setWidth:[g1 width]];
        [line setVertices:p0 :beg];
        [list addObject:line];
        dirty = YES;
    }
}
#endif

/* optimize objects in list, so that they line up correctly
 */
- (void)sortList
{   int			i, iCnt, begIx;
    NSPoint		beg, end, p;
    id			g;
    NSMutableArray	*jlist = list, *newList = [NSMutableArray array];
    float		dist = TOLERANCE;

    /* copy objects from jlist to nesList in correct order
     */
    while ( (iCnt = [jlist count]) )
    {
        g = [jlist objectAtIndex:0];
        [newList addObject:g];
        begIx = [newList count]-1;
        beg = [g pointWithNum:0];
        end = [g pointWithNum:MAXINT];
        [jlist removeObject:g];

        iCnt = [jlist count];
        for ( i=0; i<iCnt; i++ )
        {   g = [jlist objectAtIndex:i];
            p = [g pointWithNum:0];
            if ( SqrDistPoints(p, beg)<dist*dist )	/* start of new object fits to start of sequence */
            {	[g changeDirection];
                [newList insertObject:g atIndex:begIx];
                beg = [g pointWithNum:0];
            }
            else if ( SqrDistPoints(p, end)<dist*dist )	/* start of new object fits to end of sequence */
            {	[newList addObject:g];
                end = [g pointWithNum:MAXINT];
                dirty = YES;
            }
            else
            {	p = [g pointWithNum:MAXINT];
                if ( SqrDistPoints(p, beg)<dist*dist )	/* end of new object fits to start of sequence */
                {   [newList insertObject:g atIndex:begIx];
                    beg = [g pointWithNum:0];
                }
                else if ( SqrDistPoints(p, end)<dist*dist )	/* end of new object fits to end of sequence */
                {   [g changeDirection];
                    [newList addObject:g];
                    end = [g pointWithNum:MAXINT];
                }
                else
                    continue;
            }
            [jlist removeObject:g];	/* start from the beginning of jlist */
            iCnt = [jlist count];
            i = -1;
        }
    }
    [self setList:newList];
}

/* jlist	list of objects
 * dist		maximum distance between objects
 */
- (void)complexJoin:(NSMutableArray*)jlist distance:(float)dist
{   int         i;
    VGraphic    *g;

    // jlist is selected list
    [jlist removeObject:self];

    /* extract paths and add all objects inside jlist to list
     */
    for ( i=0; i < [jlist count]; i++ )
    {
	g = [jlist objectAtIndex:i];
        [g setOutputStream:nil];
        if ( [g isKindOfClass:[VRectangle class]] )
        {   g = [(VRectangle*)g pathRepresentation];
            [jlist replaceObjectAtIndex:i withObject:g];
        }
        if ( [g isKindOfClass:[VPath class]] )
        {   int	j, jCnt = [[(VPath*)g list] count];

            for ( j=0; j<jCnt; j++ )	/* copy object from g to jlist */
                [list addObject:[[(VPath*)g list] objectAtIndex:j]];
        }
        else
            [list addObject:g];
        [jlist removeObject:g];
        i--;
    }

    /* set new jlist
     */
    [self optimizePath:dist];

    [jlist addObject:self];
    [self setSelected:YES];

    /* if an object has no contact we close to the start of the sequence
     */
    if (filled)
        [self closePath];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
}
#if 0 // old
- (void)complexJoin:jlist distance:(float)dist
{   int		i, iCnt, begIx;
    NSPoint	beg, end, p;
    id		g;
    //BOOL	hasStart = NO;	/* it may happen that we join subpaths at their starting and end points! */

    [jlist removeObject:self];

    /* extract paths inside jlist to jlist
     */
    iCnt = [jlist count];
    for ( i=0; i<iCnt; i++ )
    {
	g = [jlist objectAtIndex:i];
        [g setOutputStream:nil];
        if ( [g isKindOfClass:[VRectangle class]] )
        {   g = [g pathRepresentation];
            [jlist replaceObjectAtIndex:i withObject:g];
        }
        if ( [g isKindOfClass:[VPath class]] )
        {   int	j, jCnt = [[g list] count];

            for ( j=0; j<jCnt; j++ )	/* copy object from g to jlist */
                [jlist addObject:[[g list] objectAtIndex:j]];
            [jlist removeObject:g];
            i--;
        }
    }

    /* copy objects from list to beginning of jlist
     */
    for ( i=[list count]-1; i>=0; i-- )
        [jlist insertObject:[list objectAtIndex:i] atIndex:0];
    [list removeAllObjects];

    /* copy objects from jlist to list in correct order
     */
    while ( (iCnt = [jlist count]) )
    {
        g = [jlist objectAtIndex:0];
        [list addObject:g];
        begIx = [list count]-1;
        beg = [g pointWithNum:0];
        end = [g pointWithNum:MAXINT];
        [jlist removeObject:g];

        iCnt = [jlist count];
        for ( i=0; i<iCnt; i++ )
        {   g = [jlist objectAtIndex:i];
            p = [g pointWithNum:0];
            if ( SqrDistPoints(p, beg)<dist*dist )	/* start of new object fits to start of sequence */
            {	[g changeDirection];
                [list insertObject:g atIndex:begIx];
                beg = [g pointWithNum:0];
                [self closeGapBetween:g and:[list objectAtIndex:begIx+1]];
            }
            else if ( SqrDistPoints(p, end)<dist*dist )	/* start of new object fits to end of sequence */
            {	[list addObject:g];
                end = [g pointWithNum:MAXINT];
                [self closeGapBetween:[list objectAtIndex:[list count]-2] and:g];
            }
            else
            {	p = [g pointWithNum:MAXINT];
                if ( SqrDistPoints(p, beg)<dist*dist )	/* end of new object fits to start of sequence */
                {   [list insertObject:g atIndex:begIx];
                    beg = [g pointWithNum:0];
                    [self closeGapBetween:g and:[list objectAtIndex:begIx+1]];
                }
                else if ( SqrDistPoints(p, end)<dist*dist )	/* end of new object fits to end of sequence */
                {   [g changeDirection];
                    [list addObject:g];
                    end = [g pointWithNum:MAXINT];
                    [self closeGapBetween:[list objectAtIndex:[list count]-2] and:g];
                }
                else if ( SqrDistPoints(beg, end) < TOLERANCE*TOLERANCE )
                    break; // closed sequence - time
                else // open sequence // close to start or search next obj
                    /* wenn current nicht closed zu start/beg / distance kleiner 1.0 */
                    /* hier muessen wir irgendwie das objekt mit dem kleinsten Abstand finden !? */
                    /* 4 distanzen merken ? - nur den kleinsten der 4 (zum Start oder continued !? - merken) */
                    /* objektIndex merken - flag setzen */
                    continue;
            }
            // if ( distanceObject ) beg / end setzen etc

            [jlist removeObject:g];	/* start from the beginning of jlist */
            iCnt = [jlist count];
            i = -1;
        }
    }

    /* if an object has no contact we close to the start of the sequence
     */
    if (filled)
        [self closePath];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
}
#endif

- (void)join:obj
{   BOOL    getDirection = NO;

    if (!list)
       list = [[NSMutableArray allocWithZone:[self zone]] init];

    if ( ![list count] )
        getDirection = YES;

    if ( [obj isKindOfClass:[VRectangle class]] )
        obj = [obj pathRepresentation];
    if ( [obj isKindOfClass:[NSMutableArray class]] )
    {
        [self complexJoin:obj distance:1.0]; // 0.1 30.0*TOLERANCE
    }
    /* two closed paths -> we simply place the objects of obj at the end of our list
     */
    else if ( ([obj isKindOfClass:[VPath class]] && [obj closed] && [self closed]) )
              //([obj isKindOfClass:[VPolyLine class]] && [obj filled] && [self closed]) 
    {	NSMutableArray	*olist = [obj list];
        int		i, cnt = [olist count];

        for (i=0; i<cnt; i++)
            [list addObject:[olist objectAtIndex:i]];
    }
    /* add other filled objects simply to the end of our list */
    else if ( [obj respondsToSelector:@selector(filled)] && [obj filled] && [self closed] )
    {
        [list addObject:obj];
    }
    /* add object to the end of ourself
     */
    else
    {
        if (![list count])	/* obj is the 1st object in list */
        {
            [list addObject:obj];
            [obj setOutputStream:nil];
        }
        else if ([obj selectedKnobIndex] != -1)	/* a knob of the new object is selected */
        {
            if ([self selectedKnobIndex] != -1)	/* a knob of us is selected */
                ;	/* add new object the way that both selected ends are connected */
            else
            {   [self addToClosestEnd:obj];	/* add new object with selected end to our closest end */
                [obj setOutputStream:nil];
            }
        }
        else	/* connect the closest endpoints */
        {   [self addToClosestEnd:obj];
            [obj setOutputStream:nil];
        }
    }

    //getDirection = YES; // for 1Line Font Direction editing ! ! !
    if ( getDirection )
    {   int sIx=0, eIx;

        eIx = [self getLastObjectOfSubPath2:sIx];
        isDirectionCCW = [self directionOfSubPath:sIx :eIx];
    }

    if ( filled || [self closed] )
        [self setDirectionCCW:[self isDirectionCCW]];
    [self optimize];
    [self deselectAll];
    selectedObject = -1;
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
}

- (void)addToClosestEnd:obj
{   NSPoint	pa, pb, p1, p2;
    float	da1, da2, db1, db2, dist = 100.0*TOLERANCE;
    int		ix;
    VLine	*g = 0;

    if ([obj selectedKnobIndex] >= 0)	/* knob of obj is selected */
    {	pa = [obj pointWithNum:[obj selectedKnobIndex]];
        if ( [obj selectedKnobIndex]==0 )
            pb.x = pb.y = LARGE_COORD;
        else
            pb = pa, pa.x = pa.y = LARGE_COORD;
    }
    else	/* no knob of object selected */
    {	if ([obj isKindOfClass:[VPath class]])
        [obj getEndPoints:&pa :&pb];
        else
        {   pa = [obj pointWithNum:0];
            pb = [obj pointWithNum:MAXINT];
        }
    }
    [self getEndPoints:&p1 :&p2];

    /* closer 1st point (p1) -> add object at beginning of list */
    da1 = SqrDistPoints(pa, p1);
    da2 = SqrDistPoints(pa, p2);
    db1 = SqrDistPoints(pb, p1);
    db2 = SqrDistPoints(pb, p2);
    /* circle */
    if ( [obj isKindOfClass:[VArc class]] && Abs([obj angle]) >= 360.0 )
        ix = [list count];
    else if ( da1<da2 && da1<db1 && da1<db2 )	/* pa / p1 */
    {
        [obj changeDirection];
        if (da1 && da1 < dist)	// close the gap with a line
        //if (da1)	// close the gap with a line	2005-03-29
        {   g = [VLine line];
            [g setVertices:pa :p1];
            [list insertObject:g atIndex:0];
        }
        ix = 0;	/* the new object becomes our 1st object in the list */
    }
    else if ( da2<=da1 && da2<=db1 && da2<=db2 )	/* pa / p2 */
    {
        if (da2 && da2 < dist)	// close the gap with a line
        //if (da2)	// close the gap with a line	2005-03-29
        {   g = [VLine line];
            [g setVertices:p2 :pa];
            [list insertObject:g atIndex:[list count]];
        }
        ix = [list count];	/* the new object becomes our last object */
    }
    else if ( db1<=da1 && db1<=da2 && db1<=db2 )	/* pb / p1 */
    {
        if (db1 && db1 < dist)	// close the gap with a line
        //if (db1)	// close the gap with a line	2005-03-29
        {   g = [VLine line];
            [g setVertices:pb :p1];
            [list insertObject:g atIndex:0];
        }
        ix = 0;	/* the new object becomes our 1st object in the list */
    }
    else	/* pb / p2 */
    {
        [obj changeDirection];
        if (db2 && db2 < dist)	// close the gap with a line
        //if (db2)	// close the gap with a line	2005-03-29
        {   g = [VLine line];
            [g setVertices:p2 :pb];
            [list insertObject:g atIndex:[list count]];
        }
        ix = [list count];	/* the new object becomes our last object */
    }

    [g setColor:color];
    [g setWidth:width];
    if ([obj isKindOfClass:[VPath class]])
    {	[self addList:[obj list] at:ix];
        [[obj list] removeAllObjects];
    }
    else
        [list insertObject:obj atIndex:ix];
}

/* split
 * modified: 2012-01-20 ( use getLastObjectOfSubPath2: to split open paths faster)
 * copy all objects from the path to the ulist
 * the ungrouped objects are selected
 */
- (void)splitTo:ulist
{   int	i, begIx = 0, endIx = 0, cnt = [list count];

    endIx = [self getLastObjectOfSubPath2:begIx];

    /* path with subpaths splitted to paths ! */
    if (endIx != cnt-1)
    {
        while (endIx <= cnt-1)
        {

            if (begIx == endIx)
            {   VGraphic    *g = [list objectAtIndex:begIx];

                [g setSelected:YES];
                [g setColor:color];
                [g setWidth:width];
                if (([g isKindOfClass:[VArc class]] && Diff(Abs([g angle]), 360.0) <= TOLERANCE) ||
                     [g isKindOfClass:[VRectangle class]] || [g isKindOfClass:[VPolyLine class]])
                {
                    [g setFilled:NO];
                    if (fillColor)
                    {   [(VArc*)g setFillColor:fillColor];
                        [(VArc*)g setStepWidth:stepWidth];
                        [(VArc*)g setRadialCenter:radialCenter];
                    }
                }
                [ulist addObject:g];
            }
            else
            {   VPath	*pg = [VPath path];

                [pg setFilled:NO];
                [pg setSelected:YES];
                [pg setColor:color];
                if (fillColor)
                {   [pg setFillColor:fillColor];
                    [pg setStepWidth:stepWidth];
                    [pg setRadialCenter:radialCenter];
                }
                [pg setWidth:width];
                for (i=begIx; i<=endIx; i++)
                    [[pg list] addObject:[list objectAtIndex:i]];
                [ulist addObject:pg];
            }
            begIx = endIx+1;
            if (begIx > cnt-1)
                break;
            endIx = [self getLastObjectOfSubPath2:begIx]; //  tolerance:TOLERANCE
        }
    }
    else
        for ( i = 0, cnt = [list count]; i < cnt; i++ )
        {	VGraphic    *g = [list objectAtIndex:i];

            [g setSelected:YES];
            [g setColor:color];
            [g setWidth:width];
            [ulist addObject:g];
        }
}


- (void)setSize:(NSSize)newSize
{   NSRect	bRect = [self coordBounds];

    [self scale:((bRect.size.width)  ? newSize.width /bRect.size.width  : 1.0)
               :((bRect.size.height) ? newSize.height/bRect.size.height : 1.0)
     withCenter:bRect.origin];
}
- (NSSize)size
{   NSRect	bRect = [self coordBounds];
    return bRect.size;
}

- (void)setBoundsZero
{
    coordBounds = bounds = NSZeroRect;
}

/* created:  16.09.95
 * modified: 2000-11-03
 *
 * Returns the bounds.
 */
- (NSRect)coordBounds
{
    if ( ![list count] )
        return NSZeroRect;

    if (coordBounds.size.width == 0.0 && coordBounds.size.height == 0.0)
    {   NSRect	rect;
        int	i, cnt = [list count]-1;

        coordBounds = [[list objectAtIndex:cnt] coordBounds];
        for (i=cnt-1; i>=0; i--)
        {   rect = [[list objectAtIndex:i] coordBounds];
            coordBounds = VHFUnionRect(rect, coordBounds);
        }
    }
    return coordBounds;
}

- (NSRect)bounds
{
    if ( ![list count] )
        return NSZeroRect;

    if (bounds.size.width == 0.0 && bounds.size.height == 0.0)
    {   NSRect	rect;
        int	i, cnt = [list count]-1;

        bounds = [[list objectAtIndex:cnt] bounds];
        for (i=cnt-1; i>=0; i--)
        {   rect = [[list objectAtIndex:i] bounds];
            bounds = VHFUnionRect(rect, bounds);
        }
    }
    return bounds;
}

/*
- (NSRect)extendedBoundsWithScale:(float)scale
{   NSRect	rect, bRect;
    int		i, cnt = [list count]-1;

    if ( cnt<0 )
        return NSZeroRect;
    bRect = [[list objectAtIndex:cnt] extendedBoundsWithScale:scale];
    for (i=cnt-1; i>=0; i--)
    {	rect = [[list objectAtIndex:i] extendedBoundsWithScale:scale];
        bRect = NSUnionRect(rect , bRect);
    }
    return bRect;
}
*/
/* created:  22.10.95
 * modified: 28.02.97
 *
 * Returns the bounds at the given rotation.
 */
- (NSRect)boundsAtAngle:(float)angle withCenter:(NSPoint)cp
{   NSRect	rect, bRect;
    int		i, cnt = [list count]-1;

    bRect = [(VGraphic*)[list objectAtIndex:cnt] boundsAtAngle:angle withCenter:cp];
    for (i=cnt-1; i>=0; i--)
    {	rect = [(VGraphic*)[list objectAtIndex:i] boundsAtAngle:angle withCenter:cp];
        bRect = NSUnionRect(rect , bRect);
    }
    return bRect;
}

- (void)drawKnobs:(NSRect)rect direct:(BOOL)direct scaleFactor:(float)scaleFactor
{
    if ( (NSIsEmptyRect(rect) || !NSIsEmptyRect(NSIntersectionRect(rect, [self extendedBoundsWithScale:scaleFactor]))) )
    {
	if ( VHFIsDrawingToScreen() && isSelected )
        {   int	i, cnt = [list count], step = (cnt<2000) ? 1 : cnt/2000;

            for ( i=cnt-1; i>=0; i-=step )
            {	id	obj = [list objectAtIndex:i];

                if ( isSelected || [obj isSelected] )
                {   BOOL	sel = [obj isSelected];

                    [obj setSelected:YES];
                    [obj drawKnobs:rect direct:direct scaleFactor:scaleFactor];
                    [obj setSelected:sel];
                }
            }
        }
    }
}
- (void)drawControls:(NSRect)rect direct:(BOOL)direct scaleFactor:(float)scaleFactor
{
    if ( (NSIsEmptyRect(rect) ||
          !NSIsEmptyRect(NSIntersectionRect(rect, [self extendedBoundsWithScale:scaleFactor]))) )
    {
	if ( VHFIsDrawingToScreen() && isSelected )
        {   int	i, cnt = [list count], step = (cnt<2000) ? 1 : cnt/2000;

            for ( i=cnt-1; i>=0; i-=step )
            {	id	obj = [list objectAtIndex:i];
                BOOL	sel = [obj isSelected];

                [obj setSelected:YES];
                //[obj drawKnobs:rect direct:direct scaleFactor:scaleFactor];
                [obj drawControls:rect direct:direct scaleFactor:scaleFactor];
                [obj setSelected:sel];
                if ([obj isMemberOfClass:[VCurve class]])
                {   [NSBezierPath setDefaultLineWidth:1.0/scaleFactor];
                    [NSBezierPath strokeLineFromPoint:[obj pointWithNum:0] toPoint:[obj pointWithNum:1]];
                    [NSBezierPath strokeLineFromPoint:[obj pointWithNum:3] toPoint:[obj pointWithNum:2]];
                }
            }
        }
    }
}

/*
 * Depending on the pt_num passed in, return the rectangle
 * that should be used for scrolling purposes. When the rectangle
 * passes out of the visible rectangle then the screen should
 * scroll. If the first and last points are selected, then the second
 * and third points are included in the rectangle. If the second and
 * third points are selected, then they are used by themselves.
 */
- (NSRect)scrollRect:(int)pt_num inView:(id)aView
{   VGraphic	*g = nil;

    if (pt_num != -1)
    {
        if ( pt_num >= [self numPoints] )
        {   g = [list objectAtIndex:[list count]-1];
            pt_num = MAXINT;
        }
        else if ( !pt_num )
            g = [list objectAtIndex:0];
        else
        {   int	i, cnt, pCnt = 0, prevPCnt = 0;

            for (i=0, cnt = [list count]; i<cnt; i++)
            {   pCnt += [[list objectAtIndex:i] numPoints];
                if ( pCnt > pt_num )
                    break;		// to this object refers our pt_num
                prevPCnt = pCnt;	// count of pts befor this gr
            }
            g = [list objectAtIndex:i];
            pt_num -= prevPCnt;
        }
        return [g scrollRect:pt_num inView:aView];
    }
    return [self bounds];
}

/* 
 * This method constains the point to the bounds of the view passed
 * in. Like the method above, the constaining is dependent on the
 * control point that has been selected.
 */
- (void)constrainPoint:(NSPoint *)aPt andNumber:(int)pt_num toView:aView
{   VGraphic	*g = nil;

    if (pt_num < 0)
        return;

    if ( pt_num >= [self numPoints] )
    {   g = [list objectAtIndex:[list count]-1];
        pt_num = MAXINT;
    }
    else if ( !pt_num )
        g = [list objectAtIndex:0];
    else
    {   int	i, cnt, pCnt = 0, prevPCnt = 0;

        for (i=0, cnt = [list count]; i<cnt; i++)
        {   pCnt += [[list objectAtIndex:i] numPoints];
            if ( pCnt > pt_num )
                break;		// to this object refers our pt_num
            prevPCnt = pCnt;	// count of pts befor this gr
        }
        g = [list objectAtIndex:i];
        pt_num -= prevPCnt;
    }
    [g constrainPoint:aPt andNumber:pt_num toView:aView];
}

- (NSPoint)nearestPointOnObject:(int*)objIndex distance:(float*)distance toPoint:(NSPoint)pt
{   int		i, cnt = [list count];
    NSPoint	cpt = NSZeroPoint, tpt;

    *distance = MAXCOORD;

    /* search nearest object to pt */
    for (i=0; i<cnt; i++)
    {	float		dist = MAXCOORD;
        VGraphic	*g = [list objectAtIndex:i];
        NSRect 		bRect = [g bounds];

        bRect = NSInsetRect(bRect, -2.0, -2.0);
        if ( !NSPointInRect(pt, bRect) )
            continue;
        if ([g isKindOfClass:[VLine class]])
        {   NSPoint	p0, p1;

            [(VLine*)g getVertices:&p0 :&p1];
            dist = pointOnLineClosestToPoint(p0, p1, pt, &tpt);
        }
        else if ([g isKindOfClass:[VArc class]])
            dist = [(VArc*)g getPointOnArcClosestToPoint:pt intersection:&tpt];
            //dist = pointOnArcClosestToPoint([g center], [g radius], [(VArc*)g begAngle], [g angle], pt, &tpt);
        else if ([g isKindOfClass:[VCurve class]])
        {   NSPoint	pc[4];

            [(VCurve*)g getVertices:&pc[0] :&pc[1] :&pc[2] :&pc[3]];
            dist = pointOnCurveNextToPoint(&tpt, pc, &pt);
        }
        else if ([g isKindOfClass:[VPolyLine class]])
        {   NSPoint	ppt;
            float	d;
            int		j, count = [g numPoints];

            dist = MAXCOORD;
            /* check nearest polyline line to pt */
            for (j=0; j<count-1; j++)
            {
                if ((d=pointOnLineClosestToPoint([g pointWithNum:j], [g pointWithNum:j+1], pt, &ppt)) <= dist)
                {   tpt = ppt;
                    dist = d;
                }
            }
        }
        else if ([g isKindOfClass:[VRectangle class]])
        {   VPath	*rp = [(VRectangle*)g pathRepresentation];
            int		j, rcnt = [[rp list] count];

            dist = MAXCOORD;
            for (j=0; j<rcnt; j++)
            {	float		d = MAXCOORD;
                VGraphic	*rg = [[rp list] objectAtIndex:j];
                NSRect 		bRect = [g bounds];
                NSPoint		rpt;

                bRect = NSInsetRect(bRect, -2.0, -2.0);
                if ( !NSPointInRect(pt, bRect) )
                    continue;
                if ([rg isKindOfClass:[VLine class]])
                {   NSPoint	p0, p1;

                    [(VLine*)rg getVertices:&p0 :&p1];
                    d = pointOnLineClosestToPoint(p0, p1, pt, &rpt);
                }
                else if ([rg isKindOfClass:[VArc class]])
                    d = [(VArc*)rg getPointOnArcClosestToPoint:pt intersection:&rpt];
                    //d = pointOnArcClosestToPoint([rg center], [rg radius], [(VArc*)rg begAngle], [rg angle], pt, &rpt);
                if (d <= dist)
                {   tpt = rpt;
                    dist = d;
                }
            }
        }
        if (dist <= *distance)
        {   cpt = tpt;
            *objIndex = i;
            *distance = dist;
        }
    }
    return cpt;
}

- (VGraphic*)addPointAt:(NSPoint)pt
{   NSMutableArray	*spList = nil;
    int			i, splitI = -1;
    NSPoint		cpt, start, end, sgStart, sgEnd;
    NSAutoreleasePool 	*pool = [NSAutoreleasePool new];
    float		distance=MAXCOORD;
    VGraphic		*splitg=nil;

    cpt = [self nearestPointOnObject:&splitI distance:&distance toPoint:pt];

    splitg = [list objectAtIndex:splitI];

    /* VPolyLine */
    if ([splitg isKindOfClass:[VPolyLine class]])
    {
        [(VPolyLine*)splitg addPointAt:pt];
        return self;
    }

    start = [self pointWithNum:0];
    end = [self pointWithNum:MAXINT];
    if ( (Diff(start.x, cpt.x) < 100.0*TOLERANCE && Diff(start.y, cpt.y) < 100.0*TOLERANCE) ||
         (Diff(end.x, cpt.x) < 100.0*TOLERANCE && Diff(end.y, cpt.y) < 100.0*TOLERANCE) )
    {   [pool release];
        return nil;
    }
    sgStart = [splitg pointWithNum:0];
    sgEnd = [splitg pointWithNum:MAXINT];
    if ((Diff(sgStart.x, cpt.x) > 100.0*TOLERANCE || Diff(sgStart.y, cpt.y) > 100.0*TOLERANCE) &&
        (Diff(sgEnd.x, cpt.x) > 100.0*TOLERANCE || Diff(sgEnd.y, cpt.y) > 100.0*TOLERANCE))
        spList = [splitg getListOfObjectsSplittedFrom:&cpt :1];
    else // nothing to add at s or e point
    {   [pool release];
        return nil;
    }
    /* remove splitg - add graphics from splist */
    [list removeObjectAtIndex:splitI];
    for (i=[spList count]-1; i>=0; i--)
        [list insertObject:[spList objectAtIndex:i] atIndex:splitI];

    [pool release];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
    return self;
}

/* the indices of the graphics around selected Point (which will be removed later) */
/* in correct order */
/* the index which will have the changed graphic will be returned */
- (int)changedValuesForRemovePointUndo:(int*)changedIx :(int*)chPt_num :(NSPoint*)changedPt
{   int		removedIx = -1, pt_num, begIx, endIx, nPts;
    VGraphic	*sg = [list objectAtIndex:selectedObject], *g1; // selectedObject
    NSPoint	sgPtStart, sgPtEnd;
    BOOL	connected = NO;

    if ( ![list count] || selectedObject < 0)
        return -4;

    pt_num = [sg selectedKnobIndex];
    nPts = [sg numPoints];

    /* point inside PolyLine */
    if ([sg isKindOfClass:[VPolyLine class]] && pt_num && pt_num < nPts-1 && nPts > 2)
    {
        chPt_num[0] = pt_num;   	     // we need pt_num inside PolyLine
        changedIx[0] = selectedObject; // and index of PolyLine inside Path
        removedIx = -1;
        return removedIx;
    }

    /* beg/end to selectedObjects subPath, + or - gr */
    begIx = [self getFirstObjectOfSubPath:selectedObject];
    endIx = [self getLastObjectOfSubPath:begIx];
    if (begIx == endIx)
        endIx = [list count]-1;

    if (([sg isKindOfClass:[VCurve class]] && (pt_num == 1 || pt_num == 2)) || 	// curve points 1,2
        ([sg isKindOfClass:[VArc class]] && pt_num == 2))			// arc center
        return -4;

    sgPtStart = [sg pointWithNum:0]; // notice old start point
    sgPtEnd = [sg pointWithNum:MAXINT]; // notice old end point

    /* get the connected Graphic to sg (selectedObject) */
    if (!pt_num) // corresponding gr is bevor sg
    {   NSPoint	g1PtEnd;

        g1 = (selectedObject-1>=begIx) ? [list objectAtIndex:selectedObject-1] : [list objectAtIndex:endIx];
        if ([sg isKindOfClass:[VArc class]] && [g1 isKindOfClass:[VArc class]])
            return -4; // two arcs we cant remove one and close the path Fix Me: open path and arc at end

        g1PtEnd = [g1 pointWithNum:MAXINT];
        if ( Diff(g1PtEnd.x, sgPtStart.x) < TOLERANCE && Diff(g1PtEnd.y, sgPtStart.y) < TOLERANCE)
            connected = YES;

        if (!connected && [sg isKindOfClass:[VPolyLine class]] && nPts > 2)
        {
            chPt_num[0] = pt_num;	 	// we need pt_num inside PolyLine
            changedIx[0] = selectedObject; // and index of PolyLine inside Path
            changedPt[0] = [sg pointWithNum:pt_num]; // old start point
            removedIx = -3;
            //[(VPolyLine*)g removePointWithNum:pt_num];
        }
        else if (!connected)
        {
            changedIx[0] = -1;
            removedIx = selectedObject; // notice the removed Graphic !
            changedPt[0] = [g1 pointWithNum:MAXINT]; // no point
            chPt_num[0] = -1;
            //[list removeObjectAtIndex:selectedObject];
        }

        else if ([sg isKindOfClass:[VPolyLine class]] && nPts > 2 && ![g1 isKindOfClass:[VArc class]])
        {
            chPt_num[0] = pt_num;	 // we need pt_num inside PolyLine // was pt_num+1
            changedIx[0] = selectedObject; // and index of PolyLine inside Path
            changedPt[0] = [sg pointWithNum:pt_num]; // old start point // was pt_num+1
            removedIx = -2;
            chPt_num[1] = MAXINT;
            changedIx[1] = (selectedObject-1>=begIx) ? (selectedObject-1) : (endIx);
            changedPt[1] = [g1 pointWithNum:MAXINT]; // g1 end will be moved to new sg start
            //[(VPolyLine*)g removePointWithNum:pt_num];
            //[g1 movePoint:MAXINT to:[g pointWithNum:0]]; // move g1 end to new start of polyLine
        }
        /* else if ([g1 isKindOfClass:[VPolyLine class]] && [g1 numPoints] > 2)
        {
            chPt_num[0] = [g1 numPoints]-2;	 // we need pt_num inside PolyLine
            changedIx[0] = (selectedObject-1>=begIx) ? (selectedObject-1) : (endIx); // and index of PolyLine inside Path
            changedPt[0] = [g1 pointWithNum:[g1 numPoints]-2]; // old start point
            removedIx = -3;
            //[(VPolyLine*)g1 removePointWithNum:MAXINT];
            //[g1 movePoint:MAXINT to:gPtStart];	// move previous (now last) point of polyline to close path
        } */
        else if ([g1 isKindOfClass:[VArc class]])			// remove g1
        {
            changedIx[0] = selectedObject;
            removedIx = (selectedObject-1>=begIx) ? (selectedObject-1) : (endIx);
            changedPt[0] = [sg pointWithNum:0]; // old start point
            chPt_num[0] = 0;
            //[g movePoint:0 to:[g1 pointWithNum:0]];	// close Gap with sg start to g1 start
            //[list removeObjectAtIndex:(selectedObject-1>=begIx) ? (selectedObject-1) : (endIx)];
        }
        else					// remove g
        {   
            changedIx[0] = (selectedObject-1>=begIx) ? (selectedObject-1) : (endIx);
            removedIx = selectedObject;
            changedPt[0] = [g1 pointWithNum:MAXINT]; // old end point
            chPt_num[0] = [g1 numPoints]-1;
            //[g1 movePoint:MAXINT to:gPtEnd]; 	// close Gap with g1 end to g end
            //[list removeObjectAtIndex:selectedObject];
        }
    }
    else // corresponding gr is behind g
    {   NSPoint	g1PtStart ;

        g1 = (selectedObject+1<=endIx) ? [list objectAtIndex:selectedObject+1] : [list objectAtIndex:begIx];

        if ([sg isKindOfClass:[VArc class]] && [g1 isKindOfClass:[VArc class]])
            return -4; // two arcs we cant remove one and close the path Fix Me: open path and arc at end

        g1PtStart = [g1 pointWithNum:0];
        if ( Diff(g1PtStart.x, sgPtEnd.x) < TOLERANCE && Diff(g1PtStart.y, sgPtEnd.y) < TOLERANCE)
            connected = YES;

        if (!connected && [sg isKindOfClass:[VPolyLine class]] && nPts > 2)
        {
            chPt_num[0] = nPts-1;	 // we need pt_num inside PolyLine
            changedIx[0] = selectedObject; // and index of PolyLine inside Path
            changedPt[0] = [sg pointWithNum:nPts-1]; // old start point
            removedIx = -3;
            //[(VPolyLine*)sg removePointWithNum:pt_num];
        }
        else if (!connected)
        {
            changedIx[0] = -1;
            removedIx = selectedObject; // notice only the removed Gr
            changedPt[0] = [sg pointWithNum:0];
            chPt_num[0] = -1;
            //[list removeObjectAtIndex:selectedObject];
        }

        else if ([g1 isKindOfClass:[VPolyLine class]] && [g1 numPoints] > 2 && ![sg isKindOfClass:[VArc class]])
        {
            chPt_num[0] = 0;	 // we need pt_num inside PolyLine // was 1
            changedIx[0] = (selectedObject+1 <= endIx) ? (selectedObject+1) : (begIx); // index of PolyLine inside Path
            changedPt[0] = [g1 pointWithNum:0]; // old point // was 1
            removedIx = -2;
            chPt_num[1] = MAXINT;
            changedIx[1] = selectedObject;
            changedPt[1] = [sg pointWithNum:MAXINT]; // sg end will be moved to new g1 start
            //[(VPolyLine*)g1 removePointWithNum:0];
            //[g movePoint:MAXINT to:[g1 pointWithNum:0]];	// move start of g to new start of polyline
        }
        /* else if ([sg isKindOfClass:[VPolyLine class]] && nPts > 2)
        {
            chPt_num[0] = nPts-2;	 // we need pt_num inside PolyLine
            changedIx[0] = selectedObject; // and index of PolyLine inside Path
            changedPt[0] = [sg pointWithNum:nPts-2]; // old start point
            removedIx = -3;
            //[(VPolyLine*)g removePointWithNum:MAXINT];
            //[g movePoint:MAXINT to:gPtEnd];	// move previous (now last) point of polyline to close path
        } */
        else if ([sg isKindOfClass:[VArc class]])		// remove g
        {
            changedIx[0] = (selectedObject+1 <= endIx) ? (selectedObject+1) : (begIx);
            removedIx = selectedObject;
            changedPt[0] = [g1 pointWithNum:0]; // old start point
            chPt_num[0] = 0;
            //[g1 movePoint:0 to:gPtStart]; 		// close Gap with g1 start to g start
            //[list removeObjectAtIndex:selectedObject];
        }
        else							// remove g1
        {   changedIx[0] = selectedObject;
            removedIx = (selectedObject+1<=endIx) ? (selectedObject+1) : (begIx);
            changedPt[0] = [sg pointWithNum:MAXINT]; // old end point
            chPt_num[0] = [sg numPoints]-1;
            //[g movePoint:MAXINT to:[g1 pointWithNum:MAXINT]];	// close Gap with g end to g1 end
            //[list removeObjectAtIndex:(selectedObject+1<=endIx) ? (selectedObject+1) : (begIx)];
        }
    }
    return removedIx;
}

/* return YES if we remove something - undo (from -AddPoint) must add the oldGraphic */
- (BOOL)removeGraphicsAroundPoint:(NSPoint)pt andIndex:(int)oldIndex
{   VGraphic	*atGr, *oGr;
    int		begIx, endIx;
    NSPoint	gPtStart, gPtEnd, oPt={0,0};

    atGr = [list objectAtIndex:oldIndex];
    if ([atGr isKindOfClass:[VPolyLine class]] && [atGr numPoints] > 2)
    {   int	pt_num; // num of pt in polyline

        pt_num = [(VPolyLine*)atGr removePoint:pt];
        /* close Gap to prev/next Object if start/end pt of polyline */
        if (!pt_num || pt_num >= [atGr numPoints]-1) // start or end point
            [atGr movePoint:pt_num to:pt]; // set new start/end pt to old start/end point

        return NO;
    }
    begIx = [self getFirstObjectOfSubPath:oldIndex];
    endIx = [self getLastObjectOfSubPath:begIx];
    if (begIx == endIx)
        endIx = [list count]-1;

    gPtStart = [atGr pointWithNum:0]; // start point
    gPtEnd   = [atGr pointWithNum:MAXINT]; // end point

    /* check graphic atIndex and behind */
    if ( Diff(gPtEnd.x, pt.x) <= TOLERANCE && Diff(gPtEnd.y, pt.y) <= TOLERANCE )
    {
        oGr = (oldIndex+1<=endIx) ? [list objectAtIndex:oldIndex+1] : [list objectAtIndex:begIx];
        oPt = [oGr pointWithNum:0];
        if ( Diff(gPtEnd.x, oPt.x) <= TOLERANCE && Diff(gPtEnd.y, oPt.y) <= TOLERANCE )
        {
            [list removeObjectAtIndex:(oldIndex+1<=endIx) ? (oldIndex+1) : (begIx)];
            [list removeObjectAtIndex:oldIndex];
        }
        else NSLog(@"VPath.m: removeGraphicsAroundPoint: normally impossible 1");
    }
    /* check graphic atIndex and befor */
    else if ( Diff(gPtEnd.x, pt.x) <= TOLERANCE && Diff(gPtEnd.y, pt.y) <= TOLERANCE )
    {
        oGr = (oldIndex-1>=begIx) ? [list objectAtIndex:oldIndex-1] : [list objectAtIndex:endIx];
        oPt = [oGr pointWithNum:MAXINT];
        if ( Diff(gPtStart.x, oPt.x) <= TOLERANCE && Diff(gPtStart.y, oPt.y) <= TOLERANCE )
        {
            [list removeObjectAtIndex:oldIndex];
            [list removeObjectAtIndex:(oldIndex-1<=endIx) ? (oldIndex-1) : (endIx)];
        }
        else NSLog(@"VPath.m: removeGraphicsAroundPoint: normally impossible 2");
    }
    else NSLog(@"VPath.m: removeGraphicsAroundPoint: normally impossible 3");

    return YES;
}

- (BOOL)removePointWithNum:(int)pt_num
{   VGraphic    *g=nil, *g1;
    int         begIx, endIx, curObject = -1, nPts;
    NSPoint     gPtStart, gPtEnd, gPtWithNum; // notice old end point
    BOOL        connected = NO;

    if ( ![list count] || pt_num < 0 )
        return YES;

    [self deselectAll];
    selectedObject = -1;

    /* beyond list -> point number of end point */
    if ( pt_num >= [self numPoints] )
    {   g = [list objectAtIndex:[list count]-1];
        pt_num = MAXINT;
        curObject = [list count]-1;
    }
    else if ( !pt_num )
    {   g = [list objectAtIndex:0];
        curObject = 0;
    }
    else
    {   int	i, cnt, pCnt = 0, prevPCnt = 0;

        for (i=0, cnt = [list count]; i<cnt; i++)
        {   pCnt += [[list objectAtIndex:i] numPoints];
            if ( pCnt > pt_num )
                break;		// to this object refers our pt_num
            prevPCnt = pCnt;	// count of pts befor this gr
        }
        g = [list objectAtIndex:i];
        pt_num -= prevPCnt;
        curObject = i;
    }
    if (!g)
        return YES;
    begIx = [self getFirstObjectOfSubPath:curObject];
    endIx = [self getLastObjectOfSubPath:begIx];
    if (begIx == endIx)
        endIx = [list count]-1;

    gPtStart = [g pointWithNum:0]; // notice old start point
    gPtEnd = [g pointWithNum:MAXINT]; // notice old end point
    gPtWithNum = [g pointWithNum:pt_num]; // notice old end point
    nPts = [g numPoints];

    if (([g isKindOfClass:[VCurve class]] && (pt_num == 1 || pt_num == 2)) || 	// curve points 1,2
        ([g isKindOfClass:[VArc class]] && pt_num == 2))			// arc center
        return YES;
    if ([g isKindOfClass:[VPolyLine class]] && nPts > 2 && pt_num && pt_num < nPts-1)
    {   [(VPolyLine*)g removePointWithNum:pt_num];
        return YES;
    }

    /* get the connected Graphic to g (curObject) */
    if (!pt_num) // corresponding gr is bevor g
    {   NSPoint	g1PtEnd;

        g1 = (curObject-1>=begIx) ? [list objectAtIndex:curObject-1] : [list objectAtIndex:endIx];
        if ([g isKindOfClass:[VArc class]] && [g1 isKindOfClass:[VArc class]])
            return YES; // two arcs we cant remove one and close the path Fix Me: open path and arc at end

        g1PtEnd = [g1 pointWithNum:MAXINT];
        if ( Diff(g1PtEnd.x, gPtStart.x) < TOLERANCE && Diff(g1PtEnd.y, gPtStart.y) < TOLERANCE)
            connected = YES;

        if (!connected && [g isKindOfClass:[VPolyLine class]] && nPts > 2)
        {
            [(VPolyLine*)g removePointWithNum:pt_num];
        }
        else if (!connected)
        {
            [list removeObjectAtIndex:curObject];
        }
        else if ([g isKindOfClass:[VPolyLine class]] && nPts > 2 && ![g1 isKindOfClass:[VArc class]])
        {
            [(VPolyLine*)g removePointWithNum:pt_num];
            [g1 movePoint:MAXINT to:[g pointWithNum:0]]; // move g1 end to new start of polyLine
        }
        /* else if ([g1 isKindOfClass:[VPolyLine class]] && [g1 numPoints] > 2)
        {
            [(VPolyLine*)g1 removePointWithNum:MAXINT];
            [g1 movePoint:MAXINT to:gPtStart];	// move previous (now last) point of polyline to close path
        } */
        else if ([g1 isKindOfClass:[VArc class]])			// remove g1
        {
            [g movePoint:0 to:[g1 pointWithNum:0]];	// close Gap with g start to g start
            [list removeObjectAtIndex:(curObject-1>=begIx) ? (curObject-1) : (endIx)];
        }
        else					// remove g
        {   [g1 movePoint:MAXINT to:gPtEnd]; 	// close Gap with g1 end to g end
            [list removeObjectAtIndex:curObject];
        }
    }
    else // corresponding gr is behind g
    {   NSPoint	g1PtStart;

        g1 = (curObject+1<=endIx) ? [list objectAtIndex:curObject+1] : [list objectAtIndex:begIx];

        if ([g isKindOfClass:[VArc class]] && [g1 isKindOfClass:[VArc class]])
            return YES; // two arcs we cant remove one and close the path Fix Me: open path and arc at end

        g1PtStart = [g1 pointWithNum:0];
        if ( Diff(g1PtStart.x, gPtEnd.x) < TOLERANCE && Diff(g1PtStart.y, gPtEnd.y) < TOLERANCE)
            connected = YES;

        if (!connected && [g isKindOfClass:[VPolyLine class]] && nPts > 2)
        {
            [(VPolyLine*)g removePointWithNum:pt_num];
        }
        else if (!connected)
        {
            [list removeObjectAtIndex:curObject];
        }
        else if ([g1 isKindOfClass:[VPolyLine class]] && [g1 numPoints] > 2 && ![g isKindOfClass:[VArc class]])
        {
            [(VPolyLine*)g1 removePointWithNum:0];
            [g movePoint:MAXINT to:[g1 pointWithNum:0]];	// move start of g to new start of polyline
        }
        /* else if ([g isKindOfClass:[VPolyLine class]] && nPts > 2)
        {
            [(VPolyLine*)g removePointWithNum:MAXINT];
            [g movePoint:MAXINT to:gPtEnd];	// move previous (now last) point of polyline to close path
        } */
        else if ([g isKindOfClass:[VArc class]])		// remove g
        {
            [g1 movePoint:0 to:gPtStart]; 		// close Gap with g1 start to g start
            [list removeObjectAtIndex:curObject];
        }
        else							// remove g1
        {   [g movePoint:MAXINT to:[g1 pointWithNum:MAXINT]];	// close Gap with g end to g1 end
            [list removeObjectAtIndex:(curObject+1<=endIx) ? (curObject+1) : (begIx)];
            
        }
    }

    if ( ![list count] )
        return NO; // hole graphic will removed in DocView.m -delete
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
    return YES;
}

/*
 * pt_num is the changing control point. pt holds the relative change in each coordinate. 
 * The relative is needed and not the absolute because the closest inside control point
 * changes when one of the outside points change.
 */
- (void)movePoint:(int)pt_num to:(NSPoint)p
{   VGraphic	*g=nil, *g1;
    BOOL	control = [(App*)NSApp control];
    int		begIx, endIx, curObject = -1;
    NSPoint	gPtStart, gPtEnd, gPtWithNum; // notice old end point

    if ( ![list count] || pt_num < 0 )
        return;
    /* beyond list -> point number of end point */
    if ( pt_num >= [self numPoints] )
    {   g = [list objectAtIndex:[list count]-1];
        pt_num = MAXINT;
        curObject = [list count]-1;
    }
    else if ( !pt_num )
    {   g = [list objectAtIndex:0];
        curObject = 0;
    }
    else
    {   int	i, cnt, pCnt = 0, prevPCnt = 0;

        for (i=0, cnt = [list count]; i<cnt; i++)
        {   pCnt += [[list objectAtIndex:i] numPoints];
            if ( pCnt > pt_num )
                break;		// to this object refers our pt_num
            prevPCnt = pCnt;	// count of pts befor this gr
        }
        g = [list objectAtIndex:i];
        pt_num -= prevPCnt;
        curObject = i;
    }
    if (!g)
        return;

    if ( [g isKindOfClass:[VCurve class]] && (pt_num == 1 || pt_num == 2) )
    {
        [g movePoint:pt_num to:p]; // move only the control pt
        coordBounds = bounds = NSZeroRect;
        dirty = YES;
        graduateDirty = YES;
        return;
    }

    begIx = [self getFirstObjectOfSubPath:curObject];
    endIx = [self getLastObjectOfSubPath:begIx];
    if (begIx == endIx)
        endIx = [list count]-1;

    gPtStart = [g pointWithNum:0]; // notice old start point
    gPtEnd = [g pointWithNum:MAXINT]; // notice old end point
    gPtWithNum = [g pointWithNum:pt_num]; // notice old end point

    /* move point connected to pt_num */
    g1 = (curObject+1<=endIx) ? [list objectAtIndex:curObject+1] : [list objectAtIndex:begIx];
    if ([g isKindOfClass:[VArc class]])
    {   int	i = 2, stop = 0;
        NSPoint	g1PtEnd = [g1 pointWithNum:MAXINT]; // notice old end point

        [g movePoint:pt_num to:p];
        /* move graphics at end of arc g */
        if (DiffPoint([g1 pointWithNum:0], gPtEnd) <= TOLERANCE)
        {   /* move only if control is set (else point never match) or no arc */
            if (control || ![g1 isKindOfClass:[VArc class]])
                [g1 movePoint:0 to:[g pointWithNum:MAXINT]];
            if (control) // move also graphics at end of g1
            {
                while ([g1 isKindOfClass:[VArc class]] && g1 != g) // move graphic at g1 end
                {   VGraphic	*g2 = (curObject+i<=endIx) ? [list objectAtIndex:curObject+i]
                                         : [list objectAtIndex:begIx+(curObject+i-endIx)-1];

                    if ((g2 == g) ||
                        (DiffPoint(g1PtEnd, [g2 pointWithNum:0]) > TOLERANCE))
                    {   if (g1 == g) stop = 1;
                        break;
                    }
                    else // if (DiffPoint(g1PtEnd, [g2 pointWithNum:0]) <= TOLERANCE)
                    {   g1PtEnd = [g2 pointWithNum:MAXINT]; // notice old end point g2 will become g1
                        [g2 movePoint:0 to:[g1 pointWithNum:MAXINT]];
                    }
                    g1 = g2;
                    i++;
                }
                if (g1 == g) stop = 1;
            }
        }
        /* move graphics at start of arc g */
        if (!stop)
        {   i = 2;
            g1 = (curObject-1>=begIx) ? [list objectAtIndex:curObject-1] : [list objectAtIndex:endIx];
            /* move graphics at start of g */
            if (DiffPoint([g1 pointWithNum:MAXINT], gPtStart) <= TOLERANCE)
            {   NSPoint	g1PtStart = [g1 pointWithNum:0]; // notice old g1 start point

                /* move only if control is set (else point never match) or no arc */
                if (control || ![g1 isKindOfClass:[VArc class]])
                    [g1 movePoint:MAXINT to:[g pointWithNum:0]];
                if (control)
                {
                    while ([g1 isKindOfClass:[VArc class]] && g1 != g) // move graphics at g1 start
                    {   VGraphic	*g2 = (curObject-i>=begIx) ? [list objectAtIndex:curObject-i]
                                         : [list objectAtIndex:endIx-(begIx-(curObject-i))+1];

                        if ((g2 == g) ||
                            (DiffPoint(g1PtStart, [g2 pointWithNum:MAXINT]) > TOLERANCE))
                            break;
                        else
                        {   g1PtStart = [g2 pointWithNum:0]; // note: old g2 start pt -> will become g1
                            [g2 movePoint:MAXINT to:[g1 pointWithNum:0]];
                        }
                        g1 = g2;
                        i++;
                    }
                }
            }
        }
    }
    else if (!pt_num)// if (![g isKindOfClass:[VArc class]]) // g is no arc
    {   NSPoint	g1PtStart = NSZeroPoint; // old end point

        g1 = (curObject-1>=begIx) ? [list objectAtIndex:curObject-1] : [list objectAtIndex:endIx];
        if (DiffPoint([g1 pointWithNum:MAXINT], gPtWithNum) <= 5.0*TOLERANCE)
        {
            g1PtStart = [g1 pointWithNum:0];
            [g1 movePoint:MAXINT to:p];
            p = [g1 pointWithNum:MAXINT];
        }
        [g movePoint:pt_num to:p]; // no arc
        if (control)
        {   int	i = 2;

            while ([g1 isKindOfClass:[VArc class]] && g1 != g) // move graphic at g1 start
            {   VGraphic	*g2 = (curObject-i>=begIx) ? [list objectAtIndex:curObject-i]
                                                         : [list objectAtIndex:endIx-(begIx-(curObject-i))+1];

                if (DiffPoint(g1PtStart, [g2 pointWithNum:MAXINT]) <= TOLERANCE)
                {   g1PtStart = [g2 pointWithNum:0]; // note: old g2 start pt -> will become g1
                    [g2 movePoint:MAXINT to:[g1 pointWithNum:0]];
                }
                else break;
                if (g2 == g)
                    break;
                g1 = g2;
                i++;
            }
        }
    }
    else // if (![g isKindOfClass:[VArc class]]) // g is no arc
    {   NSPoint	g1PtEnd = [g1 pointWithNum:MAXINT]; // notice old end point

        if (DiffPoint([g1 pointWithNum:0], gPtWithNum) <= 5.0*TOLERANCE)
        {   [g1 movePoint:0 to:p]; // move g1 start to p
            p = [g1 pointWithNum:0];
        }
        [g movePoint:pt_num to:p]; // no arc !
        if (control)
        {   int	i = 2;

            while ([g1 isKindOfClass:[VArc class]] && g1 != g) // move graphic at g1 end
            {   VGraphic	*g2 = (curObject+i<=endIx) ? [list objectAtIndex:curObject+i]
                                                         : [list objectAtIndex:begIx+(curObject+i-endIx)-1];

                if (DiffPoint(g1PtEnd, [g2 pointWithNum:0]) <= TOLERANCE)
                {   g1PtEnd = [g2 pointWithNum:MAXINT]; // notice old end point g2 will become g1
                    [g2 movePoint:0 to:[g1 pointWithNum:MAXINT]];
                }
                else break;
                if (g2 == g)
                    break;
                g1 = g2;
                i++;
            }
        }
    }
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
}

/* needed for undo
 * if control button is set -> the radius of an arc will changed (else not!)
 * for the way back we need the possibility to say "the button is set"
 */
- (void)movePoint:(int)pt_num to:(NSPoint)p control:(BOOL)control
{   VGraphic	*g=nil, *g1;
    int		begIx, endIx, curObject = -1;
    NSPoint	gPtStart, gPtEnd, gPtWithNum; // notice old end point

    if ( ![list count] || pt_num < 0 )
        return;
    /* beyond list -> point number of end point */
    if ( pt_num >= [self numPoints] )
    {   g = [list objectAtIndex:[list count]-1];
        pt_num = MAXINT;
        curObject = [list count]-1;
    }
    else if ( !pt_num )
    {   g = [list objectAtIndex:0];
        curObject = 0;
    }
    else
    {   int	i, cnt, pCnt = 0, prevPCnt = 0;

        for (i=0, cnt = [list count]; i<cnt; i++)
        {   pCnt += [[list objectAtIndex:i] numPoints];
            if ( pCnt > pt_num )
                break;		// to this object refers our pt_num
            prevPCnt = pCnt;	// count of pts befor this gr
        }
        g = [list objectAtIndex:i];
        pt_num -= prevPCnt;
        curObject = i;
    }
    if (!g)
        return;

    if ( [g isKindOfClass:[VCurve class]] && (pt_num == 1 || pt_num == 2) )
    {
        [g movePoint:pt_num to:p]; // move only the control pt
        coordBounds = bounds = NSZeroRect;
        dirty = YES;
        graduateDirty = YES;
        return;
    }

    begIx = [self getFirstObjectOfSubPath:curObject];
    endIx = [self getLastObjectOfSubPath:begIx];
    if (begIx == endIx)
        endIx = [list count]-1;

    gPtStart = [g pointWithNum:0]; // notice old start point
    gPtEnd = [g pointWithNum:MAXINT]; // notice old end point
    gPtWithNum = [g pointWithNum:pt_num]; // notice old end point

    /* move point connected to pt_num */
    g1 = (curObject+1<=endIx) ? [list objectAtIndex:curObject+1] : [list objectAtIndex:begIx];
    if ([g isKindOfClass:[VArc class]])
    {   int	i = 2, stop = 0;
        NSPoint	g1PtEnd = [g1 pointWithNum:MAXINT]; // notice old end point

        [(VArc*)g movePoint:pt_num to:p control:control];
        /* move graphics at end of arc g */
        if (DiffPoint([g1 pointWithNum:0], gPtEnd) <= TOLERANCE)
        {   /* move only if control is set (else point never match) or no arc */
            if (control || ![g1 isKindOfClass:[VArc class]])
            {
                if (![g1 isKindOfClass:[VArc class]])
                    [g1 movePoint:0 to:[g pointWithNum:MAXINT]];
                else
                    [(VArc*)g1 movePoint:0 to:[g pointWithNum:MAXINT] control:control];
            }
            if (control) // move also graphics at end of g1
            {
                while ([g1 isKindOfClass:[VArc class]] && g1 != g) // move graphic at g1 end
                {   VGraphic	*g2 = (curObject+i<=endIx) ? [list objectAtIndex:curObject+i]
                                         : [list objectAtIndex:begIx+(curObject+i-endIx)-1];

                    if ((g2 == g) ||
                        (DiffPoint(g1PtEnd, [g2 pointWithNum:0]) > TOLERANCE))
                    {   if (g1 == g) stop = 1;
                        break;
                    }
                    else // if (DiffPoint(g1PtEnd, [g2 pointWithNum:0]) <= TOLERANCE)
                    {   g1PtEnd = [g2 pointWithNum:MAXINT]; // notice old end point g2 will become g1
                        if (![g2 isKindOfClass:[VArc class]])
                            [g2 movePoint:0 to:[g1 pointWithNum:MAXINT]];
                        else
                            [(VArc*)g2 movePoint:0 to:[g1 pointWithNum:MAXINT] control:control];
                    }
                    g1 = g2;
                    i++;
                }
                if (g1 == g) stop = 1;
            }
        }
        /* move graphics at start of arc g */
        if (!stop)
        {   i = 2;
            g1 = (curObject-1>=begIx) ? [list objectAtIndex:curObject-1] : [list objectAtIndex:endIx];
            /* move graphics at start of g */
            if (DiffPoint([g1 pointWithNum:MAXINT], gPtStart) <= TOLERANCE)
            {   NSPoint	g1PtStart = [g1 pointWithNum:0]; // notice old g1 start point

                /* move only if control is set (else point never match) or no arc */
                if (control || ![g1 isKindOfClass:[VArc class]])
                {
                    if (![g1 isKindOfClass:[VArc class]])
                        [g1 movePoint:MAXINT to:[g pointWithNum:0]];
                    else
                        [(VArc*)g1 movePoint:MAXINT to:[g pointWithNum:0] control:control];
                }
                if (control)
                {
                    while ([g1 isKindOfClass:[VArc class]] && g1 != g) // move graphics at g1 start
                    {   VGraphic	*g2 = (curObject-i>=begIx) ? [list objectAtIndex:curObject-i]
                                         : [list objectAtIndex:endIx-(begIx-(curObject-i))+1];

                        if ((g2 == g) ||
                            (DiffPoint(g1PtStart, [g2 pointWithNum:MAXINT]) > TOLERANCE))
                            break;
                        else
                        {   g1PtStart = [g2 pointWithNum:0]; // note: old g2 start pt -> will become g1
                            if (![g2 isKindOfClass:[VArc class]])
                                [g2 movePoint:MAXINT to:[g1 pointWithNum:0]];
                            else
                                [(VArc*)g2 movePoint:MAXINT to:[g1 pointWithNum:0] control:control];
                        }
                        g1 = g2;
                        i++;
                    }
                }
            }
        }
    }
    else if (!pt_num)// if (![g isKindOfClass:[VArc class]]) // g is no arc
    {   NSPoint	g1PtStart = NSZeroPoint; // note: old end point

        g1 = (curObject-1>=begIx) ? [list objectAtIndex:curObject-1] : [list objectAtIndex:endIx];
        if (DiffPoint([g1 pointWithNum:MAXINT], gPtWithNum) <= 5.0*TOLERANCE)
        {
            g1PtStart = [g1 pointWithNum:0];
            if (![g1 isKindOfClass:[VArc class]])
                [g1 movePoint:MAXINT to:p];
            else
                [(VArc*)g1 movePoint:MAXINT to:p control:control];
            p = [g1 pointWithNum:MAXINT];
        }
        [g movePoint:pt_num to:p]; // no arc
        if (control)
        {   int	i = 2;

            while ([g1 isKindOfClass:[VArc class]] && g1 != g) // move graphic at g1 start
            {   VGraphic	*g2 = (curObject-i>=begIx) ? [list objectAtIndex:curObject-i]
                                                         : [list objectAtIndex:endIx-(begIx-(curObject-i))+1];

                if (DiffPoint(g1PtStart, [g2 pointWithNum:MAXINT]) <= TOLERANCE)
                {   g1PtStart = [g2 pointWithNum:0]; // note: old g2 start pt -> will become g1
                    if (![g2 isKindOfClass:[VArc class]])
                        [g2 movePoint:MAXINT to:[g1 pointWithNum:0]];
                    else
                        [(VArc*)g2 movePoint:MAXINT to:[g1 pointWithNum:0] control:control];
                }
                else break;
                if (g2 == g)
                    break;
                g1 = g2;
                i++;
            }
        }
    }
    else // if (![g isKindOfClass:[VArc class]]) // g is no arc
    {   NSPoint	g1PtEnd = [g1 pointWithNum:MAXINT]; // notice old end point

        if (DiffPoint([g1 pointWithNum:0], gPtWithNum) <= 5.0*TOLERANCE)
        {
            if (![g1 isKindOfClass:[VArc class]])
                [g1 movePoint:0 to:p]; // move g1 start to p
            else
                [(VArc*)g1 movePoint:0 to:p control:control]; // move g1 start to p
            p = [g1 pointWithNum:0];
        }
        [g movePoint:pt_num to:p]; // no arc !
        if (control)
        {   int	i = 2;

            while ([g1 isKindOfClass:[VArc class]] && g1 != g) // move graphic at g1 end
            {   VGraphic	*g2 = (curObject+i<=endIx) ? [list objectAtIndex:curObject+i]
                                                         : [list objectAtIndex:begIx+(curObject+i-endIx)-1];

                if (DiffPoint(g1PtEnd, [g2 pointWithNum:0]) <= TOLERANCE)
                {   g1PtEnd = [g2 pointWithNum:MAXINT]; // notice old end point g2 will become g1
                    if (![g2 isKindOfClass:[VArc class]])
                        [g2 movePoint:0 to:[g1 pointWithNum:MAXINT]];
                    else
                        [(VArc*)g2 movePoint:0 to:[g1 pointWithNum:MAXINT] control:control];
                }
                else break;
                if (g2 == g)
                    break;
                g1 = g2;
                i++;
            }
        }
    }
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
}

/*
 * pt_num is the changing control point. pt holds the relative change in each coordinate. 
 * The relative is needed and not the absolute because the closest inside control point
 * changes when one of the outside points change.
 */
- (void)movePoint:(int)pt_num by:(NSPoint)pt
{   NSPoint	ptWithNum;

    if ( ![list count] || pt_num < 0 )
        return;

    ptWithNum = [self pointWithNum:pt_num];
    pt.x = ptWithNum.x + pt.x;
    pt.y = ptWithNum.y + pt.y;
    [self movePoint:pt_num to:pt];
    dirty = YES;
    graduateDirty = YES;
}

/* The pt argument holds the relative point change. */
- (void)moveBy:(NSPoint)pt
{   int	i;

    for (i=[list count]-1; i>=0; i--)
        [[list objectAtIndex:i] moveBy:pt];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    if (!graduateDirty && graduateList)
    {
        for (i=[graduateList count]-1; i>=0; i--)
            [[graduateList objectAtIndex:i] moveBy:pt];
    }
}

/* Given the point number, return the point.
 * We either return the point of the path (nothing selected) or the selected object
 */
- (NSPoint)pointWithNum:(int)pt_num
{   int	i, cnt, pCnt = 0, prevPCnt = 0;

    if ( ![list count] || pt_num < 0 )
        return NSMakePoint( 0.0, 0.0);
    /* beyond list -> return point number of end point */
    if ( pt_num >= [self numPoints] )
        return [[list objectAtIndex:[list count]-1] pointWithNum:MAXINT];
    /* nothing selected -> return point of path */
    if ( !pt_num )
        return [[list objectAtIndex:0] pointWithNum:0];

    for (i=0, cnt = [list count]; i<cnt; i++)
    {   pCnt += [[list objectAtIndex:i] numPoints];
        if ( pCnt > pt_num )
            break;		// to this object refers our pt_num
        prevPCnt = pCnt;	// count of pts befor this gr
    }
    return [[list objectAtIndex:i] pointWithNum:pt_num - prevPCnt];
}

- (int)numPoints
{   int	i, cnt, pCnt = 0;

    for (i=0, cnt = [list count]; i<cnt; i++)
        pCnt += [[list objectAtIndex:i] numPoints];
    return pCnt;
}

/* modified: 2010-07-15
 *
 * we dont change the order (without split polylines)
 */
- (void)pointWithNumBecomeStartPoint:(int)pt_num
{   int	i, cnt, endIx, begIx = 0, curIx = -1, pCnt = 0, prevPCnt = 0;

    if ( !pt_num )
        return;

    if ( ![self closed] ) // only start / end points !
    {
        if ( pt_num == [self numPoints]-1 )
            [self changeDirection];
        return;
    }
 
    for (i=0, cnt = [list count]; i<cnt; i++)
    {   pCnt += [[list objectAtIndex:i] numPoints];
        curIx = i;
        if ( pCnt > pt_num )
            break;		// to this object refers our pt_num
        prevPCnt = pCnt;	// count of pts befor this gr
    }
    if ( pt_num-prevPCnt >= [[list objectAtIndex:curIx] numPoints]-1 ) // last point of Graphic
        curIx ++; // next Graphic is our start Graphic

    begIx = [self getFirstObjectOfSubPath:curIx];
    endIx = [self getLastObjectOfSubPath:begIx]; //  tolerance:TOLERANCE

    /* move objects bevor pt_num at the end of subpath */
    for (i=curIx-1; i >= begIx; i--)
    {
        [list insertObject:[list objectAtIndex:i] atIndex:endIx+1];
        [list removeObjectAtIndex:i];
        endIx --; // need the same place to insert (remove destroy position
    }
    [self deselectAll];
    selectedObject = -1;
}

- (void)mirrorAround:(NSPoint)mp;
{   int	i;

    for (i=[list count]-1; i>=0; i--)
        [(VGraphic*)[list objectAtIndex:i] mirrorAround:mp];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    if (!graduateDirty && graduateList)
    {
        for (i=[graduateList count]-1; i>=0; i--)
            [(VGraphic*)[graduateList objectAtIndex:i] mirrorAround:mp];
    }
}

/* modified: 2008-10-11
 */
- (void)changeDirection
{
    if ( !filled && ![self closed] )
    {   [self changeDirectionOfSubPath:0 :[list count]-1];
        return;
    }

    [self setDirectionCCW:(isDirectionCCW) ? 0 : 1];
    dirty = YES;
}

/* created:   21.10.95
 * modified:  05.03.97
 * parameter: angle	angle
 *            cp	rotation center
 * purpose:   draws the plane with the given rotation angles
 */
- (void)drawAtAngle:(float)angle withCenter:(NSPoint)cp in:view
{   int	i;

    for ( i=[list count]-1; i>=0; i-- )
        [(VGraphic*)[list objectAtIndex:i] drawAtAngle:angle withCenter:cp in:view];
}

- (void)setAngle:(float)angle withCenter:(NSPoint)cp
{   int		i;

    if (filled)
    {   graduateAngle -= angle;
        if (graduateAngle < 0.0)
            graduateAngle += 360.0;
        if (graduateAngle > 360.0)
            graduateAngle -= 360.0;
        vhfRotatePointAroundCenter(&radialCenter, NSMakePoint(0.5, 0.5), -angle);
        if (radialCenter.x > 1.0) radialCenter.x = 1.0;
        if (radialCenter.x < 0.0) radialCenter.x = 0.0;
        if (radialCenter.y > 1.0) radialCenter.y = 1.0;
        if (radialCenter.y < 0.0) radialCenter.y = 0.0;
        graduateDirty = YES;
    }
    for (i=[list count]-1; i>=0; i--)
        [(VGraphic*)[list objectAtIndex:i] setAngle:angle withCenter:cp];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    if (!graduateDirty && graduateList)
    {
        for (i=[graduateList count]-1; i>=0; i--)
            [(VGraphic*)[graduateList objectAtIndex:i] setAngle:angle withCenter:cp];
    }
}

- (void)transform:(NSAffineTransform*)matrix
{   int     i;
    NSSize  size = NSMakeSize(width, width);

    size = [matrix transformSize:size];
    width = (Abs(size.width) + Abs(size.height)) / 2;
    for ( i=[list count]-1; i >= 0; i-- )
        [[list objectAtIndex:i] transform:matrix];
    coordBounds = bounds = NSZeroRect;
    dirty = graduateDirty = YES;
}

- (void)scale:(float)x :(float)y withCenter:(NSPoint)cp
{   int		i;

    width *= (Abs(x)+Abs(y))/2.0;
    for (i=[list count]-1; i>=0; i--)
        [(VGraphic*)[list objectAtIndex:i] scale:x :y withCenter:cp];
    coordBounds = bounds = NSZeroRect;
    dirty = YES;
    graduateDirty = YES;
}

/* created:  1995-09-19
 * modified: 2014-02-18 (if (f && !width && (filled > 1 && antialias) ))
 * purpose:  draw the path
 */
#define DEBUG_TRACE	0
- (void)drawWithPrincipal:principal
{   int             i, f;
    int             cnt = [self count];	/* [self countRecursive] for path in path ! */
    NSPoint         currentPoint = NSMakePoint(LARGENEG_COORD, LARGENEG_COORD);
    NSBezierPath    *bPath = [NSBezierPath bezierPath];
    BOOL            antialias = VHFAntialiasing();

    if (!cnt)
        return;

#if DEBUG_TRACE
    [[NSDPSContext currentContext] setOutputTraced:YES];
#endif

    for (f=0; f <= 1; f++)  // 0 = fill, 1 = stroke
    {   NSColor	*col;
        VFloat	w;

        if (!f && !filled) continue;            // fill run: nothing to fill or allready filled
#if !defined(__APPLE__)	// OpenStep 4.2, linux - FIXME: should be without antialiasing
        if (f && !(width || !filled)) continue; // stroke run: nothing to stroke
#else   // TODO: this is a workaround to make 0-width fillings visible, we should better add a wireframe mode
        // 4.0.2:  if (f && !width && (filled > 1 || ! antialias) )
        //       this is also called from drawGraduatedWithPrincipal with antialias == NO !
        if (f && !width && (filled > 1 && antialias) )  // [4.0.2] was: (.. || ! antialias) (???)
            continue;   // stroke run: nothing to stroke and color shading -> skip
#endif
        if (     !f && filled == 2 && (graduateDirty || !graduateList))
        {   [self drawGraduatedWithPrincipal:principal];
            continue;
        }
        else if (!f && filled == 3 && (graduateDirty || !graduateList))
        {   [self drawRadialWithPrincipal:principal];
            continue;
        }
        else if (!f && filled == 4 && (graduateDirty || !graduateList))
        {   [self drawAxialWithPrincipal:principal];
            continue;
        }
        else if (!f && (filled == 2 || filled == 3 || filled == 4) && graduateList && !graduateDirty)
        {   int gCnt = [graduateList count];

            /* draw graduateList */
            VHFSetAntialiasing(NO);
            for (i=0; i<gCnt; i++)
                [(VGraphic*)[graduateList objectAtIndex:i] drawWithPrincipal:principal];
            if (antialias) VHFSetAntialiasing(antialias);
            continue;
        }
        col = (!f || (!width && filled)) ? fillColor : color;
        w = (!f) ? (0.0) : ((width > 0.0) ? width : [NSBezierPath defaultLineWidth]);   // width
        if ( filled && width == 0.0 )  // if filled and no stroke width, we stroke very thin to make everything visible
        {
            w = 0.1 / (([principal scaleFactor]) ? ([principal scaleFactor]) : (1.0));
            if ( ! antialias && !f )
                w = 0.0;
        }

        /* colorSeparation */
        if (!VHFIsDrawingToScreen() && [principal separationColor])
            col = [self separationColor:col]; // get individual separation color

        if ( [principal mustDrawPale] )
        {   VFloat h, s, b, a;

            [[col colorUsingColorSpaceName:NSDeviceRGBColorSpace] getHue:&h saturation:&s brightness:&b alpha:&a];
            [[NSColor colorWithCalibratedHue:h saturation:s brightness:(b<0.5) ? 0.5 : b alpha:a] set];
        }
#if !defined(GNUSTEP_BASE_VERSION) && !defined(__APPLE__)	// OpenStep 4.2
        else if (VHFIsDrawingToScreen() && [[col colorSpaceName] isEqualToString:NSDeviceCMYKColorSpace])
            [[col colorUsingColorSpaceName:NSCalibratedRGBColorSpace] set];
#endif
        else
            [col set];

        [bPath setLineWidth:w];
        [bPath setLineCapStyle:NSRoundLineCapStyle];
        [bPath setLineJoinStyle:NSRoundLineJoinStyle];
        for (i=0; i<cnt; i++)
            currentPoint = [[list objectAtIndex:i] appendToBezierPath:bPath currentPoint:currentPoint];

        if (!f) // (filled)
        {   [bPath setWindingRule:NSEvenOddWindingRule];
            [bPath fill];
        }
        else
            [bPath stroke];
    }
    /* display directions */
    if ( [principal showDirection] )
    {   NSPoint le=NSZeroPoint;

        for (i=0; i<cnt; i++)
        {   NSPoint s = [[list objectAtIndex:i] pointWithNum:0];
            NSPoint e = [[list objectAtIndex:i] pointWithNum:MAXINT];

            if ( !i || (Diff(le.x, s.x) > TOLERANCE || Diff(le.y, s.y) > TOLERANCE) ) // Start points
                [[list objectAtIndex:i] drawDirectionAtScale:[principal scaleFactor]/2.0];
                //[[list objectAtIndex:i] drawStartAtScale:[principal scaleFactor]];
            else if ( Diff(s.x, e.x) > 100.0*TOLERANCE || Diff(s.y, e.y) > 100.0*TOLERANCE )
                [[list objectAtIndex:i] drawDirectionAtScale:[principal scaleFactor]];
            le = [[list objectAtIndex:i] pointWithNum:MAXINT];
        }
    }

#if DEBUG_TRACE
    PSWait();
    [[NSDPSContext currentContext] setOutputTraced:NO];
#endif
}

/* modified: 2012-12-12 (alpha added, float -> double)
 * FIXME: there is a solid border between graduate steps, which is a rounding issue,
 *        and additionally probably the w = 0.1 in -drawWithPrincipal: => better to use method without stroke
 */
#define MAXSTEPS	1000
- (void)drawGraduatedWithPrincipal:principal
{   int			steps = 15, poolCnt = 0, oldFilled = filled;
    double		xMax, yMax, dx, dy, fsteps, angle = graduateAngle, length, rStepWidth = stepWidth;
    NSRect		bRect = [self coordBounds];
    NSPoint		p0, p1, ls, le, p0e, p1e, p0End;
    VLine		*line0, *line1, *line2, *line3;
    NSColor		*endCol = fillColor, *startCol = endColor;
    // FIXME: the color as double will convert float->double on 32 Bit, which doesn't work well any more (better VFloat)
    double		colDiff1  = 1.0, colDiff2  = 1.0, colDiff3  = 1.0, colDiff4  = 1.0;
    double		colStep1  = 1.0, colStep2  = 1.0, colStep3  = 1.0, colStep4  = 1.0, alphaStep  = 1.0;
    double		curCol1   = 1.0, curCol2   = 1.0, curCol3   = 1.0, curCol4   = 1.0, curAlpha   = 1.0;
    double		endCol1   = 1.0, endCol2   = 1.0, endCol3   = 1.0, endCol4   = 1.0, endAlpha   = 1.0;
    double		startCol1 = 1.0, startCol2 = 1.0, startCol3 = 1.0, startCol4 = 1.0, startAlpha = 1.0, mul = 1.0;
    VPath		*path, *rectP;
    NSAutoreleasePool	*pool, *pool1;
    NSString	*fcolSpaceName, *ecolSpaceName, *colSpaceName;
    BOOL		antialias = VHFAntialiasing();

    if (!bRect.size.width || !bRect.size.height)
        return;

    filled = 1;
    if ([startCol isEqual:endCol])
    {
        [self drawWithPrincipal:principal];
        filled = oldFilled;
        return;
    }

    /* convert fill/endColor to one colorSpaceName */
    fcolSpaceName = [fillColor colorSpaceName];
    ecolSpaceName = [endColor colorSpaceName];
    if ([fcolSpaceName isEqual:@"NSDeviceCMYKColorSpace"] || [ecolSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
    {
        startCol = [endColor colorUsingColorSpaceName:@"NSDeviceCMYKColorSpace"];
        endCol   = [fillColor colorUsingColorSpaceName:@"NSDeviceCMYKColorSpace"];
        colSpaceName = @"NSDeviceCMYKColorSpace";
    }
    else if ([fcolSpaceName isEqual:@"NSCalibratedWhiteColorSpace"] &&
             [ecolSpaceName isEqual:@"NSCalibratedWhiteColorSpace"])
    {   startCol = [endColor colorUsingColorSpaceName:@"NSCalibratedWhiteColorSpace"];
        endCol   = [fillColor colorUsingColorSpaceName:@"NSCalibratedWhiteColorSpace"];
        colSpaceName = @"NSCalibratedWhiteColorSpace";
    }
    else
    {   startCol = [endColor colorUsingColorSpaceName:@"NSCalibratedRGBColorSpace"];
        endCol   = [fillColor colorUsingColorSpaceName:@"NSCalibratedRGBColorSpace"];
        colSpaceName = @"NSCalibratedRGBColorSpace";
    }
    if (!startCol || !endCol)
    {   NSLog(@"drawGraduatedWithPrincipal: ColorSpace not supported");
        [self drawWithPrincipal:principal];
        filled = oldFilled;
        return;
    }

    if (graduateList)
        [graduateList release];
    graduateList = [[NSMutableArray allocWithZone:[self zone]] init];
    graduateDirty = NO;

    pool = [NSAutoreleasePool new];
    if (!rStepWidth) rStepWidth = 2.0;

    angle = graduateAngle;
    if (angle >= 180.0)
    {   NSColor	*col;

        col = startCol;
        startCol = endCol;
        endCol = col;
        angle -= 180.0;
    }

    /* 135 > angle > 45
     * line y is fix and we calc start values for x start/end and dx
     */
    if (angle < 135.0 && angle > 45.0)
    {   NSColor	*col;

        col = startCol;
        startCol = endCol;
        endCol   = col;
        p0.y = bRect.origin.y - rStepWidth;
        p1.y = bRect.origin.y + bRect.size.height + rStepWidth;
        p0.x = p1.x = bRect.origin.x;
        ls = le = bRect.origin;
        le.x = bRect.origin.x + bRect.size.width;
        if (angle > 90.0)
        {   p0.x = bRect.origin.x;
            p1.x = p0.x - (bRect.size.height + 2.0*rStepWidth)/Tan(180.0-angle);
            ls.x = bRect.origin.x - bRect.size.height/Tan(180.0-angle);
            ls.y = le.y = bRect.origin.y + bRect.size.height;
        }
        else if (angle < 90.0)
        {   p1.x = bRect.origin.x;
            p0.x = p1.x - (bRect.size.height + 2.0*rStepWidth)/Tan(angle);
            ls.x = bRect.origin.x - bRect.size.height/Tan(angle);
            ls.y = le.y = bRect.origin.y;
        }
    }
    /* 135 <= angle <= 45
     * line x is fix and we calc start values for y start/end and dy
     */
    else
    {   p0.x = bRect.origin.x - rStepWidth;
        p1.x = bRect.origin.x + bRect.size.width + rStepWidth;
        p0.y = p1.y = bRect.origin.y;
        ls = le = bRect.origin;
        le.y = bRect.origin.y + bRect.size.height;

        if (angle && angle <= 45.0)
        {   p1.y = bRect.origin.y;
            p0.y = p1.y - (bRect.size.width + 2.0*rStepWidth)*Tan(angle);
            ls.x = le.x = bRect.origin.x;
            ls.y = bRect.origin.y - bRect.size.width*Tan(angle);
        }
        else if (angle)
        {   NSColor	*col;

            col = startCol;
            startCol = endCol;
            endCol = col;
            p0.y = bRect.origin.y;
            p1.y = p0.y - (bRect.size.width + 2.0*rStepWidth)*Tan(180.0-angle);
            ls.x = le.x = bRect.origin.x + bRect.size.width;
            ls.y = bRect.origin.y - bRect.size.width*Tan(180.0-angle);
        }
    }

    length = sqrt(SqrDistPoints(ls, le));
    fsteps = length / rStepWidth;
    steps = ((int)fsteps) + ((fsteps-((int)fsteps) > 0.0) ? 1 : 0);

    dx = Diff(ls.x, le.x)/(double)steps;
    dy = Diff(ls.y, le.y)/(double)steps;

    steps --; // for startCol

    /* build path - else we must rotate the rectangle (sqrt, sin, ..) */
    line0 = [VLine line];
    line1 = [VLine line];
    line2 = [VLine line];
    line3 = [VLine line];
    rectP = [VPath path];
    [rectP setFilled:1]; // simple filling
    [line0 setVertices:p0 :p1];
    [[rectP list] addObject:line0];
    [line1 setVertices:p1 :NSMakePoint(p1.x+dx, p1.y+dy)];
    [[rectP list] addObject:line1];
    [line2 setVertices:NSMakePoint(p1.x+dx, p1.y+dy) :NSMakePoint(p0.x+dx, p0.y+dy)];
    [[rectP list] addObject:line2];
    [line3 setVertices:NSMakePoint(p0.x+dx, p0.y+dy) :p0];
    [[rectP list] addObject:line3];

    pool1 = [NSAutoreleasePool new];

    yMax = bRect.origin.y+bRect.size.height;
    xMax = bRect.origin.x+bRect.size.width;
    while ( steps && ((!dx && (p0.y < yMax || p1.y < yMax)) || (!dy && (p0.x < xMax || p1.x < xMax))) )
    {
        path = [rectP clippedFrom:self];
        if (!path || ![[path list] count])
        {   //NSLog(@"VPolyLine -drawGraduatedWithPrincipal: troubles with extreme paths!");
            p0.x += dx; p0.y += dy;
            p1.x += dx; p1.y += dy;
            [[[rectP list] objectAtIndex:0] setVertices:p0 :p1];
            [[[rectP list] objectAtIndex:1] setVertices:p1 :NSMakePoint(p1.x+dx, p1.y+dy)];
            [[[rectP list] objectAtIndex:2] setVertices:NSMakePoint(p1.x+dx, p1.y+dy) :NSMakePoint(p0.x+dx, p0.y+dy)];
            [[[rectP list] objectAtIndex:3] setVertices:NSMakePoint(p0.x+dx, p0.y+dy) :p0];
            [rectP setBoundsZero];
            /* correct col steps */
            steps--;
        }
        else
            break; // start p0 p1 !
        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }
    p0e.x = p0.x + steps*dx;
    p0e.y = p0.y + steps*dy;
    p1e.x = p1.x + steps*dx;
    p1e.y = p1.y + steps*dy;
    [[[rectP list] objectAtIndex:0] setVertices:p0e :p1e];
    [[[rectP list] objectAtIndex:1] setVertices:p1e :NSMakePoint(p1e.x+dx, p1e.y+dy)];
    [[[rectP list] objectAtIndex:2] setVertices:NSMakePoint(p1e.x+dx, p1e.y+dy) :NSMakePoint(p0e.x+dx, p0e.y+dy)];
    [[[rectP list] objectAtIndex:3] setVertices:NSMakePoint(p0e.x+dx, p0e.y+dy) :p0e];
    [rectP setBoundsZero];
    while ( steps && ((!dx && (p0e.y < yMax || p1e.y < yMax)) || (!dy && (p0e.x < xMax || p1e.x < xMax))) )
    {
        path = [rectP clippedFrom:self];
        if (!path || ![[path list] count])
        {   //NSLog(@"VPolyLine -drawGraduatedWithPrincipal: troubles with extreme paths!");
            p0e.x -= dx; p0e.y -= dy;
            p1e.x -= dx; p1e.y -= dy;
            [[[rectP list] objectAtIndex:0] setVertices:p0e :p1e];
            [[[rectP list] objectAtIndex:1] setVertices:p1e :NSMakePoint(p1e.x+dx, p1e.y+dy)];
            [[[rectP list] objectAtIndex:2] setVertices:NSMakePoint(p1e.x+dx, p1e.y+dy) :NSMakePoint(p0e.x+dx, p0e.y+dy)];
            [[[rectP list] objectAtIndex:3] setVertices:NSMakePoint(p0e.x+dx, p0e.y+dy) :p0e];
            [rectP setBoundsZero];
            /* correct col steps */
            steps--;
            if (steps <= 1)
            {   [pool1 release]; [pool release];
                filled = oldFilled;
                return;
            }
        }
        else
            break; // end
        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }


    if ([colSpaceName isEqual:@"NSCalibratedRGBColorSpace"])
    {
        startCol1 = curCol1 = [startCol redComponent];
        startCol2 = curCol2 = [startCol greenComponent];
        startCol3 = curCol3 = [startCol blueComponent];
        endCol1 = [endCol redComponent];
        endCol2 = [endCol greenComponent];
        endCol3 = [endCol blueComponent];
    }
    else if ([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
    {
        startCol1 = curCol1 = [startCol cyanComponent];
        startCol2 = curCol2 = [startCol magentaComponent];
        startCol3 = curCol3 = [startCol yellowComponent];
        startCol4 = curCol4 = [startCol blackComponent];
        endCol1 = [endCol cyanComponent];
        endCol2 = [endCol magentaComponent];
        endCol3 = [endCol yellowComponent];
        endCol4 = [endCol blackComponent];
    }
    else // NSCalibratedWhiteColorSpace
    {
        startCol1 = curCol1 = [startCol whiteComponent];
        endCol1   = [endCol whiteComponent];
    }
    startAlpha = curAlpha = [startCol alphaComponent];
    endAlpha              = [endCol   alphaComponent];

    /* correct steps */
    p0End.x = p0e.x + dx;
    p0End.y = p0e.y + dy;
    length = sqrt(SqrDistPoints(p0, p0End));
    if (steps > MAXSTEPS)
    {
        steps = MAXSTEPS;
        rStepWidth = length / steps;
        fsteps = length / rStepWidth;
        steps = ((int)fsteps) + ((fsteps-((int)fsteps) > 0.0) ? 1 : 0);
        dx = Diff(p0.x, p0End.x)/(double)steps;
        dy = Diff(p0.y, p0End.y)/(double)steps;
    }
    if ( steps == 0.0 )
        steps = 1.0;
    colDiff1 = Diff(curCol1, endCol1);
    colDiff2 = Diff(curCol2, endCol2);
    colDiff3 = Diff(curCol3, endCol3);
    colDiff4 = Diff(curCol4, endCol4);
    colStep1 = colDiff1/steps;
    colStep2 = colDiff2/steps;
    colStep3 = colDiff3/steps;
    colStep4 = colDiff4/steps;
    alphaStep = (endAlpha-startAlpha)/2.0 / steps;

    if (curCol1 > endCol1) colStep1 = -colStep1;
    if (curCol2 > endCol2) colStep2 = -colStep2;
    if (curCol3 > endCol3) colStep3 = -colStep3;
    if (curCol4 > endCol4) colStep4 = -colStep4;

    colStep1  = floor(colStep1 *1000000.0)/1000000.0;
    colStep2  = floor(colStep2 *1000000.0)/1000000.0;
    colStep3  = floor(colStep3 *1000000.0)/1000000.0;
    colStep4  = floor(colStep4 *1000000.0)/1000000.0;
    alphaStep = floor(alphaStep*1000000.0)/1000000.0;

    [[[rectP list] objectAtIndex:0] setVertices:p0 :p1];
    [[[rectP list] objectAtIndex:1] setVertices:p1 :NSMakePoint(p1.x+dx, p1.y+dy)];
    [[[rectP list] objectAtIndex:2] setVertices:NSMakePoint(p1.x+dx, p1.y+dy) :NSMakePoint(p0.x+dx, p0.y+dy)];
    [[[rectP list] objectAtIndex:3] setVertices:NSMakePoint(p0.x+dx, p0.y+dy) :p0];
    [rectP setBoundsZero];
    VHFSetAntialiasing(NO);
    while ( (!dx && (p0.y < yMax || p1.y < yMax)) || (!dy && (p0.x < xMax || p1.x < xMax)) )
    {
        path = [rectP clippedFrom:self];
        if (p0.y >= p0e.y && p0.x >= p0e.x && p1.y >= p1e.y && p1.x >= p1e.x && (!path || ![[path list] count]))
            break;
        [path sortList];
        if ([colSpaceName isEqual:@"NSCalibratedRGBColorSpace"])
            [path setFillColor:[NSColor colorWithCalibratedRed:curCol1 green:curCol2 blue:curCol3 alpha:curAlpha]];
        else if ([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
            [path setFillColor:[NSColor colorWithDeviceCyan:curCol1 magenta:curCol2 yellow:curCol3 black:curCol4 alpha:curAlpha]];
        else
            [path setFillColor:[NSColor colorWithCalibratedWhite:curCol1 alpha:curAlpha]];
        [path drawWithPrincipal:principal]; // we want to fill online
        /* Fix me
         * clipfehler im openstep
         * path links und rechts vom clipbereich -> dann wird innerhalb des clipbereichs eine linie dargestellt
         */
        /* moeglicher workaround
         * den pfad zerlegen in mehrere pfade
         * - check if path innerhalb einer der anderen nicht vergessen !!!
        {   int		j, pCnt = [[path list] count];
            BOOL	startIx = 0, endIx = 0;

            while (startIx < pCnt)
            {
                endIx = [path getLastObjectOfSubPath:startIx];
                if (startIx == endIx)
                {   startIx++;
                    continue;
                }
                else
                {   VPath	*p = [VPath path];

                    [p setFilled:1];
                    if ([colSpaceName isEqual:@"NSCalibratedRGBColorSpace"])
                        [path setFillColor:[NSColor colorWithCalibratedRed:curCol1 green:curCol2 blue:curCol3 alpha:1.0]];
                    else if ([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
                        [path setFillColor:[NSColor colorWithDeviceCyan:curCol1 magenta:curCol2 yellow:curCol3 black:curCol4 alpha:1.0]];
                    else
                        [path setFillColor:[NSColor colorWithCalibratedWhite:curCol1 alpha:1.0]];
                    for (j = startIx; j<=endIx; j++)
                        [[p list] addObject:[[path list] objectAtIndex:j]];

                    [graduateList addObject:[[p copy] autorelease]];
                }
                startIx = endIx+1;
            }
        }
         */
        [graduateList addObject:[[path copy] autorelease]];

        curCol1  = startCol1  + mul*colStep1;
        curCol2  = startCol2  + mul*colStep2;
        curCol3  = startCol3  + mul*colStep3;
        curCol4  = startCol4  + mul*colStep4;
        curAlpha = startAlpha + mul*alphaStep;
        mul += 1.0;
        p0.x += dx; p0.y += dy;
        p1.x += dx; p1.y += dy;
        /* build new path - else we must rotate the rectangle (sqrt, sin, ..) */
        [[[rectP list] objectAtIndex:0] setVertices:p0 :p1];
        [[[rectP list] objectAtIndex:1] setVertices:p1 :NSMakePoint(p1.x+dx, p1.y+dy)];
        [[[rectP list] objectAtIndex:2] setVertices:NSMakePoint(p1.x+dx, p1.y+dy) :NSMakePoint(p0.x+dx, p0.y+dy)];
        [[[rectP list] objectAtIndex:3] setVertices:NSMakePoint(p0.x+dx, p0.y+dy) :p0];
        [rectP setBoundsZero];

        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }
    if (antialias) VHFSetAntialiasing(antialias);

    [pool1 release];
    [pool release];
    filled = oldFilled;
}

- (void)drawRadialWithPrincipal:principal
{   int			steps = 15, poolCnt = 0, oldFilled = filled;
    float		fsteps, rRadius, endRadius, overlap = 1.0, rStepWidth = stepWidth;
    NSRect		bRect = [self coordBounds];
    NSPoint		rCenter, ll, lr, ur, ul, maxDistP;
    VArc		*theArc, *theArc2;
    NSColor		*endCol = fillColor, *startCol = endColor;
    double		colDiff1 = 1.0, colDiff2 = 1.0, colDiff3 = 1.0, colDiff4 = 1.0, distance, minRadius;
    double		colStep1 = 1.0, colStep2 = 1.0, colStep3 = 1.0, colStep4 = 1.0;
    double		curCol1 = 1.0, curCol2 = 1.0, curCol3 = 1.0, curCol4 = 1.0;
    double		endCol1 = 1.0, endCol2 = 1.0, endCol3 = 1.0, endCol4 = 1.0;
    double		startCol1 = 1.0, startCol2 = 1.0, startCol3 = 1.0, startCol4 = 1.0, mul = 1.0;
    VPath		*path, *arcPath;
    NSAutoreleasePool   *pool, *pool1;
    NSString            *fcolSpaceName, *ecolSpaceName, *colSpaceName;
    BOOL                antialias = VHFAntialiasing();

    if (!bRect.size.width || !bRect.size.height)
        return;

    filled = 1;
    if ([startCol isEqual:endCol])
    {
        [self drawWithPrincipal:principal];
        filled = oldFilled;
        return;
    }

    /* convert fill/endColor to one colorSpaceName */
    fcolSpaceName = [fillColor colorSpaceName];
    ecolSpaceName = [endColor  colorSpaceName];
    if ([fcolSpaceName isEqual:@"NSDeviceCMYKColorSpace"] || [ecolSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
    {
        startCol = [endColor  colorUsingColorSpaceName:@"NSDeviceCMYKColorSpace"];
        endCol   = [fillColor colorUsingColorSpaceName:@"NSDeviceCMYKColorSpace"];
        colSpaceName = @"NSDeviceCMYKColorSpace";
    }
    else if ([fcolSpaceName isEqual:@"NSCalibratedWhiteColorSpace"] &&
             [ecolSpaceName isEqual:@"NSCalibratedWhiteColorSpace"])
    {   startCol = [endColor  colorUsingColorSpaceName:@"NSCalibratedWhiteColorSpace"];
        endCol   = [fillColor colorUsingColorSpaceName:@"NSCalibratedWhiteColorSpace"];
        colSpaceName = @"NSCalibratedWhiteColorSpace";
    }
    else
    {   startCol = [endColor  colorUsingColorSpaceName:@"NSCalibratedRGBColorSpace"];
        endCol   = [fillColor colorUsingColorSpaceName:@"NSCalibratedRGBColorSpace"];
        colSpaceName = @"NSCalibratedRGBColorSpace";
    }
    if (!startCol || !endCol)
    {   NSLog(@"drawGraduatedWithPrincipal: ColorSpace not supported");
        [self drawWithPrincipal:principal];
        filled = oldFilled;
        return;
    }

    if (graduateList)
        [graduateList release];
    graduateList = [[NSMutableArray allocWithZone:[self zone]] init];
    graduateDirty = NO;

    pool = [NSAutoreleasePool new];
    if (!rStepWidth) rStepWidth = 2.0;

    rCenter.x = bRect.origin.x + bRect.size.width*radialCenter.x;
    rCenter.y = bRect.origin.y + bRect.size.height*radialCenter.y;

    ll = bRect.origin;
    ul = NSMakePoint(bRect.origin.x, bRect.origin.y+bRect.size.height);
    ur = NSMakePoint(bRect.origin.x+bRect.size.width, bRect.origin.y+bRect.size.height);
    lr = NSMakePoint(bRect.origin.x+bRect.size.width, bRect.origin.y);
    maxDistP = (SqrDistPoints(ll, rCenter) > SqrDistPoints(lr, rCenter)) ? ll : lr;
    if (SqrDistPoints(ul, rCenter) > SqrDistPoints(maxDistP, rCenter))
        maxDistP = ul;
    if (SqrDistPoints(ur, rCenter) > SqrDistPoints(maxDistP, rCenter))
        maxDistP = ur;
    rRadius = sqrt(SqrDistPoints(rCenter, maxDistP));
    /* our ring */
    arcPath = [VPath path];
    theArc = [VArc arc];
    theArc2 = [VArc arc];
    [arcPath setFilled:1];
    [theArc setFilled:1];
    [theArc setCenter:rCenter start:NSMakePoint(rCenter.x+rRadius, rCenter.y) angle:360.0];
    [[arcPath list] addObject:theArc];
    [theArc2 setCenter:rCenter start:NSMakePoint(rCenter.x+rRadius-rStepWidth, rCenter.y) angle:360.0];
    [[arcPath list] addObject:theArc2];

    fsteps = rRadius / rStepWidth;
    steps = ((int)fsteps) + ((fsteps-((int)fsteps) > 0.0) ? 1 : 0);
    steps --; // for startCol
    if ( steps <= 0 )
        steps = 1;

    pool1 = [NSAutoreleasePool new];

    while (rRadius > TOLERANCE*10.0)
    {
        path = [arcPath clippedFrom:self];
        if (!path || [[path list] count] <= 1)
        {
            rRadius -= rStepWidth;
            [[[arcPath list] objectAtIndex:0] setCenter:rCenter start:NSMakePoint(rCenter.x+rRadius, rCenter.y)
                                                  angle:360.0];
            [[[arcPath list] objectAtIndex:1] setCenter:rCenter
                                                  start:NSMakePoint(rCenter.x+rRadius-rStepWidth, rCenter.y)
                                                  angle:360.0];
            [arcPath setBoundsZero];
            steps--; // correct col steps
        }
        else
            break; // start theArc
        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }
    endRadius = rStepWidth;
    [[[arcPath list] objectAtIndex:0] setCenter:rCenter start:NSMakePoint(rCenter.x+endRadius, rCenter.y)
                                          angle:360.0];
    [[[arcPath list] objectAtIndex:1] setCenter:rCenter start:NSMakePoint(rCenter.x+endRadius-rStepWidth, rCenter.y)
                                          angle:360.0];
    [arcPath setBoundsZero];
    while (endRadius < rRadius)
    {
        path = [arcPath clippedFrom:self];
        if (!path || [[path list] count] <= 1)
        {
            endRadius += rStepWidth;
            [[[arcPath list] objectAtIndex:0] setCenter:rCenter start:NSMakePoint(rCenter.x+endRadius, rCenter.y)
                                                  angle:360.0];
            [[[arcPath list] objectAtIndex:1] setCenter:rCenter
                                                  start:NSMakePoint(rCenter.x+endRadius-rStepWidth, rCenter.y)
                                                  angle:360.0];
            [arcPath setBoundsZero];
            steps--; // correct col steps
            if (steps <= 1)
            {   [pool1 release]; [pool release];
                filled = oldFilled;
                return;
            }
        }
        else
            break; // end
        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }

    if ([colSpaceName isEqual:@"NSCalibratedRGBColorSpace"])
    {
        startCol1 = curCol1 = [startCol redComponent];
        startCol2 = curCol2 = [startCol greenComponent];
        startCol3 = curCol3 = [startCol blueComponent];
        endCol1 = [endCol redComponent];
        endCol2 = [endCol greenComponent];
        endCol3 = [endCol blueComponent];
    }
    else if ([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
    {
        startCol1 = curCol1 = [startCol cyanComponent];
        startCol2 = curCol2 = [startCol magentaComponent];
        startCol3 = curCol3 = [startCol yellowComponent];
        startCol4 = curCol4 = [startCol blackComponent];
        endCol1 = [endCol cyanComponent];
        endCol2 = [endCol magentaComponent];
        endCol3 = [endCol yellowComponent];
        endCol4 = [endCol blackComponent];
    }
    else // NSCalibratedWhiteColorSpace
    {
        startCol1 = curCol1 = [startCol whiteComponent];
        endCol1 = [endCol whiteComponent];
    }
    colDiff1 = Diff(curCol1, endCol1);
    colDiff2 = Diff(curCol2, endCol2);
    colDiff3 = Diff(curCol3, endCol3);
    colDiff4 = Diff(curCol4, endCol4);
    colStep1 = colDiff1/steps;
    colStep2 = colDiff2/steps;
    colStep3 = colDiff3/steps;
    colStep4 = colDiff4/steps;

    distance = (rRadius-(endRadius-rStepWidth));
    minRadius = endRadius-rStepWidth;

    if (steps > MAXSTEPS)
    {
        steps = MAXSTEPS;
        colStep1 = colDiff1/steps;
        colStep2 = colDiff2/steps;
        colStep3 = colDiff3/steps;
        colStep4 = colDiff4/steps;
        rStepWidth = distance/steps;
    }

#if 0
/* ultimative hack !!! */
    for (i=0; i<4; i++)
    {   double	testCol, colStep, colDiff;

        switch (i)
        {   case 0: colStep = colStep1; colDiff = colDiff1; break;
            case 1: colStep = colStep2; colDiff = colDiff2; break;
            case 2: colStep = colStep3; colDiff = colDiff3; break;
            default: colStep = colStep4; colDiff = colDiff4;
        }
        testCol = (1.0/colStep)/(([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"]) ? 4.0 : 3.0);
        testCol = testCol-((int)testCol);
        while ( steps > 1 && colStep && /*(testCol < 0.15 || 1.0-testCol < 0.15)*/
                (([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"] &&
                  (Diff(testCol, 0.2) < 0.07 || Diff(1.0-testCol, 0.2) < 0.07)) || // 0.6 - 0.15
                 (/*![colSpaceName isEqual:@"NSDeviceCMYKColorSpace"] &&*/ (testCol < 0.15 || 1.0-testCol < 0.15))))

        {
            steps--;
            colStep1 = colDiff1/steps;
            colStep2 = colDiff2/steps;
            colStep3 = colDiff3/steps;
            colStep4 = colDiff4/steps;
            rStepWidth = distance/steps;
            switch (i)
            {   case 0: colStep = colStep1; break;
                case 1: colStep = colStep2; break;
                case 2: colStep = colStep3; break;
                default: colStep = colStep4;
            }
            testCol = (1.0/colStep)/(([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"]) ? 4.0 : 3.0);
            testCol = testCol-((int)testCol);
            if (steps == 1)
                break;
        }
    }
#endif

    if (curCol1 > endCol1) colStep1 = -colStep1;
    if (curCol2 > endCol2) colStep2 = -colStep2;
    if (curCol3 > endCol3) colStep3 = -colStep3;
    if (curCol4 > endCol4) colStep4 = -colStep4;

    colStep1 = floor(colStep1*1000000.0)/1000000.0;
    colStep2 = floor(colStep2*1000000.0)/1000000.0;
    colStep3 = floor(colStep3*1000000.0)/1000000.0;
    colStep4 = floor(colStep4*1000000.0)/1000000.0;

#if 0
NSLog(@"colStep1: %.15f testCol1: %.15f steps: %d\n", colStep1, ((1.0/colStep1)/(([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"]) ? 4.0 : 3.0))), steps;
NSLog(@"colStep2: %.15f testCol2: %.15f\n", colStep2, ((1.0/colStep2)/(([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"]) ? 4.0 : 3.0)));
NSLog(@"colStep3: %.15f testCol3: %.15f\n", colStep3, ((1.0/colStep3)/(([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"]) ? 4.0 : 3.0)));
#endif

    /* so we get a continuous image if we move the center
     * because the radius of the inner circle is always rStepWidth
     */
    fsteps = distance/rStepWidth;
//    fsteps = rRadius/rStepWidth;
    fsteps = ((int)fsteps) + ((fsteps-((int)fsteps) > 0.0) ? 1 : 0);
//    rRadius = fsteps*rStepWidth;
    distance = fsteps*rStepWidth;
    rRadius = distance + minRadius;
    endRadius = minRadius+rStepWidth;

    if (rStepWidth < 3.0)
       overlap = rStepWidth * 0.2;

    /* build our ring */
    [[[arcPath list] objectAtIndex:0] setCenter:rCenter
                                          start:NSMakePoint(rCenter.x+rRadius, rCenter.y)
                                          angle:360.0];
    if ((rRadius-rStepWidth-overlap) <= 0.0)
        [[[arcPath list] objectAtIndex:1] setCenter:rCenter
                                              start:NSMakePoint(rCenter.x, rCenter.y)
                                              angle:360.0];
    else
        [[[arcPath list] objectAtIndex:1] setCenter:rCenter
                                              start:NSMakePoint(rCenter.x+rRadius-rStepWidth-overlap, rCenter.y)
                                              angle:360.0];
    [arcPath setBoundsZero];

    VHFSetAntialiasing(NO);
    while (rRadius > TOLERANCE*10.0)
    {
        path = [arcPath clippedFrom:self];
        if (rRadius <= endRadius && (!path || [[path list] count] <= 1))
            break;
        if ([[path list] count] > 1)
        {   [path sortList];
            if ([colSpaceName isEqual:@"NSCalibratedRGBColorSpace"])
                [path setFillColor:[NSColor colorWithCalibratedRed:curCol1 green:curCol2 blue:curCol3 alpha:1.0]];
            else if ([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
                [path setFillColor:[NSColor colorWithDeviceCyan:curCol1 magenta:curCol2 yellow:curCol3 black:curCol4 alpha:1.0]];
            else
                [path setFillColor:[NSColor colorWithCalibratedWhite:curCol1 alpha:1.0]];
            [path drawWithPrincipal:principal];
            [graduateList addObject:[[path copy] autorelease]];
        }
//else
//    NSLog(@"fault in radialFilling\n");
        curCol1 = startCol1 + mul*colStep1;
        curCol2 = startCol2 + mul*colStep2;
        curCol3 = startCol3 + mul*colStep3;
        curCol4 = startCol4 + mul*colStep4;
        mul += 1.0;
        rRadius -= rStepWidth;
        [[[arcPath list] objectAtIndex:0] setCenter:rCenter
                                              start:NSMakePoint(rCenter.x+rRadius, rCenter.y)
                                              angle:360.0];
        if ((rRadius-rStepWidth-overlap) <= 0.0)
            [[[arcPath list] objectAtIndex:1] setCenter:rCenter
                                                  start:NSMakePoint(rCenter.x, rCenter.y)
                                                  angle:360.0];
        else
            [[[arcPath list] objectAtIndex:1] setCenter:rCenter
                                                  start:NSMakePoint(rCenter.x+rRadius-rStepWidth-overlap, rCenter.y)
                                                  angle:360.0];
        [arcPath setBoundsZero];
        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }
    if (antialias) VHFSetAntialiasing(antialias);

    [pool1 release];
    [pool release];
    filled = oldFilled;
}

- (void)drawAxialWithPrincipal:principal
{   int			steps = 15, poolCnt = 0, oldFilled = filled;
    double		fsteps, rRadius, stepAngle, startAngle, endAngle, rStepWidth = stepWidth;
    NSRect		bRect = [self coordBounds];
    NSPoint		rCenter, ll, lr, ur, ul, maxDistP, startArc, endArc;
    VArc		*theArc;
    VLine		*ecline, *csline;
    NSColor		*endCol = fillColor, *startCol = endColor;
    double		colStep1 = 1.0, colStep2 = 1.0, colStep3 = 1.0, colStep4 = 1.0;
    double		curCol1 = 1.0, curCol2 = 1.0, curCol3 = 1.0, curCol4 = 1.0;
    double		endCol1 = 1.0, endCol2 = 1.0, endCol3 = 1.0, endCol4 = 1.0;
    double		startCol1 = 1.0, startCol2 = 1.0, startCol3 = 1.0, startCol4 = 1.0, mul = 1.0;
    VPath		*path, *cakePath;
    NSAutoreleasePool	*pool, *pool1;
    NSString		*fcolSpaceName, *ecolSpaceName, *colSpaceName;
    BOOL		antialias = VHFAntialiasing();

    if (!bRect.size.width || !bRect.size.height)
        return;

    filled = 1;
    if ([startCol isEqual:endCol])
    {
        [self drawWithPrincipal:principal];
        filled = oldFilled;
        return;
    }

    /* convert fill/endColor to one colorSpaceName */
    fcolSpaceName = [fillColor colorSpaceName];
    ecolSpaceName = [endColor colorSpaceName];
    if ([fcolSpaceName isEqual:@"NSDeviceCMYKColorSpace"] || [ecolSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
    {
        startCol = [endColor colorUsingColorSpaceName:@"NSDeviceCMYKColorSpace"];
        endCol = [fillColor colorUsingColorSpaceName:@"NSDeviceCMYKColorSpace"];
        colSpaceName = @"NSDeviceCMYKColorSpace";
    }
    else if ([fcolSpaceName isEqual:@"NSCalibratedWhiteColorSpace"] &&
             [ecolSpaceName isEqual:@"NSCalibratedWhiteColorSpace"])
    {   startCol = [endColor colorUsingColorSpaceName:@"NSCalibratedWhiteColorSpace"];
        endCol = [fillColor colorUsingColorSpaceName:@"NSCalibratedWhiteColorSpace"];
        colSpaceName = @"NSCalibratedWhiteColorSpace";
    }
    else
    {   startCol = [endColor colorUsingColorSpaceName:@"NSCalibratedRGBColorSpace"];
        endCol = [fillColor colorUsingColorSpaceName:@"NSCalibratedRGBColorSpace"];
        colSpaceName = @"NSCalibratedRGBColorSpace";
    }
    if (!startCol || !endCol)
    {   NSLog(@"drawRadialWithPrincipal: ColorSpace not supported");
        [self drawWithPrincipal:principal];
        filled = oldFilled;
        return;
    }

    if (graduateList)
        [graduateList release];
    graduateList = [[NSMutableArray allocWithZone:[self zone]] init];
    graduateDirty = NO;

    pool = [NSAutoreleasePool new];
    if (!rStepWidth) rStepWidth = 2.0;

    rCenter.x = bRect.origin.x + bRect.size.width*radialCenter.x;
    rCenter.y = bRect.origin.y + bRect.size.height*radialCenter.y;

    ll = bRect.origin;
    ul = NSMakePoint(bRect.origin.x, bRect.origin.y+bRect.size.height);
    ur = NSMakePoint(bRect.origin.x+bRect.size.width, bRect.origin.y+bRect.size.height);
    lr = NSMakePoint(bRect.origin.x+bRect.size.width, bRect.origin.y);
    maxDistP = (SqrDistPoints(ll, rCenter) > SqrDistPoints(lr, rCenter)) ? ll : lr;
    if (SqrDistPoints(ul, rCenter) > SqrDistPoints(maxDistP, rCenter))
        maxDistP = ul;
    if (SqrDistPoints(ur, rCenter) > SqrDistPoints(maxDistP, rCenter))
        maxDistP = ur;
    rRadius = sqrt(SqrDistPoints(rCenter, maxDistP));

    fsteps = (2.0*Pi*rRadius)/rStepWidth;
    steps = ((int)fsteps) + ((fsteps-((int)fsteps) > 0.0) ? 1 : 0);
    steps --; // for startCol

    if (steps > MAXSTEPS)
    {
        steps = MAXSTEPS;
        rStepWidth = (2.0*Pi*rRadius)/steps;
        fsteps = (2.0*Pi*rRadius)/rStepWidth;
        steps = ((int)fsteps) + ((fsteps-((int)fsteps) > 0.0) ? 1 : 0);
    }

    stepAngle = 360.0/(double)steps; // umfang / rStepWidth = cnt, 360 / cnt = stepAngle

    /* our cake */
    startAngle = endAngle = graduateAngle;
    endAngle += 360.0;
    if (startAngle == 360.0) { startAngle = 0.0; endAngle = 360.0; }

    /* korrekt start/endAngle if radCenter laying on bRect frame */
    if ( Diff(rCenter.y, bRect.origin.y) <= 0.0001 ) // down
    {
        if ( Diff(rCenter.x, bRect.origin.x) <= 0.0001 && (!startAngle || startAngle >= 90.0) ) // down left
        {
            startAngle = 0.0;
            endAngle = 90.0;
            fsteps /= 4.0;
        }
        else if ( Diff(rCenter.x, bRect.origin.x+bRect.size.width) <= 0.0001 &&
             (startAngle >= 180.0 || startAngle <= 90.0) ) // down right
        {
            startAngle = 90.0;
            endAngle = 180.0;
            fsteps /= 4.0;
        }
        else if ( !startAngle || startAngle >= 180.0 )
        {
            startAngle = 0.0;
            endAngle = 180.0;
            fsteps /= 2.0;
        }
    }
    else if ( Diff(rCenter.y, bRect.origin.y+bRect.size.height) <= 0.0001 ) // up
    {
        if ( Diff(rCenter.x, bRect.origin.x) <= 0.0001 && startAngle >= 0.0  && startAngle <= 270.0 ) // up left
        {
            startAngle = 270.0;
            endAngle = 360.0;
            fsteps /= 4.0;
        }
        else if ( Diff(rCenter.x, bRect.origin.x+bRect.size.width) <= 0.0001 &&
             (startAngle >= 270.0 || startAngle <= 180.0) ) // up right
        {
            startAngle = 180.0;
            endAngle = 270.0;
            fsteps /= 4.0;
        }
        else if ( startAngle <= 180.0 )
        {
            startAngle = 180.0;
            endAngle = 360.0;
            fsteps /= 2.0;
        }
    }
    else if ( Diff(rCenter.x, bRect.origin.x) <= 0.0001 && startAngle >= 90.0 && startAngle <= 270.0 ) // left
    {
        startAngle = 270.0;
        endAngle = 450.0;
        fsteps /= 2.0;
    }
    else if ( Diff(rCenter.x, bRect.origin.x+bRect.size.width) <= 0.0001 && (startAngle <= 90.0 || startAngle >= 270.0) ) // right
    {
        startAngle = 90.0;
        endAngle = 270.0;
        fsteps /= 2.0;
    }
    steps = ((int)fsteps) + ((fsteps-((int)fsteps) > 0.0) ? 1 : 0);

    startArc = vhfPointAngleFromRefPoint(rCenter, NSMakePoint(rCenter.x+rRadius, rCenter.y), startAngle);
    endArc = vhfPointAngleFromRefPoint(rCenter, startArc, stepAngle);
    cakePath = [VPath path];
    [cakePath setFilled:1];
    ecline = [VLine line];
    [ecline setVertices:endArc :rCenter];
    [[cakePath list] addObject:ecline];
    csline = [VLine line];
    [csline setVertices:rCenter :startArc];
    [[cakePath list] addObject:csline];
    theArc = [VArc arc];
    [theArc setCenter:rCenter start:startArc angle:stepAngle];
    [[cakePath list] addObject:theArc];

    pool1 = [NSAutoreleasePool new];

    while (startAngle < endAngle)
    {
        path = [cakePath clippedFrom:self];
        if (!path || [[path list] count] <= 1)
        {
            startArc = endArc;
            endArc = vhfPointAngleFromRefPoint(rCenter, startArc, stepAngle);
            [[[cakePath list] objectAtIndex:0] setVertices:endArc :rCenter];
            [[[cakePath list] objectAtIndex:1] setVertices:rCenter :startArc];
            [[[cakePath list] objectAtIndex:2] setCenter:rCenter start:startArc angle:stepAngle];
            [cakePath setBoundsZero];
            /* set coordBounds to NSZeroRect */
            [cakePath setList:[[cakePath list] retain] optimize:NO];
            [[cakePath list] release];
            steps--; // correct col steps
            startAngle += stepAngle; // correct startAngle !
        }
        else
            break; // start theArc
        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }
    startArc = vhfPointAngleFromRefPoint(rCenter, NSMakePoint(rCenter.x+rRadius, rCenter.y), endAngle); // -360.0
    endArc = vhfPointAngleFromRefPoint(rCenter, startArc, -stepAngle);
    [[[cakePath list] objectAtIndex:0] setVertices:endArc :rCenter];
    [[[cakePath list] objectAtIndex:1] setVertices:rCenter :startArc];
    [[[cakePath list] objectAtIndex:2] setCenter:rCenter start:startArc angle:-stepAngle];
    [cakePath setBoundsZero];
    /* set coordBounds to NSZeroRect */
    [cakePath setList:[[cakePath list] retain] optimize:NO];
    [[cakePath list] release];

    while (endAngle > graduateAngle-360.0)
    {
        path = [cakePath clippedFrom:self];
        if (!path || [[path list] count] <= 1)
        {
            startArc = endArc;
            endArc = vhfPointAngleFromRefPoint(rCenter, startArc, -stepAngle);
            [[[cakePath list] objectAtIndex:0] setVertices:endArc :rCenter];
            [[[cakePath list] objectAtIndex:1] setVertices:rCenter :startArc];
            [[[cakePath list] objectAtIndex:2] setCenter:rCenter start:startArc angle:-stepAngle];
            [cakePath setBoundsZero];
            /* set coordBounds to NSZeroRect */
            [cakePath setList:[[cakePath list] retain] optimize:NO];
            [[cakePath list] release];
            steps--; // correct col steps
            endAngle -= stepAngle; // correct endAngle !
            if (steps <= 1)
            {   [pool1 release]; [pool release];
                filled = oldFilled;
                return;
            }
        }
        else
            break; // end
        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }

    if ([colSpaceName isEqual:@"NSCalibratedRGBColorSpace"])
    {
        startCol1 = curCol1 = [startCol redComponent];
        startCol2 = curCol2 = [startCol greenComponent];
        startCol3 = curCol3 = [startCol blueComponent];
        endCol1 = [endCol redComponent];
        endCol2 = [endCol greenComponent];
        endCol3 = [endCol blueComponent];
    }
    else if ([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
    {
        startCol1 = curCol1 = [startCol cyanComponent];
        startCol2 = curCol2 = [startCol magentaComponent];
        startCol3 = curCol3 = [startCol yellowComponent];
        startCol4 = curCol4 = [startCol blackComponent];
        endCol1 = [endCol cyanComponent];
        endCol2 = [endCol magentaComponent];
        endCol3 = [endCol yellowComponent];
        endCol4 = [endCol blackComponent];
    }
    else // NSCalibratedWhiteColorSpace
    {
        startCol1 = curCol1 = [startCol whiteComponent];
        endCol1 = [endCol whiteComponent];
    }

    colStep1 = Diff(curCol1, endCol1);
    colStep2 = Diff(curCol2, endCol2);
    colStep3 = Diff(curCol3, endCol3);
    colStep4 = Diff(curCol4, endCol4);
    colStep1 /= steps;
    colStep2 /= steps;
    colStep3 /= steps;
    colStep4 /= steps;
    if (curCol1 > endCol1) colStep1 = -colStep1;
    if (curCol2 > endCol2) colStep2 = -colStep2;
    if (curCol3 > endCol3) colStep3 = -colStep3;
    if (curCol4 > endCol4) colStep4 = -colStep4;

    colStep1 = floor(colStep1*1000000.0)/1000000.0;
    colStep2 = floor(colStep2*1000000.0)/1000000.0;
    colStep3 = floor(colStep3*1000000.0)/1000000.0;
    colStep4 = floor(colStep4*1000000.0)/1000000.0;

    /* build our cake */
    if (startAngle >= 360.0)	startAngle -= 360.0;
    if (startAngle < 0.0)	startAngle += 360.0;
    startArc = vhfPointAngleFromRefPoint(rCenter, NSMakePoint(rCenter.x+rRadius, rCenter.y), startAngle);
    endArc = vhfPointAngleFromRefPoint(rCenter, startArc, stepAngle);
    [[[cakePath list] objectAtIndex:0] setVertices:endArc :rCenter];
    [[[cakePath list] objectAtIndex:1] setVertices:rCenter :startArc];
    [[[cakePath list] objectAtIndex:2] setCenter:rCenter start:startArc angle:stepAngle];
    [cakePath setBoundsZero];
    /* set coordBounds to NSZeroRect */
    [cakePath setList:[[cakePath list] retain] optimize:NO];
    [[cakePath list] release];

    VHFSetAntialiasing(NO);
    while (startAngle <= endAngle-stepAngle+10.0*TOLERANCE)
    {
        path = [cakePath clippedFrom:self];
        if (startAngle > endAngle-stepAngle && (!path || [[path list] count] <= 1))
            break;
        if ([[path list] count] > 1)
        {   [path sortList];
            if ([colSpaceName isEqual:@"NSCalibratedRGBColorSpace"])
                [path setFillColor:[NSColor colorWithCalibratedRed:curCol1 green:curCol2 blue:curCol3 alpha:1.0]];
            else if ([colSpaceName isEqual:@"NSDeviceCMYKColorSpace"])
                [path setFillColor:[NSColor colorWithDeviceCyan:curCol1 magenta:curCol2 yellow:curCol3 black:curCol4 alpha:1.0]];
            else
                [path setFillColor:[NSColor colorWithCalibratedWhite:curCol1 alpha:1.0]];
            [path drawWithPrincipal:principal];
            [graduateList addObject:[[path copy] autorelease]];
        }
        curCol1 = startCol1 + mul*colStep1;
        curCol2 = startCol2 + mul*colStep2;
        curCol3 = startCol3 + mul*colStep3;
        curCol4 = startCol4 + mul*colStep4;
        mul += 1.0;
        startArc = endArc;
        endArc = vhfPointAngleFromRefPoint(rCenter, startArc, stepAngle);
        [[[cakePath list] objectAtIndex:0] setVertices:endArc :rCenter];
        [[[cakePath list] objectAtIndex:1] setVertices:rCenter :startArc];
        [[[cakePath list] objectAtIndex:2] setCenter:rCenter start:startArc angle:stepAngle];
        [cakePath setBoundsZero];
        /* set coordBounds to NSZeroRect */
        [cakePath setList:[[cakePath list] retain] optimize:NO];
        [[cakePath list] release];
        startAngle += stepAngle;
        poolCnt++;
        if (poolCnt > 50)
        {   [pool1 release];
            pool1 = [NSAutoreleasePool new];
            poolCnt = 0;
        }
    }
    if (antialias) VHFSetAntialiasing(antialias);

    [pool1 release];
    [pool release];
    filled = oldFilled;
}

/*
 * Check for a control point hit. Return the point number hit in the pt argument.
 * Does not set the graphic selection!!
 */
- (BOOL)hitEdge:(NSPoint)p fuzz:(float)fuzz :(NSPoint*)pt :(float)controlsize
{   int	i;

    for (i=[list count]-1; i>=0; i--)
    {	id obj = [list objectAtIndex:i];

        if ([obj hitEdge:p fuzz:fuzz :pt :controlsize])
        {   NSPoint	p0, plast, prevPt;
            int		begIx = [self getFirstObjectOfSubPath:i];
            int		endIx = [self getLastObjectOfSubPath:begIx];

            p0 = [obj pointWithNum:0];
            /* pt mit 0 oder 1 checken */
            if ( Diff((*pt).x, p0.x) <= TOLERANCE && Diff((*pt).y, p0.y) <= TOLERANCE )
            {	int	prevI = (i-1 < begIx) ? (endIx) : (i-1);
                id	prevG = [list objectAtIndex:prevI];

                prevPt = [prevG pointWithNum:MAXINT];
                /* previous graphic is connected and give us no hit */
                if ( Diff(prevPt.x, p0.x) <= TOLERANCE && Diff(prevPt.y, p0.y) <= TOLERANCE &&
                     ![prevG hitEdge:p fuzz:fuzz :&plast :controlsize] )
                    continue;
                return YES;
            }
            plast = [obj pointWithNum:MAXINT];
            if ( Diff((*pt).x, plast.x) <= TOLERANCE && Diff((*pt).y, plast.y) <= TOLERANCE )
            {	int	nextI = (i+1 > endIx) ? (begIx) : (i+1);
                id	nextG = [list objectAtIndex:nextI];

                prevPt = [nextG pointWithNum:0];
                /* next graphic is connected and give us no hit */
                if ( Diff(prevPt.x, plast.x) <= TOLERANCE && Diff(prevPt.y, plast.y) <= TOLERANCE &&
                     ![nextG hitEdge:p fuzz:fuzz :&p0 :controlsize] )
                    continue;
                return YES;
            }
            return YES;
        }
    }

    return NO;
}

/*
 * Check for a control point hit.
 * Return the point number hit in the pt_num argument.
 */
- (BOOL)hitControl:(NSPoint)p :(int*)pt_num controlSize:(float)controlsize
{   int		i, j, cnt = [list count], pCnt = 0;
    BOOL	control = [(App*)NSApp control];

    for (i=0; i<cnt; i++)
    {	id obj = [list objectAtIndex:i];

        if ([obj hitControl:p :pt_num controlSize:controlsize])
        {
            /* check if we must grap the next/prev control pt (curves only) */
            if ( control && (!(*pt_num) || (*pt_num) == [obj numPoints]-1) )
            {   int	begIx = [self getFirstObjectOfSubPath:i];
                int	endIx = [self getLastObjectOfSubPath:begIx];

                /* check prev connected graphic */
                if ( !(*pt_num) )
                {   NSPoint	p0, prevPt;
                    int		pnum=0, prevI = (i-1 < begIx) ? (endIx) : (i-1);
                    id		prevG = [list objectAtIndex:prevI];

                    p0 = [obj pointWithNum:0];
                    prevPt = [prevG pointWithNum:MAXINT];
                    /* previous graphic is connected and give us a hit != last */
                    if ( Diff(prevPt.x, p0.x) <= TOLERANCE && Diff(prevPt.y, p0.y) <= TOLERANCE )
                    {
                        if ( [prevG hitControl:p :&pnum controlSize:controlsize] &&
                             pnum != [prevG numPoints]-1 )
                        {
                            /* now we must take prev graphic */
                            if ( selectedObject >= 0 && selectedObject != prevI )
                            {   [[list objectAtIndex:selectedObject] setSelected:NO];
                                selectedObject = -1;
                            }
                            *pt_num = pnum;
                            if (*pt_num == [prevG selectedKnobIndex]) // arc center we do not select the object
                                selectedObject = prevI;
                            /* correct pCnt */
                            pCnt = 0;
                            for (j=0; j<prevI; j++)
                                pCnt += [[list objectAtIndex:j] numPoints];
                            *pt_num += pCnt;
                            [self setSelected:YES];
                            return YES;
                        }
                    }
                }
                else /* check next connected graphic */
                {   NSPoint	pl, nextPt;
                    int		pnum=0, nextI = (i+1 > endIx) ? (begIx) : (i+1);
                    id		nextG = [list objectAtIndex:nextI];

                    nextPt = [nextG pointWithNum:0];
                    pl = [obj pointWithNum:MAXINT];
                    /* previous graphic is connected and give us a hit != last */
                    if ( Diff(nextPt.x, pl.x) <= TOLERANCE && Diff(nextPt.y, pl.y) <= TOLERANCE )
                    {
                        if ( [nextG hitControl:p :&pnum controlSize:controlsize] && pnum )
                        {
                            /* now we must take prev graphic */
                            if ( selectedObject >= 0 && selectedObject != nextI )
                            {   [[list objectAtIndex:selectedObject] setSelected:NO];
                                selectedObject = -1;
                            }
                            *pt_num = pnum;
                            if (*pt_num == [nextG selectedKnobIndex]) // arc center we do not select the object
                                selectedObject = nextI;
                            /* correct pCnt */
                            if ( nextI != i+1 )
                            {	pCnt = 0;
                                for (j=0; j<nextI; j++)
                                    pCnt += [[list objectAtIndex:j] numPoints];
                            }
                            else
                                pCnt += [obj numPoints];
                            *pt_num += pCnt;
                            [self setSelected:YES];
                            return YES;
                        }
                    }
                }
            }
            if ( selectedObject >= 0 && selectedObject != i )
            {   [[list objectAtIndex:selectedObject] setSelected:NO];
                selectedObject = -1;
            }
            if (*pt_num == [obj selectedKnobIndex]) // arc center we do not select the object
                selectedObject = i;
            *pt_num += pCnt;
            [self setSelected:YES];
            return YES;
        }
        pCnt += [obj numPoints];
    }
    return NO;
}

/* created:   16.09.95
 * modified:  2001-08-18
 * parameter: p	clicked point
 * purpose:   check whether point hits object
 */
- (BOOL)hit:(NSPoint)p fuzz:(float)fuzz
{   int		i;
    int		hit = NO;
    BOOL	alternate = [(App*)NSApp alternate];

    if ( !Prefs_SelectByBorder && filled && [self isPointInside:p] )
        return YES;

    for (i=[list count]-1; i>=0; i--)
    {	id obj = [list objectAtIndex:i];

        if ([obj hit:p fuzz:fuzz])
        {	hit = YES;
            [self deselectAll];
            if (alternate)
            {	[obj setSelected:YES];
                if (selectedObject >= 0 && selectedObject != i)
                    [[list objectAtIndex:selectedObject] setSelected:NO];
                selectedObject = i;
            }
            break;
        }
    }

    return (BOOL)hit;
}

- (void)changeDirectionOfSubPath:(int)startIx :(int)endIx
{   int	i, j;

    for (i=startIx, j=endIx; i<=j; i++, j--)
    {	id	obj;

        [[list objectAtIndex:i] changeDirection];
        if ( i==j )
            break;
        [[list objectAtIndex:j] changeDirection];
        obj = [[list objectAtIndex:j] retain];
        [list replaceObjectAtIndex:j withObject:[list objectAtIndex:i]];
        [list replaceObjectAtIndex:i withObject:obj];
        [obj release];
    }
    dirty = YES;
}

/* created:  1998-04-02
 * modified: 2012-01-20 (open path do not change direction here - allways wrong)
 *           2008-10-11 (use getLastObjectOfSubPath2 to allow open paths -- no)
 * optimize the way that the outer paths are optimized in ccw (cw) direction
 * and the inner paths are optimized in cw (ccw) direction
 * outer paths are the one with an even intersection count
 */
- (void)setDirectionCCW:(BOOL)ccw
{   int		begIx = 0, endIx = 0, cnt = [list count], i, lCount=0, iCntTot;
    NSPoint	p, p0, p1, *pts = NULL;
    BOOL	isCCW, needCCW;
    VLine	*line = [VLine line];
    NSRect	bRect;
    float	y, yMin, yMax, stepWi;

    /* open path - we cant determine direction */
    if ( ![self closed] )
    {   isDirectionCCW = ccw;
        return;
    }

    while ( begIx < cnt )
    {
        /* localize path */
        endIx = [self getLastObjectOfSubPath:begIx]; //  tolerance:TOLERANCE

        /* single element (hack?) */
        if ( begIx == endIx && ![[list objectAtIndex:begIx] isKindOfClass:[VArc class]] &&
             ![[list objectAtIndex:begIx] isKindOfClass:[VPolyLine class]])
        {   begIx = endIx + 1;
            continue;
        }

        /* count intersections of a horizontal line (with intersects our subpath) with the path */
        [[list objectAtIndex:begIx] getPoint:&p at:0];
        bRect = [self coordBounds];
        p0.x = bRect.origin.x - 2000.0; p1.x = bRect.origin.x+bRect.size.width + 2000.0;
        bRect = [self coordBoundsOfSubPath:begIx :endIx];
        yMin = bRect.origin.y;
        yMax = bRect.origin.y + bRect.size.height;
        stepWi = Max((yMax - yMin) / 10.0, TOLERANCE);
        for ( y=yMin+stepWi; y<yMax; y+=stepWi )
        {
            p0.y = p1.y = y;
            [line setVertices:p0 :p1];
            /* determine x for comparison left/right */
            for (i=begIx; i<=endIx; i++)
            {
                if ( [[list objectAtIndex:i] getIntersections:&pts with:line] )
                {   p.x = pts[0].x;
                    free(pts); pts = NULL;
                    break;
                }
            }
            for (i=[list count]-1, lCount=0, iCntTot=0; i>=0; i--)
            {   int	j, iCnt;

                if ( i >= begIx && i <= endIx )
                    continue;
                if ( (iCnt = [[list objectAtIndex:i] getIntersections:&pts with:line]) )
                {   iCntTot += iCnt;
                    for ( j=0; j<iCnt; j++ )
                        if ( pts[j].x < p.x )
                            lCount++;
                    free(pts); pts = NULL;
                }
            }
            //cnt = vhfFilterPoints(pts, cnt, 0.01)
            if ( Even(iCntTot) )	/* ok, we hit no edge */
                break;
        }

        /* if intersections to the left of our subpath are even this subpath becomes ccw (cw) */
        isCCW = [self directionOfSubPath:begIx :endIx];
        needCCW = (lCount%2) ? !ccw : ccw;
        if ( needCCW != isCCW )
            [self changeDirectionOfSubPath:begIx :endIx];
        begIx = endIx + 1;
    }
    isDirectionCCW = ccw;
}

- (int)getFirstObjectOfSubPath:(int)ix
{   int		i, cnt, begIx;
    NSPoint	beg, end;

    cnt = [list count];
    beg = [[list objectAtIndex:ix] pointWithNum:0];
    for ( i=ix-1; i>=0; i-- )
    {
        end = [[list objectAtIndex:i] pointWithNum:MAXINT];
        if ( !i || SqrDistPoints(beg, end) > (TOLERANCE*5)*(TOLERANCE*5) ) // small tolerance
        {   begIx = i;
            if ( i || (!i && SqrDistPoints(beg, end) > (TOLERANCE*5)*(TOLERANCE*5)) )
                begIx += 1; // dist to i -> i+1
            return begIx;
        }
        beg = [[list objectAtIndex:i] pointWithNum:0];
    }
    return ix;
}

/* find end of sub-path by testing between graphics for small distance
 * If we find a greater distance -> we find our end
 *
 * Note: This method works also for open paths !
 * Attention for questionings like: If ( begIx == endIx ) for open paths !
 * modified: 2008-07-06
 */
- (int)getLastObjectOfSubPath2:(int)startIx
{   int		i, cnt, endIx = startIx;
    float	d;
    NSPoint	start, beg, end;

    cnt = [list count];
    if (cnt <= startIx)
        return startIx;
    start = [[list objectAtIndex:startIx] pointWithNum:0];
    end   = [[list objectAtIndex:startIx] pointWithNum:MAXINT];
    for ( i=startIx+1; i<cnt; i++ )
    {
        beg = [[list objectAtIndex:i] pointWithNum:0];
        /* we need a bigger Tolerance here, for gaps coming from contour methods or other waste */
        if ( (d=SqrDistPoints(end, beg)) < (TOLERANCE*30.0)*(TOLERANCE*30.0) ) // instead 15  2016-09-30
        {   end = [[list objectAtIndex:i] pointWithNum:MAXINT];
            endIx = i;
            continue; // graphics connectet
        }
        else
            return endIx;
    }
    return endIx;
}

/* find end of sub-path by testing path-points for a small distance
 * to start point.
 * If a point is closer to start than to the next point -> that's our end
 *
 * Note: This method only works for closed paths !
 */
- (int)getLastObjectOfSubPath:(int)startIx
{   int		i, cnt, endIx;
    NSPoint	beg, end;

    cnt = [list count];
    beg = [[list objectAtIndex:startIx] pointWithNum:0];
    for ( i=startIx; i<cnt; i++ )
    {
        /* for i == startIx we also check if the object is closed by itself (rectangle, circle, ...) */
        end = [[list objectAtIndex:i] pointWithNum:MAXINT];
        if ( SqrDistPoints(beg, end) < (TOLERANCE*15)*(TOLERANCE*15) )      // small tolerance for -removeSingleGraphicsAtEnd, setDirectionCCW, contour:inlay:removeloops
        {
            if (i+1 < cnt)
            {   NSPoint	begN = [[list objectAtIndex:i+1] pointWithNum:0];   // start of next element

                if ( SqrDistPoints(end, begN) < (TOLERANCE*15)*(TOLERANCE*15) )
                    continue; // distance to next start point is better -> we stay in sub-path
            }
            endIx = i;
            return endIx;
        }
    }
    return startIx;
}

- (int)getLastObjectOfSubPath:(int)startIx tolerance:(double)tolerance;
{   int		i, cnt, endIx;
    NSPoint	beg, end;

    cnt = [list count];
    beg = [[list objectAtIndex:startIx] pointWithNum:0];
    for ( i=startIx; i<cnt; i++ )
    {
        /* for i == startIx we also check if the object is closed by itself (rectangle, circle, ...) */
        end = [[list objectAtIndex:i] pointWithNum:MAXINT];
        if ( SqrDistPoints(beg, end) < tolerance ) // contour:inlay:...
        {
            if (i+1 < cnt)
            {   NSPoint	begN = [[list objectAtIndex:i+1] pointWithNum:0];   // start of next element

                if ( SqrDistPoints(end, begN) < tolerance )
                    continue; // distance to next start point is better -> we stay in sub-path
            }
            endIx = i;
            return endIx;
        }
    }
    return startIx;
}

#define GradientNear(g, t) ([g isKindOfClass:[VCurve class]]) ? [g gradientNear:t] : [g gradientAt:t]

static NSPoint orthPointAt(id g, float r, int dirInd, float at)
{   float	b;
    NSPoint	p, grad, orthP;

	p = [g pointAt:at];			/*  point of object */
	grad = GradientNear(g, at);		/* gradient of point for outline object */

    if ( !(b = sqrt(grad.x*grad.x+grad.y*grad.y)) )
        orthP = p;
    else
    {   orthP.x = p.x + grad.y*r*dirInd/b;
        orthP.y = p.y - grad.x*r*dirInd/b;
    }
    return orthP;
}

/* created:   2008-04-14
 * modified:  2008-04-14
 * purpose:   get the direction of the elements from startIx until endIx
 * parameter: startIx
 *            endIx
 * return:    1 = ccw / 0 = cw
 *
 * get a pt little left/right of one sp graphic which do not cut the subPath
 * look if pt is inside or outside of subPath -> so we have our direction
 *
 */
- (int)directionOfSubPath:(int)startIx :(int)endIx
{   int		i, j, istep = (endIx-startIx)/7, intersection = NO, ccw = 0, cw = 0;
    float	dirInd = 1.0, d = 0.3; // right = 1.0 left = -1.0 ?????
	VLine	*tLine = [VLine line];
	NSRect	cBnds;

    if ( startIx == endIx )	// this is a 360 degree arc (circle)
    {	VGraphic	*obj = [list objectAtIndex:startIx];

        if ( [obj isKindOfClass:[VArc class]] )
            return ( [(VArc*)obj angle] > 0 ) ? 1 : 0;
        if ( [obj isKindOfClass:[VPolyLine class]] )
            return [(VPolyLine*)obj isDirectionCCW];
        return 1;
    }

    /* dirInd = 1.0 - right */
    /* check four points like this, three identic -> ok */
    for ( i=startIx; i<=endIx; (intersection || (endIx-startIx) < 10) ? (i++) : (i+=istep) )
    {	id			objI = [list objectAtIndex:i];
		NSPoint		oPt, beg = [objI pointAt:0.5]; // gradient at start
		int			cnt, inside=-1;  //, intersection = NO;

        intersection = NO;

		/* get pt orthogonal pt right of objI */
		oPt = orthPointAt(objI, d, dirInd, 0.5); // 0 is Beg
		[tLine setVertices:beg :oPt];

		/* check if the line between pt and p05  intersect our subPath */
		for (j=startIx; j<=endIx; j++)
		{	VGraphic	*objJ = [list objectAtIndex:j];
			NSPoint		*pts;
		
			if ( (cnt = [objJ getIntersections:&pts with:tLine]) )
			{
				free(pts); pts = NULL;
				if ( !(cnt == 1 && objJ == objI) )
				{
					intersection = YES;
					break;
				}
			}
		}
		/* else take the next graphic */
		if ( intersection )
			continue;

		/* get check if pt is inside or outside our subPath */
		/* 0 = outside * 1 = on * 2 = inside */
		inside = [self isPointInsideOrOn:oPt dist:TOLERANCE subPath:startIx :endIx];

		if ( inside == 1 )
			continue; // on ?
		/* outside - ccw - 1 */
		if ( !inside )
			ccw++; // return 1;
		/* inside - cw - 0 */
		else
			cw++;   // return 0;
	}

    if ( ccw || cw )
    {
        if (ccw > cw)
            return 1; // more are ccw
        else if (cw > ccw)
            return 0;
    }

	dirInd = -1.0; // left
    intersection = NO;
	/* check for points left of graphics */
    for ( i=startIx; i<=endIx; (intersection || (endIx-startIx) < 10) ? (i++) : (i+=istep) )
    {	id			objI = [list objectAtIndex:i];
		NSPoint		oPt, beg = [objI pointAt:0.5]; // gradient at start
		int			cnt, intersection = NO, inside=-1;

        intersection = NO;

		/* get pt orthogonal pt right of objI */
		oPt = orthPointAt(objI, d, dirInd, 0.5); // 0 is Beg
		[tLine setVertices:beg :oPt];

		/* check if the line between pt and p05  intersect our subPath */
		for (j=startIx; j<=endIx; j++)
		{	VGraphic	*objJ = [list objectAtIndex:j];
			NSPoint		*pts;
		
			if ( (cnt = [objJ getIntersections:&pts with:tLine]) )
			{
				free(pts); pts = NULL;
				if ( !(cnt == 1 && objJ == objI) )
				{
					intersection = YES;
					break;
				}
			}
		}
		/* else take the next graphic */
		if ( intersection )
			continue;

		/* get check if pt is inside or outside our subPath */
		/* 0 = outside * 1 = on * 2 = inside */
		inside = [self isPointInsideOrOn:oPt dist:TOLERANCE subPath:startIx :endIx];

		if ( inside == 1 )
			continue; // on ?
		/* outside - cw - 0 */
		if ( !inside )
			cw++;   // return 0;
		/* inside - ccw - 1 */
		else
			ccw++;  // return 1;
	}
    if ( ccw || cw )
    {
        if (ccw > cw)
            return 1; // more are ccw
        else if (cw > ccw)
            return 0;
    }
	cBnds = [self coordBoundsOfSubPath:startIx :endIx];
	if ( !(Diff(startIx, endIx) <= 10 && (cBnds.size.width < 10.0*TOLERANCE || cBnds.size.height < 10.0*TOLERANCE)) )
		NSLog(@"VPath.m: -directionOfSubPath: cant determine direction Bnds: o.x:%.2f o.y:%.2f s.w:%.2f s.h:%.2f",
			  cBnds.origin.x, cBnds.origin.y, cBnds.size.width, cBnds.size.height);
	return 0;
}
#if 0
/* created:   1996-06-08
 * modified:  2001-02-16
 * purpose:   get the direction of the elements from startIx until endIx
 * parameter: startIx
 *            endIx
 * return:    1 = ccw / 0 = cw
 *
 * rangles = sum of ccw angles
 * langles = sum of 360 - ccw angles
 *
 * rAngles = ccw angle between next Object to current Object
 *
 * extreme curves building a loop in the path are still a problem!
 */
- (int)directionOfSubPath:(int)startIx :(int)endIx
{   int		i;
    float	a = 0.0, rAngles = 0, lAngles = 0;

    if ( startIx == endIx )	// this is a 360 degree arc (circle)
    {	VGraphic	*obj = [list objectAtIndex:startIx];

        if ( [obj isKindOfClass:[VArc class]] )
            return ( [(VArc*)obj angle] > 0 ) ? 1 : 0;
        if ( [obj isKindOfClass:[VPolyLine class]] )
            return [(VPolyLine*)obj isDirectionCCW];
        return 1;
    }
    for ( i=startIx; i<=endIx; i++ )
    {	VGraphic	*objI = [list objectAtIndex:i];

        /* angle of object */
        if ( ([objI isKindOfClass:[VArc class]] || [objI isKindOfClass:[VCurve class]])
             && (a = [objI angle]) )
        {
            if ( [objI isKindOfClass:[VArc class]] )
            {
                /* we process the arc in quadrants and
                 * convert the arc angle into an angle between the tangents of
                 * the start and end points of each quadrant (180 - angle) and the rest:
                 * angle <=  90 -> 180 - angle
                 * angle <= 180 -> 90 + (180-(angle-90))
                 * angle <= 270 -> 90 + 90 + (180-(angle-180))
                 * all angles have to be positive (ccw) in the end !
                 */
                if (a >= 0.0)
                {   float	n = floor(a / 90.0);		// number of quadrants.
                    a = 180.0 - (a - n*90.0);			// convert rest of angle to tangent angle.
                    rAngles += n* 90.0;				// add tangent angles for quadrants, but
                    lAngles += n*270.0;				// leave rest for usual addition
                }
                else
                {   float	n = floor(a / -90.0);		// number of quadrants
                    a = 180.0 - (a - n*-90.0);			// convert rest to tangent angle
                    rAngles += n*270.0;
                    lAngles += n* 90.0;
                }

                /*s = [objI pointWithNum:0];	// this gives not the correct angle
                e = [objI pointWithNum:MAXINT];	// we should take the intersection of the tangents
                m = [(VArc*)objI pointAt:0.5];	// But, why not convert the angle of the arc?
                a = vhfAngleBetweenPoints(e, m, s);*/
            }
            rAngles += a;
            if ( [objI isKindOfClass:[VCurve class]] )	// curve builds two edges
                lAngles += 2*360.0 - a;
            else
                lAngles += 360 - a;
        }
        /* angle between end tangent and next start tangent */
        a = 360.0 - angleBetweenGraphicsInStartOrEnd(objI, (i<endIx) ? [list objectAtIndex:i+1]
                                                                     : [list objectAtIndex:startIx], YES);
        if ( Diff(a, 0.0) > 1 && Diff(a, 360.0) > 1 )	// 0.0 was > TOLERANCE
        {   rAngles += a;
            lAngles += 360.0 - a;
        }
    }
    return (rAngles < lAngles) ? 1 : 0;
}
#endif

/* created:   05.06.98
 * modified:  
 * purpose:   get the bounds of the elements from startIx until endIx
 * parameter: startIx
 *            endIx
 * return:    bounds
 */
- (NSRect)coordBoundsOfSubPath:(int)startIx :(int)endIx
{   int		i;
    NSRect	bbox, rect;

    bbox = [[list objectAtIndex:startIx] coordBounds];
    for ( i=startIx+1; i<=endIx; i++ )
    {
        rect = [[list objectAtIndex:i] coordBounds];
        bbox = VHFUnionRect(rect, bbox);
    }
    return bbox;
}

//#define Even(x) (((x)%2) ? 0 : 1)
#define SIDESTEP 0.15 // 0.3

- (BOOL)subPathInsidePath:(int)begIx :(int)endIx
{   int		k, lenSP = Min(100, [list count]), len = Min(100, [list count]);
    int		s, i, j, listCnt, iCnt=0, leftCnt, curSubPathEndIx = -1, spIcnt = 0, on = 0;
	float	tol = 0.1;
    NSPoint	end, lBeg, lEnd, *iPts, *spIpts; // iPts[[list count]], spIpts[[list count]];
    NSRect	bRect, spRect;
    VGraphic	*lineG = [VLine line];
        
    iPts = malloc(len * sizeof(NSPoint));
    spIpts = malloc(lenSP * sizeof(NSPoint));

    /* cut all graphics in path (but from begIx until endIx (our subPath))
     * with horicontal line through end of begIx graphic
     */
	spRect = [self coordBoundsOfSubPath:begIx :endIx];
    bRect = [self bounds];
	tol = (spRect.size.height/10.0); //*(spRect.size.height/10.0);

	for (k=begIx; k<=endIx; k++)
	{
        on = 0;
	    [[list objectAtIndex:k] getPoint:&end at:0.4];

		/*if ( k < endIx && (Diff(end.y, spRect.origin.y) <= tol ||
						   Diff(end.y, spRect.origin.y+spRect.size.height) <= tol) )
			continue;*/ // we check this now inside in an exacter way
		lBeg.y = lEnd.y = end.y;
		lBeg.x = bRect.origin.x -10.0;
		lEnd.x = bRect.origin.x + bRect.size.width + 10.0;
		[(VLine*)lineG setVertices:lBeg :lEnd];

		for (s=1; s<9; s++)
		{   int	left = 0, spLeft = 0, spRight = 0;
			NSRect	curRect=spRect;

            on = 0;
			spIcnt = 0;
			iCnt = 0;
			curSubPathEndIx = ( 0 == begIx ) ? (endIx) : ([self getLastObjectOfSubPath2:0]);
			if ( 0 != begIx )
				curRect = [self coordBoundsOfSubPath:0 :curSubPathEndIx];

			for ( i=0, listCnt = [list count]; i<listCnt; i++ )
			{   VGraphic	*g = [list objectAtIndex:i];
                NSRect      gBnds = [g coordBounds];
				NSPoint     *pts = NULL;
				int         cnt=0;

				if ( i > curSubPathEndIx)
				{
					/* add spIpts to iPts*/
					/* check if one spIpt is on end
					 * remove on point if spIpts are right of end odd (else add)
					 */
					spLeft = 0; spRight = 0;
					on = 0; left = 0;
					for (j=0; j<spIcnt; j++)
					{
						if ( Diff(spIpts[j].x, end.x) < 100.0*TOLERANCE )
						{   on++;
                            break;
						}
						else if ( spIpts[j].x < end.x )
							left++;
							
						if ( spIpts[j].x < spRect.origin.x )
							spLeft++;
						else if ( spIpts[j].x > spRect.origin.x+spRect.size.width )
							spRight++;
					}
                    if ( on )
                        break; // need other k graphic
					/* we dont add the hole subPath if on/it is on right side (else we shot our Even iCnt) */
					if ( !(on && Even(left)) && left && !(spLeft == spIcnt || spRight == spIcnt) )
					{
						if (iCnt+spIcnt >= len)
							iPts = realloc(iPts, (len+=spIcnt*2) * sizeof(NSPoint));
						for (j=0; j<spIcnt; j++)
							iPts[iCnt++] = spIpts[j];
					}
//					else if ( spIcnt )
//						NSLog(@"VPath.m:  -subPathInsidePath: checken !!!");

					spIcnt = 0;

					curSubPathEndIx = ( i == begIx ) ? (endIx) : ([self getLastObjectOfSubPath2:i]);
					if ( i != begIx )
						curRect = [self coordBoundsOfSubPath:i :curSubPathEndIx];
				}
				if ( i >= begIx && i <= endIx )
					continue;

				/* end.y is too near to other subPath up/down y */
				//if ( k < endIx && (Diff(end.y, curRect.origin.y) <= SIDESTEP*SIDESTEP ||
				//				   Diff(end.y, curRect.origin.y+curRect.size.height) <= SIDESTEP*SIDESTEP) )
				if ( k < endIx && gBnds.size.height < gBnds.size.width
                                /* gBnds width bereich sollte spRect treffen */
                                && ((gBnds.origin.x >= spRect.origin.x
                                     && gBnds.origin.x+gBnds.size.width <= spRect.origin.x+spRect.size.width)
                                    || (gBnds.origin.x <= spRect.origin.x
                                        && gBnds.origin.x+gBnds.size.width >= spRect.origin.x)
                                    || (gBnds.origin.x <= spRect.origin.x+spRect.size.width
                                        && gBnds.origin.x+gBnds.size.width >= spRect.origin.x+spRect.size.width))
                               && curRect.origin.x+curRect.size.width >= end.x-100.0*TOLERANCE
                               && (Diff(lEnd.y, gBnds.origin.y) <= 100.0*TOLERANCE ||
								   Diff(lEnd.y, gBnds.origin.y+gBnds.size.height) <= 100.0*TOLERANCE) )
				{
					s = 1;
                    on++; //	iCnt = -1; no sidestep !
					break;
				}
					
				/* check bounds of current subPath to spRect - completly left or right or inside spRect - continue behind */
				if ( !vhfIntersectsRect(curRect, spRect) /*|| vhfContainsRect(spRect, curRect)*/ )
				{	i = curSubPathEndIx;
					continue;
				}

				cnt = [g getIntersections:&pts with:lineG];

				if ( cnt == 2 &&
					 ( [g isKindOfClass:[VLine class]] || 				// horicontal line
					  ([g isKindOfClass:[VArc class]] && pts[0].x == pts[1].x) ) )	// tangential arc
				{	iCnt = -1; // not even
					free(pts); pts = NULL;
					break;
				}
				else if ( cnt && [g isKindOfClass:[VRectangle class]] )
				{   NSRect	gBounds = [g coordBounds];

					/* if one intersectionpoint layes on the uppest OR lowest y value of the rectangle */
					for (j=0; j<cnt; j++)
					{
						if ( (Diff(pts[j].y, gBounds.origin.y) <= TOLERANCE) ||
							(Diff(pts[j].y, (gBounds.origin.y+gBounds.size.height)) <= TOLERANCE) )
						{
							free(pts); pts = NULL;
							iCnt = -1; // not even
							break;
						}
					}
				}
				else if ( [g isKindOfClass:[VCurve class]] && cnt )
				{   NSPoint	p0, p1, p2, p3, tpoints[3];
					int	cpt, realSol=0, numSol=0;
					double	cy, by, ay, t[3];

					[(VCurve*)g getVertices:&p0 :&p1 :&p2 :&p3];
					/* we must look if one of the intersection points lying on a extrem point of the curve
					 * represent the curve with the equations
					 * x(t) = ax*t^3 + bx*t^2 + cx*t + x(0)
					 * y(t) = ay*t^3 + by*t^2 + cy*t + y(0)
					 * -> 3ay*t^2 + 2by*t + cy = 0
					 */
					cy = 3*(p1.y - p0.y);
					by = 3*(p2.y - p1.y) - cy;
					ay = p3.y - p0.y - by - cy;

					/* get the ts in which the tangente is horicontal
					 */
					numSol = svPolynomial2( 3.0*ay, 2.0*by, cy, t);

					/* when t is on curve */
					realSol=0;
					for ( j=0 ; j<numSol ; j++)
						if ( t[j] >= 0.0 && t[j] <= 1.0 )
							tpoints[realSol++] = [(VCurve*)g pointAt:t[j]];

					/* if one intersection point is identical with one tpoint -> -1 */
					for ( j=0 ; j<realSol ;j++ )
					{
                        for ( cpt=0 ; cpt<cnt ; cpt++ )
                        {
                            if ( Diff(tpoints[j].x, pts[cpt].x) <= TOLERANCE &&
								Diff(tpoints[j].y, pts[cpt].y) <= TOLERANCE )
							{
								free(pts); pts = NULL;
								iCnt = -1;
								break;
							}
                        }
                        if ( iCnt == -1 )
                            break;
                    }
				}
				else if ( cnt > 1 && [g isKindOfClass:[VPolyLine class]] )
				{   int	p, nPts = [g numPoints];
					NSPoint	pl0, pl1;

					/* check each line in PolyLine if horicontal */
					for (p=0; p < nPts-1; p++)
					{
						pl0 = [g pointWithNum:p];
						pl1 = [g pointWithNum:p+1];

						if (pointWithToleranceInArray(pl0, TOLERANCE, pts, cnt) && // both point are in pts
							pointWithToleranceInArray(pl1, TOLERANCE, pts, cnt))
						{
							free(pts); pts = NULL;
							iCnt = -1;
							break;
						}
					}
				}

				// add points if not allways inside pparray
				// else check if pt is edge pt of graphic -> return -1
				for (j=0; j<cnt && iCnt != -1; j++)
				{
					if (spIcnt+cnt >= lenSP)
						spIpts = realloc(spIpts, (lenSP+=cnt*2) * sizeof(NSPoint));

					if ( !pointWithToleranceInArray(pts[j], 2.0*TOLERANCE, spIpts, spIcnt) )
						spIpts[spIcnt++] = pts[j];
					else
					{   NSPoint	startG, endG;

						if ( [g isKindOfClass:[VLine class]] )		/* line */
							[(VLine*)g getVertices:&startG :&endG];
						else if ( [g isKindOfClass:[VArc class]] || [g isKindOfClass:[VCurve class]] )
						{   startG = [g pointWithNum:0];
							endG = [g pointWithNum:MAXINT];
						}
						else if ( [g isKindOfClass:[VRectangle class]] )
						{   NSPoint	ur, ul, size;
							[(VRectangle*)g getVertices:&startG :&size]; // origin size
							endG = startG; endG.x += size.x;
							ul = startG; ul.y += size.y;
							ur = endG; ur.y += size.y;
							if ( (Diff(pts[j].x, ul.x) + Diff(pts[j].y, ul.y) < 10.0*TOLERANCE) ||
								(Diff(pts[j].x, ur.x) + Diff(pts[j].y, ur.y) < 10.0*TOLERANCE) )
								continue; // do not add
						}
						else if ( [g isKindOfClass:[VPolyLine class]] )
						{   int	p, pCnt = [(VPolyLine*)g ptsCount], stop = 0;

							for (p=1; p<pCnt-1; p++)
							{   NSPoint	pt = [(VPolyLine*)g pointWithNum:p];
								if ( Diff(pts[j].x, pt.x) + Diff(pts[j].y, pt.y) < 10.0*TOLERANCE )
								{   stop = 1; break; }
							}
							if (stop)
								continue; // do not add
							[(VPolyLine*)g getEndPoints:&startG :&endG];
						}
						else
						{   startG.x = endG.x = pts[j].x; startG.y = endG.y = pts[j].y;
						}
						/* point is no edge point of g -> add */
						if ( (Diff(pts[j].x, startG.x) + Diff(pts[j].y, startG.y) > 10.0*TOLERANCE) &&
							(Diff(pts[j].x, endG.x) + Diff(pts[j].y, endG.y) > 10.0*TOLERANCE) )
							spIpts[spIcnt++] = pts[j];
						else
						{
							iCnt = -1; // /\ peek of this contraction twice force an error
							break;
						}
					}
				}
				if (pts)
                    free(pts);
				if ( iCnt < 0 )
					break; // sidestep !
			}
            if ( on )
                break; // need other k Graphic

			if ( iCnt < 0 )
			{   spIcnt = 0;
				lBeg.y = lEnd.y = end.y + ((s%2) ? (-SIDESTEP*s) : (SIDESTEP*s));
				while ( (lBeg.y < spRect.origin.y || lBeg.y > spRect.origin.y+spRect.size.width) && s < 7 )
				{
					s++;
					lBeg.y = lEnd.y = end.y + ((s%2) ? (-SIDESTEP*s) : (SIDESTEP*s));
				}
				[(VLine*)lineG setVertices:lBeg :lEnd];
				continue; // sidestep !
			}
			/* add spIpts */
			/* check if one spIpt is on end
			 * remove on point if spIpts are right of end odd (else add)
			 */
			spLeft = 0; spRight = 0;
			on = 0; left = 0;
			for (j=0; j<spIcnt; j++)
			{
				if ( Diff(spIpts[j].x, end.x) < 100.0*TOLERANCE )
				{   on++;
                    break;
				}
				else if ( spIpts[j].x < end.x )
					left++;

				if ( spIpts[j].x < spRect.origin.x )
					spLeft++;
				else if ( spIpts[j].x > spRect.origin.x+spRect.size.width )
					spRight++;
			}
            if ( on )
                break; // need other k Graphic
			/* we dont add the hole subPath if on/it is on right side (else we shot our Even iCnt) */
			if ( !(on && Even(left)) && left && !(spLeft == spIcnt || spRight == spIcnt) )
			{
				if (iCnt+spIcnt >= len)
					iPts = realloc(iPts, (len+=spIcnt*2) * sizeof(NSPoint));
				for (j=0; j<spIcnt; j++)
					iPts[iCnt++] = spIpts[j];
			}
			if ( (Even(iCnt) && iCnt) || (!iCnt && s == 1) ) // (cnt || s == 1) &&
				break;

			lBeg.y = lEnd.y = end.y + ((s%2) ? (-SIDESTEP*s) : (SIDESTEP*s));
			while ( (lBeg.y < spRect.origin.y || lBeg.y > spRect.origin.y+spRect.size.width) && s < 7 )
			{
				s++;
				lBeg.y = lEnd.y = end.y + ((s%2) ? (-SIDESTEP*s) : (SIDESTEP*s));
			}
			[(VLine*)lineG setVertices:lBeg :lEnd];
		}
		if ( !on && ((Even(iCnt) && iCnt) || (!iCnt && s == 1)) )
			break;
//		else
//			NSLog(@"VPath.m: -subPathInsidePath: take next graphic");
	}
	if ( iCnt < 0 )
	{
		NSLog(@"VPath.m: -subPathInsidePath: possible fault x:%.2f y:%.2f", end.x, end.y);
		return NO;
	}
    /* count iPts left of end */
    leftCnt = 0;
    for (i=0; i<iCnt; i++)
        if ( iPts[i].x < end.x || Diff(iPts[i].x, end.x) < 2.0*TOLERANCE )
            leftCnt++;

    /* release iPts */
    if ( [list count] )
    {   free(iPts);
        free(spIpts);
        //NSZoneFree((NSZone*)[(NSObject*)NSApp zone], *ppArray);
        iPts = spIpts = 0;
    }

    if ( !leftCnt || leftCnt == iCnt )	/* all points right or left of end */
        return NO;
    return ( Even(leftCnt) ) ? NO : YES;
}

/*
 * optimize path - return NO if we found a gap
 */
- (BOOL)optimizePath:(float)w
{   int		i1, i2, changeI, startIndex = 0;
    float	startDistance = MAXCOORD, dist = w*w, dHalf = (w/2.0)*(w/2.0), d1, d2, d, ds1, ds2;
    NSPoint	l1S, l1E, l2S, l2E, sGS = NSZeroPoint;
    BOOL    closedPath = NO; // after YES no insertion befor startIndex

    if ( ![list count] )
        return NO;

    for (i1 = 0; i1<(int)[list count]-1; i1++)
    {	VGraphic	*l1=[list objectAtIndex:i1];
        BOOL        insertAtStartIndex = NO;

        if ( [l1 isKindOfClass:[VRectangle class]] ||
             ([l1 isKindOfClass:[VArc class]] && Abs([(VArc*)l1 angle]) == 360.0) ||
             ([l1 isKindOfClass:[VPolyLine class]] &&
              SqrDistPoints([l1 pointWithNum:0], [l1 pointWithNum:MAXINT]) < TOLERANCE) )
        {   startIndex++;
            continue;
        }
        sGS = [[list objectAtIndex:startIndex] pointWithNum:0];
        startDistance = MAXCOORD;
        changeI = i1+1;
        l1S = [l1 pointWithNum:0];
        l1E = [l1 pointWithNum:MAXINT];
        for (i2=i1+1; i2<(int)[list count]; i2++)
        {   VGraphic	*l2=[list objectAtIndex:i2];

            l2S = [l2 pointWithNum:0];
            l2E = [l2 pointWithNum:MAXINT];
            d1 = SqrDistPoints(l1E, l2S); d2 = SqrDistPoints(l1E, l2E);
            if ( d1 < startDistance || d2 < startDistance )
            {
                if ( d2 < d1 )
                {   startDistance = d2;
                    [l2 changeDirection];
                    l2S = [l2 pointWithNum:0];
                    l2E = [l2 pointWithNum:MAXINT];
               }
                else
                    startDistance = d1;
                changeI = i2;
                insertAtStartIndex = NO;
                if ( Diff(startDistance, 0.0) == 0.0 )
                    break;
            }
            /* distance to start graphic start point ! - open paths */
            ds1 = SqrDistPoints(sGS, l2E); ds2 = SqrDistPoints(sGS, l2S);
            if ( closedPath == NO && (ds1 < startDistance || ds2 < startDistance) )
            {
                if ( ds2 < ds1 )
                {   startDistance = ds2;
                    [l2 changeDirection];
                }
                else
                    startDistance = ds1;
                changeI = i2;
                insertAtStartIndex = YES;
                if ( Diff(startDistance, 0.0) == 0.0 )
                    break;
            }
        }
        
        if ( insertAtStartIndex && startDistance ) /* close hole - also for open paths */
        {   VGraphic	*l2 = [list objectAtIndex:changeI], *sG = [list objectAtIndex:startIndex];

            d1 = SqrDistPoints(l1E, sGS);
            l2S = [l2 pointWithNum:0];
            l2E = [l2 pointWithNum:MAXINT];
            d = SqrDistPoints(l2E, sGS);
            /* if dist of l1E to startG is smaller than dist of nextG(l2) to l1S -> close to startG */
            if ( d && d1 < d )
            {   d = d1;
                [l2 changeDirection]; // endpoint is nearest, not good vor startIndex, and l2 become next startGraphic
                l2 = sG; l2S = sGS;
                if ( d && d <= dist )
                {	VGraphic	*lineG = [VLine line];

                    if ( d <= dHalf )
                    {
                        if ( [self closeGapBetween:l1 and:l2] ) // line added !
                        {   i1 += 1; changeI += 1; }            // behind l1 is correct here
                    }
                    else
                    {   [lineG setColor:[l2 color]];
                        [lineG setWidth:[l2 width]]; [lineG setSelected:NO];
                        [(VLine*)lineG setVertices:l1E :l2S];
                        [list insertObject:lineG atIndex:i1+1];
                        i1 += 1; changeI += 1;
                    }
                }
                else if ( startDistance > dist && d1 > dist )
                    NSLog(@"VPath.m: -optimizePath:: Gap 0"); // return NO;
                insertAtStartIndex = NO;
                closedPath = YES;
                startIndex = i1+1;
            }
            else if ( d <= dist ) // close dist from l2 (changeG) to sG
            {	VGraphic	*lineG = [VLine line];

                if ( d <= dHalf )
                {
                    if ( [self closeGapBetween:l2 and:sG] )
                    {   i1 += 1; changeI += 1;
                        lineG = [list objectAtIndex:changeI];
                        [list insertObject:lineG atIndex:startIndex];
                        [list removeObjectAtIndex:changeI+1];
                    } // line added behind l2 ! falsch oft immer muss vor sG !
                }
                else
                {   [lineG setColor:[l2 color]];
                    [lineG setWidth:[l2 width]]; [lineG setSelected:NO];
                    [(VLine*)lineG setVertices:l2E :sGS];
                    [list insertObject:lineG atIndex:startIndex];
                    i1 += 1; changeI += 1;
                }
            }
            else if ( startDistance > dist && d > dist )
                NSLog(@"VPath.m: -optimizePath:: Gap 0"); // return NO;
            if ( startDistance > dist )
                startIndex = i1+1;
        }
        else if ( startDistance ) /* close hole */
        {   VGraphic	*l2 = [list objectAtIndex:changeI], *sG = [list objectAtIndex:startIndex];

            d1 = SqrDistPoints(l1E, sGS);
            l2S = [l2 pointWithNum:0];
            d = SqrDistPoints(l1E, l2S);
            /* if dist to startG is smaller than dist to nextG -> close to startG*/
            if ( d && d1 < d )
            {   d = d1;
                l2 = sG; l2S = sGS;
                startIndex = i1+1;
                closedPath = YES;
            }
            if ( d && d <= dist )
            {	VGraphic	*lineG = [VLine line];

                if ( d <= dHalf )
                {
                    if ( [self closeGapBetween:l1 and:l2] ) // line added !
                    {   i1 += 1; changeI += 1; }            // behind l1 ist correct here
                }
                else
                {   [lineG setColor:[l2 color]];
                    [lineG setWidth:[l2 width]]; [lineG setSelected:NO];
                    [(VLine*)lineG setVertices:l1E :l2S];
                    [list insertObject:lineG atIndex:i1+1];
                    i1 += 1; changeI += 1;
                }
            }
            else if ( startDistance > dist && d1 > dist )
                NSLog(@"VPath.m: -optimizePath:: Gap"); // return NO;
            if ( startDistance > dist )
                startIndex = i1+1;
        }

        if ( insertAtStartIndex )
        {   VGraphic	*gCh=[list objectAtIndex:changeI];

            [list insertObject:gCh atIndex:startIndex];
            [list removeObjectAtIndex:changeI+1];
        }
        /* if the nearest element is not the next_in_list */
        else if ( changeI != (i1+1) )
        {   VGraphic	*gCh=[list objectAtIndex:changeI];

            [list insertObject:gCh atIndex:i1+1];
            [list removeObjectAtIndex:changeI+1];
        }
    }
    /* close hole from last to start element */
    {   VGraphic	*l1=[list objectAtIndex:[list count]-1];
        VGraphic	*l2= [list objectAtIndex:startIndex];

        l1E = [l1 pointWithNum:MAXINT];
        l2S = [l2 pointWithNum:0];
        if ( (d=SqrDistPoints(l1E, l2S)) && d <= dist )
        {   VGraphic	*lineG = [VLine line];

            if ( d <= dHalf )
                [self closeGapBetween:l1 and:l2];
            else
            {   [lineG setColor:[l2 color]];
                [lineG setWidth:[l2 width]]; [lineG setSelected:NO];
                [(VLine*)lineG setVertices:l1E :l2S];
                [list addObject:lineG];
            }
        }
        else if ( d )
            return NO;
    }

    dirty = YES;
    return YES;
}

/*
 * are the most meters of otherP inside path
 */
- (BOOL)isMostOfOtherPathInsidePath:(VPath*)otherP :(VPath*)path
{   int	i, cnt=[[otherP list] count], insideCnt=0, insideDist=0, outsideCnt=0, outsideDist=0;

    /* otherPath is tiled from path !
     * we count elements/distance of otherP wich are inside path and which not
     * if more than the half distance of hole otherP is inside path -> return YES
     */
    for (i=0; i<cnt;i++)
    {   VGraphic	*g = [[otherP list] objectAtIndex:i];
        NSPoint	pIn, start, end;

        [g getPoint:&pIn at:0.4];
        start = [g pointWithNum:0];
        end = [g pointWithNum:MAXINT];

        /* point inside path */
        if ( [path isPointInside:pIn] )
        {   insideCnt++;
            insideDist += SqrDistPoints(start, end);
        }
        else
        {   outsideCnt++;
            outsideDist += SqrDistPoints(start, end);
        }
    }
    if ( insideDist > (insideDist+outsideDist)/2.0 )
        return YES;
    return NO;
}

/* can only be used after optimize
 * remove graphics at list end which do not have two neighbours
 */
- (BOOL)isShortGraphic:g
{
    if ( [g isKindOfClass:[VLine class]] )
    {   NSPoint	p0, p1;
        [(VLine*)g getVertices:&p0 :&p1];
        if ( SqrDistPoints(p0, p1) < TOLERANCE*500.0 )
            return YES;
    }
    else if ( [g isKindOfClass:[VRectangle class]] )
    {   NSPoint	o, s;
        [(VRectangle*)g getVertices:&o :&s];
        if ( s.x < TOLERANCE*100.0 && s.y < TOLERANCE*100.0 )
            return YES;
    }
    else if ( [g isKindOfClass:[VArc class]] )
    {   float	r = [(VArc*)g radius], a = [(VArc*)g angle];
        if ( r < TOLERANCE*500.0 && Abs(a) < TOLERANCE*7000.0 )
            return YES;
    }
    else if ( [g isKindOfClass:[VCurve class]] )
    {   NSPoint	p0, p1, p2, p3;
        [(VCurve*)g getVertices:&p0 :&p1 :&p2 :&p3];
        if ( SqrDistPoints(p0, p3) < TOLERANCE*1000.0 && SqrDistPoints(p0, p1) < TOLERANCE*500.0 &&
            SqrDistPoints(p1, p2) < TOLERANCE*500.0 && SqrDistPoints(p2, p3) < TOLERANCE*500.0 )
            return YES;
    }
    return NO;
}

#define CLOSETOLERANCE 0.03
- (void)removeSingleGraphicsAtEnd:(VPath*)aPath
{   long	i, endIx;

    // for (i=[alist count]-1 ;i >= 0 ; i--)
    for (i=0; i < (int)[[aPath list] count]; i++)
    {   VGraphic	*gs = [[aPath list] objectAtIndex:i];

        endIx = [aPath getLastObjectOfSubPath:i]; // tolerance:TOLERANCE*3.0

        if ( i == endIx && [self isShortGraphic:gs] )
        {   [[aPath list] removeObjectAtIndex:i];
            i--;
        }
        else if ( i != endIx && Diff(i, endIx) < 3 ) // max 3 gr
        {   int	j, remove = 1;

            for (j=i ;j < endIx ; j++)
            {   if ( ![self isShortGraphic:[[aPath list] objectAtIndex:j]] )
                {   remove = 0;
                    break;
                }
            }
            if ( remove )
            {   for (j=i ;j < endIx ; j++)
                {   [[aPath list] removeObjectAtIndex:j];
                    j--;
                    endIx--;
                }
                i--;
            }
            else
                i = endIx;
        }
        else
            i = endIx;
    }
}

/* always two points refer to each other in array
 * j is index of first point-pair we check
 * i pair we must change - cant't explain
 */
BOOL begEndPairTwiceInArray(int ix, NSPoint *array, int cnt)
{   int	i;

    for (i=0; i<cnt-1; i+=2)
        if ( i != ix
            && Diff(array[ix].x, array[i+1].x) + Diff(array[ix].y, array[i+1].y) <= 30.0*TOLERANCE
            && Diff(array[ix+1].x, array[i].x) + Diff(array[ix+1].y, array[i].y) <= 30.0*TOLERANCE)
            return YES;
    return NO;
}

 /* modified: 2014-09-19
 * purpose:  return YES, if value is in array
 */
int cntIsIntValueInArray(int val, int* array, int cnt)
{   int	i, count=0;
    
    for (i=0; i<cnt; i++)
        if ( array[i] == val )
            count++;
    return count;
}

/* here we remove the loops
 * first we remove hole selected subPaths
 * than we join subPaths wich overlap each other
 * and now we look for overlaps inside subPath itself
 * and for loops in subPath
 * this three things we do only if we find conforming points !
 * and check if path is realy closed (closing little gaps)
 * modified: 2016-09-21 (if ( j > k ) from to correction - wrong - removed)
 */
- (void)optimizeSubPathsToClosedPath:(VPath*)path :(float)w :(BOOL**)subPathSplitted :(int)subPathCnt
{   int		i, listCnt = [[path list] count], scnt = listCnt*5, oldSubPathCnt = subPathCnt;
    int     *addedAtEnd = NULL, addCnt = 0, noticeJ = -1, noticeK = -1;
    float	tol = 15.0*TOLERANCE; // 5.0 // 10.0 // 11.0
    BOOL	openPath = NO;

    /* remove subPaths were all graphics are selected */
    for (i=0; i<listCnt; i++)
    {	VPath		*sp = [[path list] objectAtIndex:i];
        int		j, spCnt = [[sp list] count], startJ = spCnt;

        /* search for a not selected graphic */
        for (j=0; j<spCnt; j++)
        {   VGraphic	*curG = [[sp list] objectAtIndex:j];
            NSPoint	s, e;

            s = [curG pointWithNum:0];
            e = [curG pointWithNum:MAXINT];

            if (![curG isSelected] /*&& SqrDistPoints(s, e) > minL*/ )
            {   startJ = j;
                break;
            }
        }
        /* no one found -> remove subPath */
        if (startJ >= spCnt)
        {
            [[sp list] removeAllObjects];
            (*subPathSplitted)[i] = NO; // time
            continue;
        }
    }

    /* join subPaths with each other */
    addedAtEnd = NSZoneMalloc((NSZone*)[(NSObject*)NSApp zone], scnt * sizeof(int));
    for (i=0, listCnt = [[path list] count]; i<listCnt; i++)
    {	VPath		*sp = [[path list] objectAtIndex:i];
        int         j, k, spCnt = [[sp list] count], startJ = spCnt, selected = 0;
        VGraphic    *startG=nil;
        BOOL        stop = NO, added = NO, hitted = NO;

        if (!spCnt || (*subPathSplitted)[i] == NO)
            continue;
        /* search for a not selected graphic */
        for (j=0; j<spCnt; j++)
        {   VGraphic	*curG = [[sp list] objectAtIndex:j];

            if (![curG isSelected] /*&& SqrDistPoints(s, e) > minL*/ )
            {   startJ = j;
                break;
            }
        }
        /* no one found -> remove subPath - also possible after we remove something */
        if (startJ >= spCnt)
        {
            [[sp list] removeAllObjects];
            (*subPathSplitted)[i] = NO; // time
            continue;
        }
        /* subPathSplitted -> look for a not selected graphic - and next for a selected graphic */
        startG = [[sp list] objectAtIndex:startJ];
        for (j=startJ; j<spCnt; j++)
        {   VGraphic	*curG = [[sp list] objectAtIndex:j];
            NSPoint     ce;

            if ([curG isSelected])
                continue;

            ce = [curG pointWithNum:MAXINT]; // last not selected bevor seleted Graphics - break in k loop

            for (k=((j+1 < spCnt)?(j+1):0); k<((j+1 < spCnt)?spCnt:startJ); k++)
            {   VGraphic	*nextG = [[sp list] objectAtIndex:k];
                NSPoint		ns, ne;
                float		distance = MAXCOORD;
                int         l, m, n;

                ns = [nextG pointWithNum:0];
                ne = [nextG pointWithNum:MAXINT];
                distance = SqrDistPoints(ce, ns);
                if (Diff(distance, 0.0) <= TOLERANCE && ![nextG isSelected])
                {
                    break; // nothing to do graphics laying correct - so curG is last not Selected Graphic
                }
                else if ([nextG isSelected]) // one of the selected Graphics after the last notSelected Gs
                {   int         selectedGs = 0;
                    VGraphic    *ngp1 = [[sp list] objectAtIndex:((k+1) < spCnt) ? (k+1) : (0)];

                    stop = NO; added = NO;
                    /* search the end of the selected graphics */
                    for (l=((k+1 < spCnt) ? (k+1):0); l < ((k+1 < spCnt) ? spCnt:k); l++)
                    {   VGraphic	*lg = [[sp list] objectAtIndex:l];
                        NSPoint		s, e;

                        s = [lg pointWithNum:0];
                        e = [lg pointWithNum:MAXINT];
                        /* lg is selected */
                        if ([lg isSelected])
                        {
                            selectedGs++;
                            if (l+1 >= spCnt)
                                l = -1; // so we go on at 0
                            if (l == k)
                                break; // one time around !!!
                            continue;
                        }
                        /* lg close to curG end !! - this is a selected loop inside subPath */
                        else if ( Diff(l, k) > 1 &&
                                  Diff(SqrDistPoints(ce, s), 0.0) <= TOLERANCE )
                        {   int  to = (((l-1) < 0) ? (spCnt-1):(l-1));
                            int  from = ((j+1) < spCnt) ? (j+1) : (0);
#if 1
//                          NSLog(@"-optimizeSubPathsToClosedPath::: remove inside selected loop");
                            for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                            {
                               [[sp list] removeObjectAtIndex:m];
                               spCnt--;
                               /* we removed befor j -> j move one down in list !!! */
                               if (m < from) { from--; to--; } // to hold state of to < from
                               if (m < j) j--;
                               if (m < startJ) startJ--;
                               
                               if (!m && to < from) // we step over 0 - second part until from !
                               {   m = spCnt;
                                   to = from+1; // little hack mh - second part until from !
                               }
                            }
                            j--; // one back if point hit other path
#endif
                            stop = YES;
                            break;
                        }
                        /* end of selected graphics in sp */
                        else
                        {   int		o, backSelected = 0;
                            VGraphic	*lgm1, *lgm2, *cgp1, *cgp2;
                            int		from = -1, to = -1;
                            int		possCntS = 2, possCntE = 2, possCntE1 = 2;
                            int     possibleSi[3], possibleEi[3], possibleEi1[3];
                            NSPoint	possibleS[3], possibleE[3], possibleE1[3], em1, em2, csp1, csp2;
                            NSPoint	nsp1 = [ngp1 pointWithNum:0]/*, nsm1 = [curG pointWithNum:0]*/;
//                            float	sqrTolTen = (10.0*TOLERANCE)*(10.0*TOLERANCE);

                            /* check distance around - one/two graphic above end of selected graphic(s) */
                            lgm1 = [[sp list] objectAtIndex:(((l-1) < 0) ? (spCnt-1):(l-1))];
                            em1 = [lgm1 pointWithNum:MAXINT];
                            lgm2 = [[sp list] objectAtIndex:(((l-2) < 0) ? (spCnt+(l-2)):(l-2))];
                            em2 = [lgm2 pointWithNum:MAXINT];

                            /* check distance around - one/two graphic above start of selected graphic(s) */
                            cgp1 = [[sp list] objectAtIndex:((j+1) < spCnt) ? (j+1) : (0)];
                            csp1 = [cgp1 pointWithNum:0];
                            cgp2 = [[sp list] objectAtIndex:(((j+2) < spCnt) ? (j+2) : ((j+2) - spCnt))];
                            csp2 = [cgp2 pointWithNum:0];

                            if (!selectedGs)
                                possCntS = possCntE = possCntE1 = 1; // one graphic is selected
/*                            else
                            {   if ( [ngp1 length] > 0.2 )
                                    possCntS = 1;
                                if ( [lgm2 length] > 0.2 )
                                    possCntE = 1;
                                if ( [cgp2 length] > 0.2 )
                                    possCntE1 = 1;
                            }
*/
                            /* flexible test graphic between start/end of not selected graphics - k */
                            possibleS[0] = ns; possibleSi[0] = k; // nextG start
                            possibleS[1] = nsp1; possibleSi[1] = ((k+1) < spCnt) ? (k+1) : (0); // nextG+1 start

                            /* end of selected graphics - l  */
                            possibleE[0] = em1; possibleEi[0] = ((l-1) < 0)?(spCnt-1):(l-1); // lgm1 end
                            possibleE[1] = em2; // lgm2 end
                            possibleEi[1] = ((l-2) < 0) ? (((l-2) == -1) ? (spCnt-1):(spCnt-2)) : (l-2);

                            /* start of selected graphics - j */
                            possibleE1[0] = csp1; possibleEi1[0] = ((j+1) < spCnt) ? (j+1) : (0); // curG +1
                            possibleE1[1] = csp2; // cgp2 start
                            possibleEi1[1] = (((j+2) < spCnt) ? (j+2) : ((j+2) - spCnt));

                            /* check if backward are selected elements in sp path !!!!! */
                            from = ((l-1) < 0) ? (spCnt-1) : (l-1);
                            to = k;
                            for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                            {
                                if ([[[sp list] objectAtIndex:m] isSelected])
                                    backSelected++;
                                if (!m && to < from) // we step over 0 - second part until from !
                                {   m = spCnt;
                                    to = from+1; // little hack mh - second part until from !
                                }
                            }

                            /* search through other subPaths which are splitted */
                            for (o=0; o < listCnt; o++)
                            {   VPath	*oSp=nil;
                                BOOL	secondTime = NO;
                                BOOL	oStartIsSelected = YES;
                                int     notSelected = 0, selected = 0, oSpCnt, oStart = -1;
                                NSPoint	oStartPt = NSZeroPoint;

                                if (o == i || !(*subPathSplitted)[o])
                                    continue;

                                oSp = [[path list] objectAtIndex:o];
                                oSpCnt = [[oSp list] count];

                                /* search in other subPath for graphic which hit one of possibleE/S */
                                /* with enoth space between ! */
                                /* selected or not selected is not interesting */
                                for (n=0; n < oSpCnt; n++)
                                {   VGraphic	*nlG = [[oSp list] objectAtIndex:n];
                                    VGraphic	*nlGm1 = nil, *nlGm2 = nil;
                                    NSPoint	nls, nle;

                                    nlGm1 = [[oSp list] objectAtIndex:(((n-1) < 0) ? (oSpCnt-1) : (n-1))];
                                    if (oSpCnt > 1)
                                        nlGm2 = [[oSp list] objectAtIndex:(((n-2) < 0)?(oSpCnt+(n-2)):(n-2))];

                                    if (n == oStart)
                                        break;
                                    nls = [nlG pointWithNum:0];
                                    nle = [nlG pointWithNum:MAXINT];
                                    /* nlG hit one of possibleE/possibleS */
                                    if ((oStart == -1 || secondTime == NO) &&
                                        (([nlG isSelected] && (![nlGm1 isSelected] || ![nlGm2 isSelected])) ||
                                         (![nlG isSelected] && ([nlGm1 isSelected] || [nlGm2 isSelected]))) &&
                                        (pointWithToleranceInArray(nls, tol, possibleE, possCntE) ||
                                         pointWithToleranceInArray(nls, tol, possibleS, possCntS) ||
                                         pointWithToleranceInArray(nls, tol, possibleE1, possCntE1)))
                                    {
                                        hitted = YES;
                                        if (oStart != -1)
                                            secondTime = YES; // else we got a loop
                                        oStart = n; oStartPt = nls;
                                        if (![nlG isSelected]) // nlG is NOT selected - we search not sels
                                        {   oStartIsSelected = NO;
                                            selected = 0;
                                        }
                                        else
                                        {   oStartIsSelected = YES;
                                            notSelected = 0;
                                        }
                                    }
                                    if (oStart != -1 && ![nlG isSelected])
                                        notSelected++; // too much not selected elements to remove ! no join
                                    else if (oStart != -1 && [nlG isSelected])
                                        selected++; // too much selected elements ! no join
#if 0
                                    if (oStart != -1 && oStartIsSelected == YES && ![nlG isSelected])
                                        notSelected++; // too much not selected elements to remove ! no join
                                    else if (oStart != -1 && oStartIsSelected == NO && [nlG isSelected])
                                        selected++; // too much selected elements ! no join
#endif
                                    /* lg is selected and close to nextG(k) start OR to lgm1 end */
                                    if (oStart != -1 &&
//                                        ((oStartIsSelected == YES && notSelected > 2 && backSelected < 3) ||
//                                       (oStartIsSelected == YES && notSelected < 3) ||
///* wichtig ? */                                         (oStartIsSelected == NO && selected < 3)) &&
                                        ((oStartIsSelected == YES && notSelected > 2 && backSelected < 3) ||
                                         (oStartIsSelected == YES && notSelected < 3) ||
                                         (oStartIsSelected == NO && notSelected && selected < 5 &&
                                          selected <notSelected+2)) &&
                                        SqrDistPoints(oStartPt, nle) > TOLERANCE &&
                                        ((pointWithToleranceInArray(oStartPt, tol, possibleE, possCntE) &&
                                          pointWithToleranceInArray(nle, tol, possibleS, possCntS)) ||
                                         (pointWithToleranceInArray(oStartPt, tol, possibleS, possCntS) &&
                                          pointWithToleranceInArray(nle, tol, possibleE, possCntE)) ||
                                         (pointWithToleranceInArray(oStartPt, tol, possibleE1, possCntE1) &&
                                          pointWithToleranceInArray(nle, tol, possibleS, possCntS)) ||
                                         (pointWithToleranceInArray(oStartPt, tol, possibleS, possCntS) &&
                                          pointWithToleranceInArray(nle, tol, possibleE1, possCntE1))))
                                    {   BOOL	changeDirection = NO;
                                        int		at = j+1, q;

/* check next three graphics */

                                        from = to = -1;
                                        /* remove graphics - from current subPath - sp */
                                        if (pointWithToleranceInArray(oStartPt, tol, possibleE, possCntE))
                                        {
                                            for (q=0; q<possCntE; q++)
                                                if (SqrDistPoints(oStartPt, possibleE[q]) < tol)
                                                {
                                                    to = possibleEi[q];
                                                    break;
                                                }
                                            for (q=0; q<possCntS; q++)
                                                if (SqrDistPoints(nle, possibleS[q]) < tol)
                                                {
                                                    from = possibleSi[q];
                                                    at = from;
                                                    break;
                                                }
                                        }
                                        else if (pointWithToleranceInArray(nle, tol, possibleE, possCntE))
                                        {   for (q=0; q<possCntS; q++)
                                                if (SqrDistPoints(oStartPt, possibleS[q]) < tol)
                                                {
                                                    from = possibleSi[q];
                                                    at = from;
                                                    break;
                                                }
                                            for (q=0; q<possCntE; q++)
                                                if (SqrDistPoints(nle, possibleE[q]) < tol)
                                                {
                                                    to = possibleEi[q];
                                                    break;
                                                }
                                        }
                                        else if (pointWithToleranceInArray(oStartPt, tol, possibleE1, possCntE1))
                                        {
                                            for (q=0; q<possCntE1; q++)
                                                if (SqrDistPoints(oStartPt, possibleE1[q]) < tol)
                                                {
                                                    from = possibleEi1[q];
                                                    at = from;
                                                    break;
                                                }
                                            for (q=0; q<possCntS; q++)
                                                if (SqrDistPoints(nle, possibleS[q]) < tol)
                                                {
                                                    to = possibleSi[q];
                                                    break;
                                                }
                                        }
                                        else if (pointWithToleranceInArray(nle, tol, possibleE1, possCntE1))
                                        {   for (q=0; q<possCntS; q++)
                                                if (SqrDistPoints(oStartPt, possibleS[q]) < tol)
                                                {
                                                    to = possibleSi[q];
                                                    break;
                                                }
                                            for (q=0; q<possCntE1; q++)
                                                if (SqrDistPoints(nle, possibleE1[q]) < tol)
                                                {
                                                    from = possibleEi1[q];
                                                    at = from;
                                                    break;
                                                }
                                        }
                                        if (from == -1 || to == -1)
                                            break;
                                        for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                                        {
                                            [[sp list] removeObjectAtIndex:m];
                                            spCnt--;
                                            /* we removed befor j -> j move one down in list !!! */
                                            if (m < from) { from--; to--; } // to hold state to < from
                                            if (m < j) j--;
                                            if (m < startJ) startJ--;
                                            if (m < at) at--;

                                            if (!m && to < from) // we step over 0 - second part until from !
                                            {   m = spCnt;
                                                to = from+1; // little hack mh - second part until from !
                                            }
                                        }
                                        /* sort graphics from oSp into sp */
                                        changeDirection = NO;
                                        //if (pointWithToleranceInArray(nle, tol, possibleS, possCnt))
                                        if (pointWithToleranceInArray(oStartPt, tol, possibleE, possCntE))
                                        {
                                            if (oStartIsSelected == YES) // 
                                            {
                                                from = (n+1 < oSpCnt) ? (n+1) : 0; // n if remove
                                                to = ((oStart-1) < 0) ? (oSpCnt-1):(oStart-1);
                                            }
                                            else
                                            {   from = oStart;
                                                to = n;
                                                changeDirection = YES;
                                            }
                                        }
                                        else if (pointWithToleranceInArray(nle, tol, possibleE, possCntE))
                                        {   if (oStartIsSelected == YES)
                                            {   from = (n+1 < oSpCnt) ? (n+1) : 0;
                                                to = ((oStart-1) < 0) ? (oSpCnt-1):(oStart-1);
                                                changeDirection = YES;
                                            }
                                            else
                                            {   to = n;
                                                from = oStart;
                                            }
                                        }
                                        else if (pointWithToleranceInArray(oStartPt, tol, possibleE1, possCntE1))
                                        {
                                            if (oStartIsSelected == YES)
                                            {
                                                to = (n+1 < oSpCnt) ? (n+1) : 0; // n if remove
                                                from = ((oStart-1) < 0) ? (oSpCnt-1):(oStart-1);
                                                changeDirection = YES;
                                            }
                                            else
                                            {   from = oStart;
                                                to = n;
                                            }
                                        }
                                        else if (pointWithToleranceInArray(nle, tol, possibleE1, possCntE1))
                                        {
                                            if (oStartIsSelected == YES) // 
                                            {
                                                from = (n+1 < oSpCnt) ? (n+1) : 0; // n if remove
                                                to = ((oStart-1) < 0) ? (oSpCnt-1):(oStart-1);
                                            }
                                            else
                                            {   from = n;
                                                to = oStart;
                                                changeDirection = YES;
                                            }
                                        }
                                        /* insert other subPath - not Selected part */
                                        /* at cur subPath j+1 */
                                         /* remove graphics in other subPath */
                                        if (!spCnt)
                                            at = 0;	
                                        for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                                        {   VGraphic	*g = [[oSp list] objectAtIndex:m];

                                            if (changeDirection)
                                                [g changeDirection];
                                            [[sp list] insertObject:g atIndex:at];
                                            spCnt++;
                                            //if (notSelected > 2)
                                            {   [[oSp list] removeObjectAtIndex:m];
                                                oSpCnt--;
                                                if (m < from) { from--; to--; } // to hold state of to < from
                                            }
                                            if (!m && to < from) // we step over 0 - second part until from !
                                            {   m = oSpCnt;
                                                to = from+1; // little hack mh - second part until from !
                                            }
                                        }
                                        /* check oSp if only selected inside !!! */
                                        //if (notSelected > 2)
                                        {   notSelected = 0;
                                            for (m=0; m<oSpCnt; m++)
                                            {
                                                if (![[[oSp list] objectAtIndex:m] isSelected])
                                                {   notSelected++;
                                                    if (notSelected > 2)
                                                        break; // we do not remove this subpath
                                                }
                                            }
                                        }
                                        /* remove other subPath graphics */
                                        /* and subPathSplitted[o] = NO */
                /*if (!notSelected)*/   if (notSelected < 3)
                                        {   [[oSp list] removeAllObjects];
                                            (*subPathSplitted)[o] = NO; // time
                                        }
                                        added = YES; hitted = NO;
                                       // j = -1; // start new for removes at begin of sp with this oSp
                                        break;
                                    }
                                    if (n+1 >= oSpCnt && oStart != -1)
                                        n = -1;
                                }
                                if (added == YES)
                                    break; // o loop
                            }
                        }
                        break; // l loop
                    }
                    if (stop == YES || added == YES)
                        break; // k loop - look for next selectedG - !!!!!!!!! else loop for k !!!???
                }
                else
                    break; // not selected Graphic !

//else NSLog(@"-optimizeSubPathsToClosedPath: Gap in oSp");
            }
            if (added == YES)
                break; // j loop
        }
        /* move subPath at end of list perhaps two other paths must first join with each other
         * to get the right points
         */
        if (!added && (*subPathSplitted)[i] == YES) // !added - new
        {
            for (j=0; j<spCnt; j++)
            {
                if ([[[sp list] objectAtIndex:j] isSelected])
                {   selected++;
                    if (selected > 1 && (!valueInArray(i, addedAtEnd, addCnt) ||
                                         (hitted && cntIsIntValueInArray(i, addedAtEnd, addCnt) < 5))) // loop else
                    {
                        [[path list] insertObject:sp atIndex:listCnt];
                        [[path list] removeObjectAtIndex:i];
                        (*subPathSplitted)[listCnt-1] = (*subPathSplitted)[i];    // -1 2016-05-23
                        for (k=i; k<listCnt-1; k++)                         // -1 2016-05-23
                            (*subPathSplitted)[k] = (*subPathSplitted)[k+1];

                        for (k=0; k<addCnt; k++)
                            addedAtEnd[k] = (addedAtEnd[k]-1 >= 0) ? (addedAtEnd[k]-1) : (listCnt-1); // indexes step one back or around
                        if (valueInArray(i, addedAtEnd, addCnt))
                        {
                            for (k=0; k<addCnt; k++)    // korrect indexes to get the korrect ones
                                if ((addedAtEnd[k])+1 == i)
                                    addedAtEnd[k] = listCnt-1;
                        }
                        if (addCnt+1 > scnt)
                            addedAtEnd = NSZoneRealloc((NSZone*)[(NSObject*)NSApp zone], addedAtEnd, (scnt+=5) * sizeof(int));

                        addedAtEnd[addCnt++] = listCnt-1; // new one
                        i--;
                        break;
                    }
                    else if (selected > 1)
                    {   if (added == YES)
                            i--;
                        break;
                    }
                }
            }
        }
        else if (added == YES)
            i--;
    }
    NSZoneFree((NSZone*)[(NSObject*)NSApp zone], addedAtEnd);
    addedAtEnd = NULL;

//return;
    tol = 10.0*TOLERANCE; // 5.0 // 10.0 // 11.0

    /* search for overlaps inside subPath
     * and for loops
     */
    for (i=0, listCnt = [[path list] count]; i<listCnt; i++)
    {	VPath		*sp = [[path list] objectAtIndex:i];
        int         j, k, spCnt = [[sp list] count], startJ = spCnt;
        VGraphic	*startG=nil;

        if (!spCnt)
            continue;
        /* search for a not selected graphic */
        for (j=0; j<spCnt; j++)
        {   VGraphic	*curG = [[sp list] objectAtIndex:j];
            /*NSPoint     s, e;

            s = [curG pointWithNum:0];
            e = [curG pointWithNum:MAXINT];*/

            if (![curG isSelected] /*&& SqrDistPoints(s, e) > minL*/ )
            {   startJ = j;
                break;
            }
        }
        /* no one found -> remove subPath */
        if (startJ >= spCnt)
        {
            [[sp list] removeAllObjects];
            (*subPathSplitted)[i] = NO; // time
            continue;
        }
        /* search for a selected graphic after a not selected graphic */
        startG = [[sp list] objectAtIndex:startJ];
        for (j=startJ; j<spCnt; j++)
        {   VGraphic	*curG = [[sp list] objectAtIndex:j];
            NSPoint	ce;

            if ([curG isSelected])
                continue;

            ce = [curG pointWithNum:MAXINT]; // last not selected graphic - break in k loop

            for (k=((j+1 < spCnt)?(j+1):0); k<((j+1 < spCnt)?spCnt:startJ); k++)
            {   VGraphic	*nextG = [[sp list] objectAtIndex:k];
                NSPoint		ns, ne;
                float		distance = MAXCOORD;
                int         l, m, n;

                ns = [nextG pointWithNum:0];
                ne = [nextG pointWithNum:MAXINT];
                distance = SqrDistPoints(ce, ns);
                if (Diff(distance, 0.0) <= TOLERANCE && ![nextG isSelected])
                {
                    break; // graphics laying correct - with break curG is allways last not selected graphic
                }
                else if ([nextG isSelected]) // collect possibleS - START searching
                {   int         selectedGs = 0;
                    VGraphic	*ngp1, *ngp2;
                    int         possCnt = 4, possibleSi[4], possibleEi[4];
                    NSPoint     possibleS[4], possibleE[4];
                    NSPoint     nsp1, nsp2, nsm1 = [curG pointWithNum:0];
                    double      sqrTolTen = (10.0*TOLERANCE)*(10.0*TOLERANCE);

                    /* check distance around - one/two graphics behind selected graphic(s) */
                    ngp1 = [[sp list] objectAtIndex:(((k+1) < spCnt) ? (k+1):(0))];
                    nsp1 = [ngp1 pointWithNum:0];
                    ngp2 = [[sp list] objectAtIndex:(((k+2) < spCnt) ? (k+2) : ((k+2) - spCnt))];
                    nsp2 = [ngp2 pointWithNum:0];

                    possibleS[0] = nsm1; possibleSi[0] = ((k-1) < 0)?(spCnt-1):(k-1); // nextG-1 start (curG)
                    possibleS[1] = ns; possibleSi[1] = k; // nextG start
                    possibleS[2] = nsp1; possibleSi[2] = ((k+1) < spCnt) ? (k+1) : (0); // nextG+1 start
                    possibleS[3] = nsp2; possibleSi[3] = ((k+2) < spCnt) ? (k+2) : (0); // nextG+2 start

                    /* search for an endpoint to possibleS - SEARCH */
                    for (l=((k+1 < spCnt) ? (k+1):0); l < ((k+1 < spCnt) ? spCnt:k); l++)
                    {   VGraphic	*lg = [[sp list] objectAtIndex:l];
                        NSPoint		s, e;
                        int         r, from = -1, to = -1;

                        s = [lg pointWithNum:0];
                        e = [lg pointWithNum:MAXINT];

                        /* lg close to curG end !! - loop - only one graphic between selected graphics ? */
                        if ( ![lg isSelected] && Diff(SqrDistPoints(ce, s), 0.0) <= TOLERANCE )
                        {   int	from = k; // nextG
                            int	to = ((l-1) < 0)?(spCnt-1):(l-1); // l-1

                            /* remove objects from k-(l-1) */
                            for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                            {
                                [[sp list] removeObjectAtIndex:m];
                                spCnt--;
                                if (m < from) { from--; to--; }
                                if (m < j) j--; // we removed befor j -> j and k and l move one down in list !!!
                                if (m < startJ) startJ--;

                                if (!m && to < from) // we step over 0 - second part until from !
                                {   m = spCnt;
                                    to = from+1; // little hack mh - second part until from !
                                }
                            }
                            break;
                        }
                        /* lg is selected OR not -  hit possibleS Array - loop */
                        // else if ( [lg isSelected] )
                    
                        /* s of lg inside possibleS Array */
                        for (r=0; r<possCnt; r++)
                        {
                            if ( SqrDistPoints(s, possibleS[r]) < sqrTolTen &&
                                Diff(l, possibleSi[r]) > 1 && !(l == 0 && possibleSi[r] == spCnt-1)
                                && !(l == spCnt-1 && possibleSi[r] == 0) )
                            {
                                to = ((l-1) < 0)?(spCnt-1):(l-1); // we need lg
                                from = possibleSi[r];
                                /* if ( j > k ) // wrong !
                                {   from = l;
                                    to = possibleSi[r];
                                }*/
                                break;
                            }
                        }
                        if (to != -1)
                        {
                            /* remove objects from from to to */
                            for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                            {
                                [[sp list] removeObjectAtIndex:m];
                                spCnt--;
                                if (m < from) { from--; to--; }
                                if (m < j) j--; // we removed befor j -> j and k and l move one down in list !!!
                                if (m < startJ) startJ--;

                                if (!m && to < from) // we step over 0 - second part until from !
                                {   m = spCnt;
                                    to = from+1; // little hack mh - second part until from !
                                }
                            }
                            j--; // one back to be sure have a not selected Graphic
                            // or [lg setSelected:NO];
                            break;
                        }
                        /*
                         * lg do not close a loop
                         */
                        else if ([lg isSelected])
                        {   selectedGs++;
                            if (l+1 >= spCnt)
                                l = -1; // so we go on at 0
                            if (l == k)
                                break; // one time around !!!
                            continue;
                        }
                        /*
                         * nothing found until next not selected graphic
                         *
                         * search for loops which are need more tolerance to find
                         * and search for overlaps which build a new subpath
                         */
                        else if ( ![lg isSelected] )
                        {   VGraphic	*lgm1, *lgm2,*lgp1;
                            int         km2 = ((k-2) < 0) ? (spCnt+(k-2)) : (k-2);
                            int         kp3 = ((k+3) < spCnt) ? (k+3) : ((k+3) - spCnt);
                            BOOL        removeLoop = NO;
                            int         q, r, sStart = -1, notSelected=0;
                            BOOL        removed = NO;
                            NSPoint     em2, em1, ep1, sStartPt = {0.0, 0.0};
                            float       sqrTolTen = (10.0*TOLERANCE)*(10.0*TOLERANCE);

                            /* check distance around - one/two graphic above end of selected graphic(s) */
                            lgm2 = [[sp list] objectAtIndex:(((l-2) < 0) ? (spCnt+(l-2)):(l-2))];
                            em2 = [lgm2 pointWithNum:MAXINT];
                            lgm1 = [[sp list] objectAtIndex:(((l-1) < 0) ? (spCnt-1):(l-1))];
                            em1 = [lgm1 pointWithNum:MAXINT];
                            lgp1 = [[sp list] objectAtIndex:(((l+1) < spCnt) ? (l+1):(0))];
                            ep1 = [lgp1 pointWithNum:MAXINT];

                            possibleE[0] = em2; // lgm2 end
                            possibleEi[0] = ((l-2) < 0) ? (((l-2) == -1) ? (spCnt-1):(spCnt-2)) : (l-2);
                            possibleE[1] = em1; possibleEi[1] = ((l-1) < 0)?(spCnt-1):(l-1); // lgm1 end
                            possibleE[2] = e; possibleEi[2] = l; // lg end
                            possibleE[3] = ep1; possibleEi[3] = ((l+1) < spCnt) ? (l+1):(0); // lgp1 end

//lg, lgm1, lgm2 allready checked !?, but importand for overlaps !

#if 1
                            //if (selectedGs) // not only one selected graphic ! > 2 ?
                            {
                            /* check possibleS possibleE to each other ! */
                            for (q=0; q<possCnt; q++)
                            {
                                for (r=0; r<possCnt; r++)
                                {
                                    if ( SqrDistPoints(possibleS[q], possibleE[r]) < sqrTolTen &&
                                        Diff(possibleEi[r], possibleSi[q]) > 2 && !(possibleEi[r] == 0 && possibleSi[q] == spCnt-1)
                                        && !(possibleEi[r] == spCnt-1 && possibleSi[q] == 0) )
                                    {
                                        to = possibleEi[r];
                                        from = possibleSi[q];
                                        /* if ( j > k ) // wrong !
                                        {   from = possibleEi[r];
                                            to = possibleSi[q];
                                        }*/
                                        break;
                                    }
                                }
                                if (to != -1)
                                    break;
                            }
                            if (to != -1)
                            {
                                /* remove objects from to to */
                                for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                                {
                                    [[sp list] removeObjectAtIndex:m];
                                    spCnt--;
                                    if (m < from) { from--; to--; }
                                    if (m < j) j--; // we removed befor j -> j and k and l move one down in list !!!
                                    if (m < startJ) startJ--;
                                    
                                    if (!m && to < from) // we step over 0 - second part until from !
                                    {   m = spCnt;
                                        to = from+1; // little hack mh - second part until from !
                                    }
                                }
                                break;
                            }
                            }
#endif

if (!removed )
{   //int sStartEi = -1;

                            /* search for other graphics which hit possibleE/S - OVERLAPS */
//                            for (n=((l+1 < spCnt) ? (l+1):0); n < ((l+1 < spCnt) ? spCnt:k); n++)
                            for (n=((j-1 < 0) ? (spCnt-1):(j-1)); n >= 0; n--)
                            {   VGraphic	*nlG = [[sp list] objectAtIndex:n];
                                NSPoint     nls, nle;

//                                if (n == k)
                                if (n == l)
                                    break; // one round finished
                                nls = [nlG pointWithNum:0];
                                nle = [nlG pointWithNum:MAXINT];
                                /* nlg is selected and hit a point from possibleE array */
                                if ((sStart == -1 || notSelected > 2) && [nlG isSelected] &&
                                    (Diff(j, n) > 1 && Diff(Diff(j, n), spCnt) > 1) &&
                                    (Diff(l, n) > 1 && Diff(Diff(l, n), spCnt) > 1) &&
                                    pointWithToleranceInArray(nle, tol, possibleS, possCnt) )
// (                                    pointWithToleranceInArray(nls, tol, possibleE, possCnt) )
                                {
                                    /*for (q=0; q<possCnt; q++)
                                        if (SqrDistPoints(sStartPt, possibleE[q]) < tol)
                                        {   sStartEi = possibleEi[q];
                                            break;
                                        }*/

//                                    sStart = n; sStartPt = nls;
                                    sStart = n; sStartPt = nle;
                                    notSelected = 0; // second try perhaps
                                }
/* length */                    if (sStart != -1 && ![nlG isSelected] && SqrDistPoints(nls,nle) > 100.0*TOLERANCE)
                                    notSelected++; // too much not selected elements to remove ?
                                /* nlg is hit a point from possibleS array */
                                if (sStart != -1 /*&& notSelected < 3*/ &&
                                    (Diff(j, n) > 1 && Diff(Diff(j, n), spCnt) > 1) &&
/* 2 */                                    (Diff(l, n) > 1 && Diff(Diff(l, n), spCnt) > 1) &&
                                    Diff(SqrDistPoints(sStartPt, nls), 0.0) > TOLERANCE &&
                                    pointWithToleranceInArray(nls, tol, possibleE, possCnt) )
//(                                    Diff(SqrDistPoints(sStartPt, nle), 0.0) > TOLERANCE &&
//                                    pointWithToleranceInArray(nle, tol, possibleS, possCnt) )
                                {   VPath 	*subP = nil;
                                    int	q, sEnd1 = -1;

#if 0 // n++
                                    for (q=0; q<possCnt; q++)
                                        if (SqrDistPoints(sStartPt, possibleE[q]) < tol)
                                        {   to = possibleEi[q];
                                            sEnd1 = ((possibleEi[q]+1) < spCnt) ? (possibleEi[q]+1) : (0);
                                            break;
                                        }
                                    for (q=0; q<possCnt; q++)
                                        if (SqrDistPoints(nle, possibleS[q]) < tol)
                                        {   from = possibleSi[q];
                                            break;
                                        }
#endif
#if 1 // n--

                                    for (q=0; q<possCnt; q++)
                                        if (SqrDistPoints(nls, possibleE[q]) < tol)
                                        {   to = possibleEi[q];
                                            sEnd1 = ((possibleEi[q]+1) < spCnt) ? (possibleEi[q]+1) : (0);
                                            break;
                                        }
                                    for (q=0; q<possCnt; q++)
                                        if (SqrDistPoints(sStartPt, possibleS[q]) < tol)
                                        {   from = possibleSi[q];
                                            break;
                                        }
#endif
#if 0 // nearest macht fehler
{   double  dist=MAXCOORD, d;
                                    for (q=0; q<possCnt; q++)
                                        if ((d=SqrDistPoints(nls, possibleE[q])) < tol && d < dist)
                                        {   dist = d;
                                            to = possibleEi[q];
                                            sEnd1 = ((possibleEi[q]+1) < spCnt) ? (possibleEi[q]+1) : (0);
                                            //break;
                                        }
                                    dist=MAXCOORD;
                                    for (q=0; q<possCnt; q++)
                                        if ((d=SqrDistPoints(sStartPt, possibleS[q])) < tol && d < dist)
                                        {   dist = d;
                                            from = possibleSi[q];
                                            //break;
                                        }
}
#endif

                                    if (from == -1 || to == -1)
                                        break;
                                    removed = YES;
                                    /* remove first part of selected graphics */
                                    for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                                    {
                                        [[sp list] removeObjectAtIndex:m];
                                        spCnt--;
                                        /* we removed befor j -> j move one down in list !!! */
                                        if (m < from) { from--; to--; }
                                        if (m < j) j--;
                                        if (m < startJ) startJ--;
                                        if (m < n) n--;
                                        if (m < sStart) sStart--;
                                        if (m < sEnd1) sEnd1--;

                                        if (!m && to < from) // we step over 0 - second part until from !
                                        {   m = spCnt;
                                            to = from+1; // little hack mh - second part until from !
                                        }
                                    }
                                    /* than we build a new subPath and add other graphics to this
                                     * so we can remove the rest of selected graphics later in i loop
                                     */
                                    if (notSelected >= 1) // 3
                                    {   subP = [VPath path];
                                        [subP setColor:[sp color]];
                                        [subP setWidth:[sp width]];
                                        [subP setFilled:[sp filled]];
                                    }
//                                    from = sStart; // first second selected Graphic
//                                    to = n;
                                    from = n; // first second selected Graphic - backsearch
                                    to = sStart;
                                    for (m=to; m >= ((!to || to < from) ? 0:from) && spCnt > m; m--)
                                    {   VGraphic	*g = [[sp list] objectAtIndex:m];

                                        if (notSelected >= 1) // 3
                                            [[subP list] insertObject:g atIndex:0]; // backwart !
                                        [[sp list] removeObjectAtIndex:m];
                                        spCnt--;
                                        if (m < from) { from--; to--; }
                                        if (m < j) j--;
                                        if (m < startJ) startJ--;
//                                        if (m < sStart) sStart--;
                                        if (m < n) n--;
                                        if (m < sEnd1) sEnd1--;

                                        if (!m && to < from) // we step over 0 - second part until from !
                                        {   m = spCnt;
                                            to = from+1; // little hack mh - second part until from !
                                        }
                                    }
                                    if (notSelected >= 1) // 3
                                    {   [[path list] addObject:subP];
                                        if ( listCnt+1 > subPathCnt )
                                            *subPathSplitted = NSZoneRealloc((NSZone*)[(NSObject*)NSApp zone], *subPathSplitted, (subPathCnt+=5) * sizeof(BOOL));
                                        (*subPathSplitted)[listCnt] = YES;
                                        listCnt++;
                                    }
                                    /* sort graphics behind/after overlap (overlap allways create two supPaths)
                                     * in a new subPath */
                                    subP = [VPath path];
                                    [subP setColor:[sp color]];
                                    [subP setWidth:[sp width]];
                                    [subP setFilled:[sp filled]];
                                    from = sEnd1;
//                                    to = ((sStart-1) < 0) ? (spCnt-1):(sStart-1); // bevor second selection
                                    to = ((n-1) < 0) ? (spCnt-1):(n-1); // bevor second selection
                                    for (m=to; m >= ((!to || to < from) ? 0:from) && spCnt > m; m--)
                                    {   VGraphic	*g = [[sp list] objectAtIndex:m];

                                        [[subP list] insertObject:g atIndex:0]; // backwart !
                                        [[sp list] removeObjectAtIndex:m]; // remove from cur sp
                                        spCnt--;
                                        if (m < from) { from--; to--; }
                                        if (m < j) j--;
                                        if (m < startJ) startJ--;
                                        if (!m && to < from) // we step over 0 - second part until from !
                                        {   m = spCnt;
                                            to = from+1; // little hack mh - second part until from !
                                        }
                                    }
                                    [[path list] addObject:subP];
                                    if ( listCnt+1 > subPathCnt )
                                        *subPathSplitted = NSZoneRealloc((NSZone*)[(NSObject*)NSApp zone], *subPathSplitted, (subPathCnt+=5) * sizeof(BOOL));
                                    (*subPathSplitted)[listCnt] = YES;
                                    listCnt++;
                                    j--; // check from curG new !!
                                    break;
                                }
//                                if (n+1 >= spCnt)
//                                    n = -1; // so we go on at 0
                                if (n-1 < 0)
                                    n = spCnt; // so we go on at spCnt-1
                            } // n loop - overlaps
}
                            if (removed)
                                break;

                            km2 = ((k-2) < 0) ? (spCnt+(k-2)) : (k-2);
                            kp3 = ((k+6) < spCnt) ? (k+6) : ((k+6) - spCnt);

                            /* now (no overlap) we search for a loop
                             * which start/end points not exactly at notSelected/selected frontiers
                             * possibleS Part - from inside selected Graphics (k+x) until k-3
                             * possibleE Part - from inside selected Graphics (l-x) until l+3
                             */

                            /*if (spCnt < selectedGs+8) // correct km2
                            {
                                if (spCnt < selectedGs+3)
                                    km2 = k; // none back
                                else if (spCnt < selectedGs+5)
                                    km2 = j; // one back
                                else //  < ..+7
                                    km2 = ((k-2) < 0) ? (spCnt+(k-2)) : (k-2); // two back
                            }*/

                            if (selectedGs < 7) // correct kp3
                            {
                                if (selectedGs < 3)
                                    kp3 = k; // none forward
                                else if (selectedGs < 3) // 3
                                    kp3 = ((k+1) < spCnt) ? (k+1) : ((k+1) - spCnt); // one forward
                                else  if (selectedGs < 4)
                                    kp3 = ((k+2) < spCnt) ? (k+2) : ((k+2) - spCnt); // two forward
                                else  if (selectedGs < 5)
                                    kp3 = ((k+3) < spCnt) ? (k+3) : ((k+3) - spCnt); // three forward
                                else  if (selectedGs < 6)
                                    kp3 = ((k+4) < spCnt) ? (k+4) : ((k+4) - spCnt); // four forward
                                else  //if (selectedGs < 7)
                                    kp3 = ((k+5) < spCnt) ? (k+5) : ((k+5) - spCnt); // five forward
                            }

                            for (n=kp3; n >= ((kp3 < km2) ? 0 : km2); n--)
                            {   VGraphic	*gn = [[sp list] objectAtIndex:n]; // --
                                NSPoint		gns = [gn pointWithNum:0];
                                int		o, lp1 = ((l+1) < spCnt) ? (l+1) : ((l+1) - spCnt);
//                                int		lm3 = ((n+1) < spCnt) ? (n+1) : ((n+1) - spCnt);
                                int		lm3 = ((n+2) < spCnt) ? (n+2) : ((n+2) - spCnt);
/*
                                if (selectedGs < 12) // correct lm3
                                {
                                    if (selectedGs < 6)
                                        lm3 = l; // none backward
                                    else if (selectedGs < 7)
                                        lm3 = (((l-1) < 0) ? (spCnt+(l-1)) : (l-1)); // one backward
                                    else if (selectedGs < 8)
                                        lm3 = (((l-2) < 0) ? (spCnt+(l-2)) : (l-2)); // two backward
                                    else if (selectedGs < 9)
                                        lm3 = (((l-3) < 0) ? (spCnt+(l-3)) : (l-3)); // three backward
                                    else if (selectedGs < 10)
                                        lm3 = (((l-4) < 0) ? (spCnt+(l-4)) : (l-4)); // four backward
                                    else if (selectedGs < 11)
                                        lm3 = (((l-5) < 0) ? (spCnt+(l-5)) : (l-5)); // five backward
                                    else // if (selectedGs < 12)
                                        lm3 = (((l-65) < 0) ? (spCnt+(l-6)) : (l-6)); // six backward
                                }
*/
                                if (n == (((j-1) < 0)?(spCnt-1):(j-1)) ||
                                    n == (((j-2) < 0) ? (spCnt+(j-2)) : (j-2)))
                                    lm3 = k; // else perhaps we remove only bevor j !!

                                /*if (spCnt < selectedGs+8) // correct km2 / lp1
                                {
                                    if (spCnt < selectedGs+3)
                                        lp1 = ((l-1) < 0) ? (spCnt+(l-1)) : (l-1); // none forward
                                    else if (spCnt < selectedGs+5)
                                        lp1 = l; // one forward
                                    else //  < ..+7
                                        lp1 = ((l+1) < spCnt) ? (l+1) : ((l+1) - spCnt); // two forward
                                }*/

                                for (o=lm3; o <= ((lm3 <= lp1) ? lp1 : spCnt-1); o++)
                                {   VGraphic	*go = [[sp list] objectAtIndex:(o = (o < spCnt) ? o : 0)]; // ++
                                    NSPoint	goe = [go pointWithNum:MAXINT];

                                    /* mal braucht man >= 1 und mal > 1 ? o > n sonst wird alles removed ! */
                                    if (((Diff(n, o) > 1 || (Diff(n, o) == 1 && o > n)) &&
                                         Diff(Diff(n, o), spCnt) > 1)
                                        && SqrDistPoints(gns, goe) < (15.0*TOLERANCE)*(15.0*TOLERANCE))
                                    {
                                        if ( Diff(n, o) == 1 )
                                            NSLog(@"VPath.m: Diff(n, o) == 1, look here if calculation fault\n");
                                        from = n;
                                        to = o;
                                        /* remove objects from k-(l-1) */
                                        for (m=to; m >= ((!to || to < from) ? 0:from); m--)
                                        {
                                            [[sp list] removeObjectAtIndex:m];
                                            spCnt--;
                                            if (m < from) { from--; to--; }
                                            if (m < j) j--;
                                            if (m < startJ) startJ--;

                                            if (!m && to < from) // we step over 0 - second part until from !
                                            {   m = spCnt;
                                                to = from+1; // little hack mh - second part until from !
                                            }
                                        }
                                        removeLoop = YES;
                                        break;
                                    }
                                    if (o == spCnt-1 && lm3 > lp1) // ++
                                    {   o = -1;
                                        lm3 = lp1-1; // hack to stop at lp1 - after spCnt
                                    }
                                } // oloop
                                if (removeLoop)
                                    break;
                                if (!n && kp3 < km2) // --
                                {   n = spCnt;
                                    kp3 = km2+1; // hack to go on after 0 at kp3
                                }
                            }
                            break;
                        }
                    } // l loop
                    break;
                }
                else if (Diff(distance, 0.0) > TOLERANCE)
                {
                    if ( !openPath )
                    {   noticeK = k;
                        noticeJ = j;
                        openPath = YES;
                    }
                    break; // break, instead continue ! go on !
                }
            } // k loop
        } // j loop
    }
    if (openPath)
        NSLog(@"VPath.m - optimizeSubPathsToClosedPath j:%d k:%d", noticeJ, noticeK);
    openPath = NO;

    /* check if closed and close little gaps */
    for (i=0; i<listCnt; i++)
    {	VPath	*sp = [[path list] objectAtIndex:i];
        int	j, spCnt = [[sp list] count];

        /* check end to next start */
        for (j=0; j<spCnt; j++)
        {   VGraphic	*curG = nil, *nextG = nil;
            NSPoint	e, ns;
            float	dist;

            if (j == spCnt-1) // last object !!!!!!!
            {   curG = [[sp list] objectAtIndex:j];
                nextG = [[sp list] objectAtIndex:0]; // startG
            }
            else
            {   curG = [[sp list] objectAtIndex:j];
                nextG = [[sp list] objectAtIndex:j+1];
            }
            //s = [curG pointWithNum:0];
            e = [curG pointWithNum:MAXINT];
            ns = [nextG pointWithNum:0];
            dist = SqrDistPoints(e, ns);

            if (dist > TOLERANCE*TOLERANCE && dist < 5.0*TOLERANCE)
            {
                if (![nextG isKindOfClass:[VArc class]])
                {
                    [nextG movePoint:0 to:e];
                }
                else if (![curG isKindOfClass:[VArc class]])
                {
                    [curG movePoint:MAXINT to:ns];
                }
                else
                {   id	g = [VLine lineWithPoints:e :ns];

                    [[sp list] insertObject:g atIndex:j+1];
                    spCnt++;
                }
            }
            else if (dist > TOLERANCE*TOLERANCE && dist < 50*TOLERANCE)
            {   id	g = [VLine lineWithPoints:e :ns];

                [[sp list] insertObject:g atIndex:j+1];
                spCnt++;
            }
            /* 1 -> dublicate to close path ! */
            else if (dist > TOLERANCE*TOLERANCE && j == spCnt-1 && spCnt == 1) // only one Object -> no 360 arc
            {   VGraphic	*gr = [curG copy];

                [gr changeDirection];
                [[sp list] addObject:gr];
                spCnt++;
            }
            else if (dist > TOLERANCE*TOLERANCE && !openPath)
            {   int k, notSelectedGs = 0;

                /* check for notSelected with length check !*/
                for (k=0; k<spCnt; k++)
                {   VGraphic	*curG = [[sp list] objectAtIndex:k];
                    NSPoint     s, e;

                    s = [curG pointWithNum:0];
                    e = [curG pointWithNum:MAXINT];

                    if (![curG isSelected] && SqrDistPoints(s, e) > 100.0*TOLERANCE )
                    {   notSelectedGs++;
//                        if ( notSelectedGs > 2 )
//                            break;
                    }
                }
                if (notSelectedGs < 6 && (float)notSelectedGs/(float)spCnt < 0.1) // remove sp
                {   [[sp list] removeAllObjects];
                    break;
                }
                openPath = YES;
                noticeJ = j;
                noticeK = i;
            }
        }
    }
    if ( openPath )
        NSLog(@"VPath - optimizeSubPathsToClosedPath -- i: %d j: %d", noticeK, noticeJ);

    if ( subPathCnt != oldSubPathCnt )
    {   NSZoneFree((NSZone*)[(NSObject*)NSApp zone], *subPathSplitted);
        *subPathSplitted = NULL;
    }
}

/* here we split graphics which intersect each other
 * inside subPaths itself
 * and subPath to subPaths
 * AND we set graphics which start/middle/end point is laying too near to hold the distance of tool width
 */
- (void)removeFaultGraphicsInSubpaths:(VPath*)path :(float)w
{   int     i, listCnt;
    int     subPathCnt = [[path list] count] + Max(5, [[path list] count]);
    BOOL    *subPathSplitted = NULL;
    float   r;

    subPathSplitted = NSZoneMalloc((NSZone*)[(NSObject*)NSApp zone], subPathCnt * sizeof(BOOL));

    /* we need more subPathSplitted[] for possible additions in - optimizeSubPathsToClosedPath */

    r = Abs((width + w) / 2.0);	// the amount of growth
    // r -= Min(0.05, r/50.0); // 0.05 60.0 - 0.1 35.0 - 0.1 25.0
    r -= 0.0094; // 0.0075 0.0055 // Min(0.0055, r/100.0); // 0.01 r/100.0 - 0.005 is ArcArc tangentintersection !!
//r -= 0.005;

    /* split each sub path itself
     */
    for ( i=0, listCnt = [[path list] count]; i<listCnt; i++ )
    {	VPath	*sp = [[path list] objectAtIndex:i];
        int     j, k, l, interCnt, spCnt = [[sp list] count];

        /* intersect and tile elements of subpath
         */
        for ( j=0; j<spCnt; j++ )
        {   VGraphic	*gJ = [[sp list] objectAtIndex:j];
            NSRect	jBounds = [gJ coordBounds];
            BOOL	splitted = NO;

            for ( k=j+1; k<spCnt; k++ )
            {   VGraphic	*gK = [[sp list] objectAtIndex:k];
                NSPoint		*interPts;
                NSRect		kBounds = [gJ coordBounds];

                if (j == k || /*((j+1 < spCnt) ? (j+1) : (0)) == k || (((j-1) < 0) ? (spCnt-1):(j-1)) == k ||*/
                    !vhfIntersectsRect(jBounds, kBounds))
                    continue;

                /* intersect graphics */
                if ( (interCnt = [gJ getIntersections:&interPts with:gK]) )
                {   NSMutableArray	*splitListJ=nil, *splitListK=nil;

                    /* tile graphics */
                    splitListJ = [gJ getListOfObjectsSplittedFrom:interPts :interCnt];
                    splitListK = [gK getListOfObjectsSplittedFrom:interPts :interCnt];

                    /* insert tiled graphics */
                    if ( [splitListJ count] > 1 )
                    {
                        splitted = YES;
                        for (l=[splitListJ count]-1; l>=0; l--)
                        {   VGraphic	*g = [splitListJ objectAtIndex:l];

                            [[sp list] insertObject:g atIndex:j+1];
                            spCnt++;
                            if (k > j)
                                k++;
                        }
                        [[sp list] removeObjectAtIndex:j];
                        spCnt--;
                        if (k > j)
                            k--;
                        j--;
                    }
                    if ( [splitListK count] > 1 )
                    {
//                        splitted = YES; // gJ perhaps not splitted - but later !!!
                        for (l=[splitListK count]-1; l>=0; l--)
                        {   VGraphic	*g = [splitListK objectAtIndex:l];

                            [[sp list] insertObject:g atIndex:k+1];
                            spCnt++;
                            //if (j > k) // not possible if k = j+1
                            //    j++;
                        }
                        [[sp list] removeObjectAtIndex:k];
                        spCnt--;
                        //if (j > k)
                        //    j--;
                    }
                    free(interPts);
                    if (splitted)
                        break;
                }
            }
        }

    }

    /* split subpaths from each other !!!
     */
    listCnt = [[path list] count];
    for ( i=0; i<listCnt; i++ )
        subPathSplitted[i] = NO; // initialize !

    for ( i=0; i<listCnt; i++ )
    {	VPath	*sp = [[path list] objectAtIndex:i];
        int     j, c, o, l, spCnt = [[sp list] count], splittedPath = NO, oSpCnt=0;

        for ( j=i+1; j<listCnt; j++ )
        {   VPath	*oSp;
            BOOL	oSplittedPath = NO;

            if ( j==i )
                continue;	/* not the same path ! */

            oSp = [[path list] objectAtIndex:j];	/* other subpath */
            oSpCnt = [[oSp list] count];

            /* intersect and tile elements of subpath -> with otherPaths */
            for ( c=0; c<spCnt; c++ )
            {   VGraphic	*gC = [[sp list] objectAtIndex:c];
                NSRect		cBounds = [gC coordBounds];

                for ( o=0; o<oSpCnt; o++ )
                {   VGraphic	*gO = [[oSp list] objectAtIndex:o];
                    NSPoint	*interPts;
                    NSRect	oBounds = [gO coordBounds];
                    int		interCnt;
                    BOOL	splitted = NO;

                    if (!vhfIntersectsRect(cBounds, oBounds))
                        continue;

                    /* intersect graphics */
                    if ( (interCnt = [gC getIntersections:&interPts with:gO]) )
                    {   NSMutableArray	*splitListC=nil, *splitListO=nil;

                        /* tile graphics */
                        splitListC = [gC getListOfObjectsSplittedFrom:interPts :interCnt];
                        splitListO = [gO getListOfObjectsSplittedFrom:interPts :interCnt];

                        /* insert tiled graphics */
                        if ( [splitListC count] > 1 )
                        {
                            splitted = YES;
                            splittedPath = YES;
                            for (l=[splitListC count]-1; l>=0; l--)
                            {   VGraphic	*g = [splitListC objectAtIndex:l];

                                [[sp list] insertObject:g atIndex:c+1];
                                spCnt++;
                            }
                            [[sp list] removeObjectAtIndex:c];
                            spCnt--;
                            gC = [[sp list] objectAtIndex:c];
                            cBounds = [gC coordBounds];
                        }
                        if ( [splitListO count] > 1 )
                        {
                            splitted = YES;
                            oSplittedPath = YES;
                            for (l=[splitListO count]-1; l>=0; l--)
                            {   VGraphic	*g = [splitListO objectAtIndex:l];

                                [[oSp list] insertObject:g atIndex:o+1];
                                oSpCnt++;
                            }
                            [[oSp list] removeObjectAtIndex:o];
                            oSpCnt--;
                        }
                        free(interPts);
                        if (splitted)
                            o = -1; // start at 0 ! for new current c graphics
                    }
                }
            }
            if (oSplittedPath && subPathSplitted[j] == NO)
                subPathSplitted[j] = YES; // perhaps allready set and not splitted any more ! ?
        }
        if (splittedPath && subPathSplitted[i] == NO) // perhaps allready set and not splitted any more ! ?
            subPathSplitted[i] = YES;
    }

    /* set objects selected - which distance is too small to original path (self) */
    for ( i=0, listCnt = [[path list] count]; i<listCnt; i++ )
    {	VPath	*sp = [[path list] objectAtIndex:i];
        int	j, spCnt = [[sp list] count];

        spCnt = [[sp list] count];
        for ( j=0; j<spCnt; j++ )
        {   VGraphic	*g = [[sp list] objectAtIndex:j];
            NSPoint	s, e, m, sa;
            VArc	*arc1 = [VArc arc], *arc2 = [VArc arc], *arc3 = [VArc arc];

/*            if ([g isSelected])
{
//                [[sp list] removeObjectAtIndex:j]; // debugging purpose only
                continue;
}*/
            [g getPoint:&m at:0.4];
            s = [g pointWithNum:0];
            e = [g pointWithNum:MAXINT];
            sa = s; sa.x += r;
            [arc1 setCenter:s start:sa angle:360.0];
            sa = e; sa.x += r;
            [arc2 setCenter:e start:sa angle:360.0];
            sa = m; sa.x += r;
            [arc3 setCenter:m start:sa angle:360.0];

            /* graphic nearer than r to original path (self) */
            if ( /*SqrDistPoints(s, e) < 0.001 ||*/
                 ![arc1 tangentIntersectionWithPath:self] || ![arc2 tangentIntersectionWithPath:self] ||
                 ![arc3 tangentIntersectionWithPath:self] || (w < 0 && !width && ![self isPointInside:m]) ||
                 (w > 0 && [self isPointInside:m]) )
            {
//                [[sp list] removeObjectAtIndex:j]; // debugging purpose only
                [g setSelected:YES];
            }
            else
                [g setSelected:NO];
        }
    }

    /* optimize to close path */
    [self optimizeSubPathsToClosedPath:path :w :&subPathSplitted :subPathCnt];
    if ( (subPathSplitted) )
        NSZoneFree((NSZone*)[(NSObject*)NSApp zone], subPathSplitted);
}

/* return a path representing the outline of us
 * the path holds two lines and two arcs
 * if we need not build a contour a copy of self is returned
 */
#define AngleNotSmallEnough(dir, w, angle) ((dir && w >= 0 && angle > 150.0) || (dir  && w <  0 && angle < 210.0) || \
                                           (!dir && w <  0 && angle > 150.0) || (!dir && w >= 0 && angle < 210.0))
#define NeedArc(dir, w, angle)	((dir && w >= 0 && angle > 180.5) || (dir  && w <  0 && angle < 179.5) || \
                                (!dir && w <  0 && angle > 180.5) || (!dir && w >= 0 && angle < 179.5))
/*#define SmallAngle(dir, w, angle )	((dir && w > 0 && angle < 89.5) || (dir && w < 0 && angle > 270.5) || \
    (!dir && w < 0 && angle < 89.5) || (!dir && w > 0 && angle > 270.5))*/
/*#define SmallAngle(dir, w, angle )	((dir && w > 0 && angle < 85.5) || (dir && w < 0 && angle > 275.5) || \
    (!dir && w < 0 && angle < 85.5) || (!dir && w > 0 && angle > 275.5))*/
#define SmallAngle(dir, w, angle )	((dir && w >= 0 && angle < 95.5) || (dir  && w <  0 && angle > 265.5) || \
                                    (!dir && w <  0 && angle < 95.5) || (!dir && w >= 0 && angle > 265.5))
/*#define SmallAngle(dir, w, angle )	((dir && w > 0 && angle < 120.0) || (dir && w < 0 && angle > 240.0) || \
    (!dir && w < 0 && angle < 120.0) || (!dir && w > 0 && angle > 240.0))*/
/* created:  1997-07-07
 * modified: 1997-07-07
 * get gradient
 * if a curve has several vertices in one point (gradient = 0, 0) we take the next vertice to get the gradient
 */
//#define GradientNear(g, t) ([g isKindOfClass:[VCurve class]]) ? [g gradientNear:t] : [g gradientAt:t]

static NSPoint orthPointAtBegOrEnd(id g, VFloat r, int dirInd, BOOL end)
{   VFloat	b;
    NSPoint	p, grad, orthP;

    if ( !end )	/* calc to beg */
    {
        p = [g pointWithNum:0];             /* start point of object */
        grad = GradientNear(g, 0.0);		/* gradient of start-point for outline object */
    }
    else
    {   p = [g pointWithNum:MAXINT];		/* end point of object */
        grad = GradientNear(g, 1.0);		/* gradient of start-point for outline object */
    }
    if ( !(b = sqrt(grad.x*grad.x+grad.y*grad.y)) )
        orthP = p;
    else
    {   orthP.x = p.x + grad.y*r*dirInd/b;
        orthP.y = p.y - grad.x*r*dirInd/b;
    }
    return orthP;
}

static float angleBetweenGraphicsInStartOrEnd(id g1, id g2, BOOL end)
{   NSPoint	p, t1End, t2End, gradB, gradA;

    if ( !end )	/* calc to beg */
    {
        p = [g1 pointWithNum:0];			/* start point of object */
        gradB = GradientNear(g1, 0.0);			/* gradient of start-point object */
        gradA = GradientNear(g2, 1.0);			/* gradient of end-point for object */
    }
    else
    {   p = [g1 pointWithNum:MAXINT];			/* end point of object */
        gradA = GradientNear(g1, 1.0);			/* gradient of start-point for outline object */
        gradB = GradientNear(g2, 0.0);			/* gradient of end-point for prev object */
    }
    t1End.x = p.x - gradA.x;
    t1End.y = p.y - gradA.y;
    t2End.x = p.x + gradB.x;
    t2End.y = p.y + gradB.y;
    return vhfAngleBetweenPoints(t1End, p, t2End);	/* get angle (ccw) on right side */
}

static NSPoint parallelPointbetweenObjects(id g1, id g2, float angle, float r, int dirInd, BOOL end)
{   NSPoint	p, gradA, gradB, pG, newP;
    double	a, b, c, nr, na;

    /* get gradients to calc start and end points of outline
     */
    if ( !end )
    {
        p = [g1 pointWithNum:0];
        gradB = GradientNear(g1, 0.0);			/* gradient of start-point for outline object */
        gradA = GradientNear(g2, 1.0);			/* gradient of end-point for prev object */
    }
    else
    {   p = [g1 pointWithNum:MAXINT];
        gradA = GradientNear(g1, 1.0);			/* gradient of start-point for outline object */
        gradB = GradientNear(g2, 0.0);			/* gradient of end-point for prev object */
    }
    a = sqrt(gradA.x*gradA.x+gradA.y*gradA.y);
    b = sqrt(gradB.x*gradB.x+gradB.y*gradB.y);	/* our gradient is orthogonal to the average of both gradients */
    pG.x = gradA.y/a + gradB.y/b;
    pG.y = -(gradA.x/a + gradB.x/b);
    if ( !pG.x && !pG.y )
    {	pG.x = - gradA.y/a;
        pG.y = + gradA.x/a;
    }
    c = sqrt(pG.x*pG.x+pG.y*pG.y);	// end point for outline object
    ( angle < 360.0-angle ) ? (na = angle/2.0) : (na = (360.0-angle)/2.0);
    nr = r / Sin(na);			// need correct distance
    newP.x = p.x + pG.x*nr*dirInd/c;
    newP.y = p.y + pG.y*nr*dirInd/c;
    return newP;
}

- (id)contour:(float)w useRaster:(BOOL)useRaster
{
    if ( [self filled] )
        return (useRaster) ? [self contourWithPixel:w]
                           : [self contour:w inlay:NO splitCurves:YES];
    else
        return [self contourOpen:w];
}
- (id)contour:(float)w
{
    if ( [self filled] )
        return [self contour:w inlay:NO splitCurves:YES];
    else
        return [self contourOpen:w];
}
- (id)contour:(float)w inlay:(BOOL)inlay splitCurves:(BOOL)splitCurves useRaster:(BOOL)useRaster
{
    return (useRaster) ? [self contourWithPixel:w]
                       : [self contour:w inlay:inlay splitCurves:splitCurves];
}
- (id)contour:(float)w inlay:(BOOL)inlay splitCurves:(BOOL)splitCurves
{   VPath	*path, *subPath = nil, *pathCopy = nil;
    //VLine   *line = [VLine new], *linePrev = [VLine new], *lineNext = [VLine new]; // to replace Curve if necessarie
    VLine   *line = nil, *linePrev = nil, *lineNext = nil; // to replace Curve if necessarie
    int		i, listCnt = [list count], begIx=0, endIx=0, dir=0;
    int		direction, inside, directionArray[listCnt], insideArray[listCnt], dirInsideCnt=0;
    VFloat	r, dirInd=1.0, bAngle, eAngle, len = 0;
    int		cnt=0;
    NSPoint sGap = NSZeroPoint;

    NSAutoreleasePool   *pool;

    /* we just return a copy */
    if ( (!filled && Abs(w)>width) || (Diff(w, 0.0) < 0.0001 && Diff(width, 0.0) < 0.0001)
         || (w<0.0 && Abs(w) == width) )
        return [[self copy] autorelease];

    //if ( Prefs_UseRaster )  // FIXME: use version with useRaster flag in parameter!
    //    return [self contourWithPixel:w];

    pathCopy = [[self copy] autorelease];
    if (inlay)
    {   VPath	*oPath;

        /* gegenrichtung contour mit w bilden */
        oPath = [pathCopy contour:-w inlay:NO splitCurves:YES]; // YES zwingend hier
        [oPath setFilled:YES optimize:NO];
        path = [oPath contour:2.0*w inlay:NO splitCurves:YES]; // YES auch hier zwingend
        return path;
    }

    r = (w + width) / 2.0;	// the amount of growth

    path = [VPath path];
    [path setColor:color];
    [path setDirectionCCW:isDirectionCCW];

    pool = [NSAutoreleasePool new];
    line = [VLine line]; linePrev = [VLine line]; lineNext = [VLine line];

    /* remove Elements with no length
     * the problem is that we destroy our closed path!
     */
    len = 0; sGap = NSZeroPoint;
    for ( i=0, listCnt = [[pathCopy list] count]; i<listCnt; i++ )
    {	VGraphic	*gThis = [[pathCopy list] objectAtIndex:i];
        NSPoint     p0, p1, p2, p3;
        double      le;

        if ([gThis isKindOfClass:[VCurve class]])
            [(VCurve*)gThis getVertices:&p0 :&p1 :&p2 :&p3];

        if ( (le=[gThis length]) < 15.0*TOLERANCE ||
             ( [gThis isKindOfClass:[VCurve class]] && SqrDistPoints(p0, p1) < 10*TOLERANCE &&
               SqrDistPoints(p2, p3) < 10*TOLERANCE && (le=SqrDistPoints(p0, p3)) < TOLERANCE) )
        {
            len += le;
            if (!sGap.x && !sGap.y && le)
                sGap = [gThis pointWithNum:0];
            [[pathCopy list] removeObject:gThis];
            i--;
            //[self closePath];
            listCnt = [[pathCopy list] count];
            continue;
        }
        else
        {   if (sGap.x && sGap.y && len >= 15.0*TOLERANCE)
            {   VLine   *line = [VLine new];

                [line setVertices:sGap :[gThis pointWithNum:0]];
                [[pathCopy list] insertObject:line atIndex:i];
                i++;
                listCnt = [[pathCopy list] count];
            }
            sGap = NSZeroPoint;
            len = 0;
        }
    }

    /* what we do here:
     * step through elements of path
     * calculate start, end points for outline-elements in a distance to path (inside/outside)
     * calculate parallel elements through start and end points
     * we have to calculate each sub path separately, so we put them in real sub paths
     */

    /* walk through path list
     */
    for ( i=0, listCnt = [[pathCopy list] count]; i<listCnt; i++ )
    {	VGraphic        *g,
                        *gThis, *gPrev, *gNext; /* this object, previous object, next object */
        NSPoint         begO = NSZeroPoint, endO = NSZeroPoint, /* start and endpoint of contour-object, if we dont add an arc (O = outline) */
                        begOrth, endOrth,       /* start and endpoint of contour-object, if we add an arc (orthogonal points) */
                        center;                 /* center point of arc if needed */
        int             sc, needArc = 0;        /* wether we need an arc to build correct contour around current edge */
        NSMutableArray  *splittedCurves = nil;

        gThis = [[pathCopy list] objectAtIndex:i];	// this object

        if ( [gThis isKindOfClass:[VCurve class]] )
        {   NSPoint p0, p1, p2, p3;

            [(VCurve*)gThis getVertices:&p0 :&p1 :&p2 :&p3];
            /* both Curve points are in its Start/End points - we build a line */
            if ( SqrDistPoints(p0, p1) < 10*TOLERANCE && SqrDistPoints(p2, p3) < 10*TOLERANCE )
            {
                [line setVertices:p0 :p3];
                gThis = line;
            }
        }

        /* new sub path
         */
        if ( !i || i>endIx )		// new sub path
        {   subPath = [VPath path];
            [[path list] addObject:subPath];
            begIx = i;
            //endIx = [pathCopy getLastObjectOfSubPath:begIx];
            endIx = [pathCopy getLastObjectOfSubPath:begIx tolerance:TOLERANCE]; //  tolerance:TOLERANCE

            cnt = 0;	// counter for cutIndex array

            /* only one element in subpath, so this must be an arc */
            if ( begIx == endIx )
            {	VGraphic    *arc;
                int         oldFillStyle=[gThis filled];

                if ( !([gThis isKindOfClass:[VArc class]] && Abs([(VArc*)gThis angle]) == 360.0) &&
                     ![gThis isKindOfClass:[VRectangle class]] &&
                     ![gThis isKindOfClass:[VPolyLine class]] )	// nothing
                {   insideArray[dirInsideCnt] = 0;
                    directionArray[dirInsideCnt++] = 0; /* doesnt matter */
                    continue;
                }
                [gThis setFilled:YES];
                if ( [pathCopy subPathInsidePath:begIx :endIx] )
                {
                    if ( [gThis width] ) // special
                    {   VArc	*gTh = [gThis copy];

                        [gTh setWidth:0.0];
                        [gTh setRadius:[gThis radius]-([gThis width]/2.0)];
                        arc = [gTh contour:-w];
                    }
                    else
                        arc = [gThis contour:-w];
                    insideArray[dirInsideCnt] = 1;
                }
                else
                {   arc = [gThis contour:w];
                    insideArray[dirInsideCnt] = 0;
                }
                directionArray[dirInsideCnt++] = 0; /* doesnt matter if only one object */
                //arc = ( [self subPathInsidePath:begIx :endIx] ) ? ([gThis contour:-w]) : ([gThis contour:w]);
                if ([arc isKindOfClass:[VPath class]])
                {   int	j, spCnt = [[(VPath*)arc list] count];

                    for (j=0; j<spCnt; j++)
                        [[subPath list] addObject:[[(VPath*)arc list] objectAtIndex:j]];
                }
                else if (arc)
                    [[subPath list] addObject:arc];
                [gThis setFilled:oldFillStyle];
                continue;
            }
            /* determine direction indicator inside(1), outside(-1) */
            direction = [pathCopy directionOfSubPath:begIx :endIx];	// 1 = ccw, 0 = cw
            if ( (inside = [pathCopy subPathInsidePath:begIx :endIx]) )
            	dir = ( direction ) ? 0 : 1;
            else
                dir = direction;
            dirInd  = ( dir ) ? 1.0 : -1.0;			// 1 = ccw, 0 = cw

            directionArray[dirInsideCnt] = direction;
            insideArray[dirInsideCnt++] = inside;
        }

        /* split curves for better results */
        if ( splitCurves && [(VGraphic*)gThis length] > 1000.0*TOLERANCE && [gThis isKindOfClass:[VCurve class]] )
        {   NSArray	*splittedCurves1 = nil, *splittedCurves2 = nil;
            NSArray	*splittedCurves3 = nil, *splittedCurves4 = nil;

            splittedCurves = [NSMutableArray arrayWithCapacity:5];
            splittedCurves1 = [(VCurve*)gThis splittedObjectsAt:0.333]; // 0.333 0.3

            splittedCurves2 = [[splittedCurves1 objectAtIndex:0] splittedObjectsAt:0.4]; // 0.2 0.4
            [splittedCurves addObject:[splittedCurves2 objectAtIndex:0]];
            [splittedCurves addObject:[splittedCurves2 objectAtIndex:1]];

            splittedCurves3 = [[splittedCurves1 objectAtIndex:1] splittedObjectsAt:0.5]; // 0.5 4/7
            [splittedCurves addObject:[splittedCurves3 objectAtIndex:0]];

            splittedCurves4 = [[splittedCurves3 objectAtIndex:1] splittedObjectsAt:0.6]; // 0.8 0.6
            [splittedCurves addObject:[splittedCurves4 objectAtIndex:0]];
            [splittedCurves addObject:[splittedCurves4 objectAtIndex:1]];
        }
        for ( sc=0; sc < ((splittedCurves) ? 5 : 1); sc++ )
        {   BOOL	/*calcBegOWithCut = 0, */calcEndOWithCut = 0;

            if ( splittedCurves )
                gThis = [splittedCurves objectAtIndex:sc];

            if ( sc >= 1 && sc <= 4 )   // 2012-01-19
                gPrev = [splittedCurves objectAtIndex:sc-1];
            else
            {
                gPrev = (i>begIx) ? [[pathCopy list] objectAtIndex:i-1] : [[pathCopy list] objectAtIndex:endIx];

                if ( [gPrev isKindOfClass:[VCurve class]] )
                {   NSPoint p0, p1, p2, p3;

                    [(VCurve*)gPrev getVertices:&p0 :&p1 :&p2 :&p3];
                    /* both Curve points are in its Start/End points - we build a line */
                    if ( SqrDistPoints(p0, p1) < 10*TOLERANCE && SqrDistPoints(p2, p3) < 10*TOLERANCE )
                    {
                        [linePrev setVertices:p0 :p3];
                        gPrev = linePrev;
                    }
                }
                if ( splitCurves && [(VGraphic*)gPrev length] > 1000.0*TOLERANCE &&
                     [gPrev isKindOfClass:[VCurve class]] )
                {   NSArray	*splittedCurvePrev = nil, *splittedC = nil;

                    splittedC = [(VCurve*)gPrev splittedObjectsAt:0.666]; // 0.666 4/7
                    if ( (splittedCurvePrev = [[splittedC objectAtIndex:1] splittedObjectsAt:0.6]) ) // 0.8 0.6
                        gPrev = [splittedCurvePrev objectAtIndex:1]; // the last of third parts of prev curve
                }
            }
            bAngle = angleBetweenGraphicsInStartOrEnd(gThis, gPrev, 0);
            begOrth = orthPointAtBegOrEnd(gThis, r, dirInd, 0);		/* beg orthogonal to beg of gThis */

            /* in this cases we need an arc between the graphics (added only at end points)
             * angle is greater than 180 at correction side
             */
            if ( NeedArc(dir, w, bAngle) )
                begO = begOrth;
/* so war es */
#if 0
            else if ( ([gThis isKindOfClass:[VLine class]] && [gPrev isKindOfClass:[VLine class]])
                     || AngleNotSmallEnough(dir, w, bAngle) )
                begO = parallelPointbetweenObjects(gThis, gPrev, bAngle, r, dirInd, 0);
            else
                calcBegOWithCut=1; // begO = parallelPointbetweenObjects(gThis, gPrev, bAngle, r, dirInd, 0);

            /* cut of prevG(parallel) with gThis(parallel) is begO
             */
            if ( calcBegOWithCut || SmallAngle(dir, w, bAngle) )
            {   VGraphic	*pG, *thG;
                NSPoint		bPrevOrth, ePrevOrth, *iPts = NULL;
                int         iCnt = 0;

                bPrevOrth = orthPointAtBegOrEnd(gPrev, r, dirInd, 0);
                ePrevOrth = orthPointAtBegOrEnd(gPrev, r, dirInd, 1);
                // get parallel object to gPrev and gThis
                pG = [gPrev parallelObject:bPrevOrth :ePrevOrth :bPrevOrth :ePrevOrth];
                endOrth = orthPointAtBegOrEnd(gThis, r, dirInd, 1);
                thG = [gThis parallelObject:begOrth :endOrth :begOrth :endOrth];

                if ( pG && thG && (iCnt = [pG getIntersections:&iPts with:thG])==1 )
                        begO = iPts[0];
                else
                    begO = begOrth;
                if (iPts)
                    free(iPts);
            }
#endif
/* neu */
#if 1
            /* cut of prevG(parallel) with gThis(parallel) is begO
             */
            else
            {   VGraphic	*pG, *thG;
                NSPoint		bPrevOrth, ePrevOrth, *iPts = NULL;
                int         iCnt = 0;

                bPrevOrth = orthPointAtBegOrEnd(gPrev, r, dirInd, 0);
                ePrevOrth = orthPointAtBegOrEnd(gPrev, r, dirInd, 1);
                // get parallel object to gPrev and gThis
                pG = [gPrev parallelObject:bPrevOrth :ePrevOrth :bPrevOrth :ePrevOrth];
                endOrth = orthPointAtBegOrEnd(gThis, r, dirInd, 1);
                thG = [gThis parallelObject:begOrth :endOrth :begOrth :endOrth];

                if ( pG && thG && (iCnt = [pG getIntersections:&iPts with:thG]) )
                {
                    if ( iCnt == 1 )
                        begO = iPts[0];
                    else
                    {   NSPoint bO = parallelPointbetweenObjects(gThis, gPrev, bAngle, r, dirInd, 0);
                        float   d=0, dist = MAXCOORD;
                        int     x;

                        for (x=0; x < iCnt; x++)
                        {
                            if ( (d = SqrDistPoints(iPts[x], bO)) < dist)
                            {   begO = iPts[x];
                                dist = d;
                            }
                        }
                    }
                }
                else if ( /*([gThis isKindOfClass:[VLine class]] && [gPrev isKindOfClass:[VLine class]])
                          ||*/ AngleNotSmallEnough(dir, w, bAngle) )
                    begO = parallelPointbetweenObjects(gThis, gPrev, bAngle, r, dirInd, 0);
                else
                    begO = begOrth;
                if (iPts)
                    free(iPts);
            }
#endif

            if ( splittedCurves && sc >= 0 && sc <= 3 ) // 2012-01-19
                gNext = [splittedCurves objectAtIndex:sc+1];
            else
            {   gNext = (i<endIx) ? [[pathCopy list] objectAtIndex:i+1] : [[pathCopy list] objectAtIndex:begIx];

                if ( [gNext isKindOfClass:[VCurve class]] )
                {   NSPoint p0, p1, p2, p3;

                    [(VCurve*)gNext getVertices:&p0 :&p1 :&p2 :&p3];
                    /* both Curve points are in its Start/End points - we build a line */
                    if ( SqrDistPoints(p0, p1) < 10*TOLERANCE && SqrDistPoints(p2, p3) < 10*TOLERANCE )
                    {
                        [lineNext setVertices:p0 :p3];
                        gNext = lineNext;
                    }
                }
                if ( splitCurves && [(VGraphic*)gNext length] > 1000.0*TOLERANCE &&
                     [gNext isKindOfClass:[VCurve class]] )
                {   NSArray	*splittedCurveNext = nil, *splittedC = nil;

                    splittedC = [(VCurve*)gNext splittedObjectsAt:0.333]; // 0.333 0.3
                    if ( (splittedCurveNext=[[splittedC objectAtIndex:0] splittedObjectsAt:0.4]) ) // 0.2 0.4
                        gNext = [splittedCurveNext objectAtIndex:0]; // the first of third parts of next curve
                }
            }
            eAngle = angleBetweenGraphicsInStartOrEnd(gThis, gNext, 1);
            endOrth = orthPointAtBegOrEnd(gThis, r, dirInd, 1);		// beg orthogonal to beg of gThis

            if ( NeedArc(dir, w, eAngle) )
            {   endO = endOrth;
                needArc = 1;
            }
/* so war es */
#if 0

            else if ( ([gThis isKindOfClass:[VLine class]] && [gNext isKindOfClass:[VLine class]])
                     || AngleNotSmallEnough(dir, w, eAngle) )
                endO = parallelPointbetweenObjects(gThis, gNext, eAngle, r, dirInd, 1);
            else
                calcEndOWithCut = 1; // endO = parallelPointbetweenObjects(gThis, gNext, eAngle, r, dirInd, 1);

            if ( calcEndOWithCut || SmallAngle(dir, w, eAngle) )
            {   VGraphic	*nG, *thG;
                NSPoint		bNextOrth, eNextOrth, *iPts = NULL;
                int         iCnt = 0;

                bNextOrth = orthPointAtBegOrEnd(gNext, r, dirInd, 0);
                eNextOrth = orthPointAtBegOrEnd(gNext, r, dirInd, 1);
                // get parallel object to gNext and gThis
                nG  = [gNext parallelObject:bNextOrth :eNextOrth :bNextOrth :eNextOrth];
                thG = [gThis parallelObject:begOrth   :endOrth   :begOrth   :endOrth];

                if ( nG && thG && (iCnt = [thG getIntersections:&iPts with:nG])==1 )
                    endO = iPts[0];
                else
                {
                    needArc = 2;	// here we calc edge orhtogonal with an arc
                    endO = endOrth;
                }
                if (iPts)
                    free(iPts);
            }

#endif

/* neu */
#if 1
            /* intersect parallel of gThis with parallel of gNext. Intersection point: endO
             */
            else
            {   VGraphic	*nG, *thG;
                NSPoint		bNextOrth, eNextOrth, *iPts = NULL;
                int         iCnt = 0;

                bNextOrth = orthPointAtBegOrEnd(gNext, r, dirInd, 0);
                eNextOrth = orthPointAtBegOrEnd(gNext, r, dirInd, 1);
                // get parallel object to gNext and gThis
                nG  = [gNext parallelObject:bNextOrth :eNextOrth :bNextOrth :eNextOrth];
                thG = [gThis parallelObject:begOrth   :endOrth   :begOrth   :endOrth];

                if ( nG && thG && (iCnt = [thG getIntersections:&iPts with:nG]) )
                {
                    if ( iCnt == 1 )
                        endO = iPts[0];
                    else // new
                    {   NSPoint eO = parallelPointbetweenObjects(gThis, gNext, eAngle, r, dirInd, 1);
                        float   d=0, dist = MAXCOORD;
                        int     x;

                        for (x=0; x < iCnt; x++)
                        {
                            if ( (d = SqrDistPoints(iPts[x], eO)) < dist)
                            {   endO = iPts[x];
                                dist = d;
                            }
                        }
                    }
                }
                else if ( /*([gThis isKindOfClass:[VLine class]] && [gNext isKindOfClass:[VLine class]])
                          ||*/ AngleNotSmallEnough(dir, w, eAngle) )
                    endO = parallelPointbetweenObjects(gThis, gNext, eAngle, r, dirInd, 1);
                else
                {   calcEndOWithCut = 1;
                    needArc = 2;	// here we calc edge orhtogonal with an arc
                    endO = endOrth;
                }
                if (iPts)
                    free(iPts);
            }
#endif

            /* now we can calc our parallel object of gThis */
            if ( (g = [gThis parallelObject:begOrth :endOrth :begO :endO]) )	/* build parallel objects */
            {
                if ( [g isKindOfClass:[VPath class]] ) // VPolyLine
                {   int	j, gCnt = [[(VPath*)g list] count];

                    for (j=0; j<gCnt; j++)
                        [[subPath list] addObject:[[(VPath*)g list] objectAtIndex:j]];
                }
                else
                    [[subPath list] addObject:g];
            }

            /* calulate arc to close ends
             * if we have to add an arc we use the end of gThis as center,
             * endO as start point, new angle is calculated
             */
            if ( needArc )
            {   VArc	*arc = [VArc arc];
                float	newA;

                [arc setWidth:[gThis width]];
                [arc setColor:[gThis color]];
                if ( needArc == 2 )	// not cut
                {
                    newA = ( eAngle > 360.0-eAngle ) ? ((360-eAngle)+180.0) : (eAngle+180.0);
                    if ( (!dir && w >= 0 && eAngle > 180.0) || (dir && w <= 0 && eAngle > 180.0) )
                    {   newA *= -1.0;
                        if ( width && (calcEndOWithCut || SmallAngle(dir, w, eAngle)) )
                        {   newA = 360.0 + newA;
                            if (newA < -360.0) newA += 360.0;
                        }
                    }
                    else if ( width && (calcEndOWithCut || SmallAngle(dir, w, eAngle)) )
                    {   newA = - (360.0-newA);
                        if (newA < -360.0) newA += 360.0;
                    }
                }	
                else
                {   /* eAngle > 180 */
                    newA = ( eAngle > 360.0-eAngle ) ? (eAngle-180.0) : ((360.0-eAngle)-180.0);
                    if ( (!dir && w >= 0 && eAngle < 180.0) || (dir && w <= 0 && eAngle < 180.0) )
                        newA *= -1.0;	/* cw */
                }
                center = [gThis pointWithNum:MAXINT]; // end pt of object is arc center - with out smoot edges
                if (Abs(newA) < 235.0) // we dont want arc greater than 180 degree (not possible in a contour)
                {   [arc setCenter:center start:endO angle:newA];
                    [[subPath list] addObject:arc];
                }
            }
        }
    }

    /* if (splitCurves) // debugging only */
    [self removeFaultGraphicsInSubpaths:path :w];

    [path unnest];	/* copy elements of subpath to list of path */
    [path setSelected:[self isSelected]];

    [pool release];
    return path;
}
#if 0 /* 4 Curves a 0.3/0.7 */
- (id)contour:(float)w inlay:(BOOL)inlay removeLoops:(BOOL)removeLoops
{   VPath	*path, *subPath=nil;
    int		i, listCnt = [list count], begIx=0, endIx=0, dir=0;
    int		direction, inside, directionArray[listCnt], insideArray[listCnt], dirInsideCnt=0;
    float	r, dirInd=1.0, bAngle, eAngle;
    int		cnt=0;

    /* we just return a copy */
    if ( (!filled && Abs(w)>width) || Diff(w, 0.0) < 0.0001 || (w<0.0 && Abs(w) == width) )
        return [[self copy] autorelease];

    //if ( Prefs_UseRaster )    // raster algorith must be called directly !
    //    return [self contourWithPixel:w];

    r = (w + width) / 2.0;	// the amount of growth

    path = [VPath path];
    [path setColor:color];

    /* remove Elements with no length
     * the problem is that we destroy our closed path!
     */
    for ( i=0, listCnt = [list count]; i<listCnt; i++ )
    {	VGraphic	*gThis = [list objectAtIndex:i];

        if ( [gThis length] < 10.0*TOLERANCE )
        {
            [list removeObject:gThis];
            i--;
            //[self closePath];
            listCnt = [list count];
            continue;
        }
    }

    /* what we do here:
     * step through elements of path
     * calculate start, end points for outline-elements in a distance to path (inside/outside)
     * calculate parallel elements through start and end points
     * we have to calculate each sub path separately, so we put them in real sub paths
     */

    /* walk through path list
     */
    for ( i=0, listCnt = [list count]; i<listCnt; i++ )
    {	id	g,
                gThis, gPrev, gNext;	/* this object, previous object, next object */
        NSPoint	begO, endO,	  /* start and endpoint of contour-object, if we dont add an arc (O = outline) */
                begOrth, endOrth, /* start and endpoint of contour-object, if we add an arc (orthogonal points) */
                center;			/* center point of arc if needed */
        int	sc, needArc = 0;	/* wether we need an arc to build correct contour around current edge */
        NSMutableArray	*splittedCurves = nil;

        gThis = [list objectAtIndex:i];	/* this object */

        /* new sub path
         */
        if ( !i || i>endIx )	/* new sub path */
        {   subPath = [VPath path];
            [[path list] addObject:subPath];
            begIx = i;
            //endIx = [self getLastObjectOfSubPath:begIx];
            endIx = [self getLastObjectOfSubPath:begIx]; //  tolerance:TOLERANCE

            cnt = 0;	/* counter for cutIndex array */

            /* only one element in subpath, so this must be an arc */
            if ( begIx == endIx )
            {	VGraphic	*arc;
                int	oldFillStyle=[gThis filled];

                if ( !([gThis isKindOfClass:[VArc class]] && Abs([(VArc*)gThis angle]) == 360.0) &&
                     ![gThis isKindOfClass:[VRectangle class]] ) /* nothing */
                {   insideArray[dirInsideCnt] = 0;
                    directionArray[dirInsideCnt++] = 0; /* doesnt matter */
                    continue;
                }
                [gThis setFilled:YES];
                if ( [self subPathInsidePath:begIx :endIx] )
                {   arc = [gThis contour:-w];
                    insideArray[dirInsideCnt] = 1;
                }
                else
                {   arc = [gThis contour:w];
                    insideArray[dirInsideCnt] = 0;
                }
                directionArray[dirInsideCnt++] = 0; /* doesnt matter if only one object */
//                ( [self subPathInsidePath:begIx :endIx] ) ? (arc = [gThis contour:-w]) : (arc = [gThis contour:w]);
                if (arc)
                    [[subPath list] addObject:arc];
                [gThis setFilled:oldFillStyle];
                continue;
            }
            /* determine direction indicator inside(1), outside(-1)
             */
            direction = [self directionOfSubPath:begIx :endIx];	/* 1 = ccw, 0 = cw */
            if ( (inside = [self subPathInsidePath:begIx :endIx]) )
            	dir = ( direction ) ? 0 : 1;
            else
                dir = direction;
            dirInd  = ( dir ) ? 1.0 : -1.0;			/* 1 = ccw, 0 = cw */

            directionArray[dirInsideCnt] = direction;
            insideArray[dirInsideCnt++] = inside;
        }

        /* split curves for better results */
        if ( [gThis isKindOfClass:[VCurve class]] )
        {   NSArray	*splittedCurves1 = nil, *splittedCurves2 = nil, *splittedCurves3 = nil;

            splittedCurves = [NSMutableArray arrayWithCapacity:4];
            splittedCurves1 = [gThis splittedObjectsAt:0.5];

            splittedCurves2 = [[splittedCurves1 objectAtIndex:0] splittedObjectsAt:0.3];
            [splittedCurves addObject:[splittedCurves2 objectAtIndex:0]];
            [splittedCurves addObject:[splittedCurves2 objectAtIndex:1]];
            splittedCurves3 = [[splittedCurves1 objectAtIndex:1] splittedObjectsAt:0.7];
            [splittedCurves addObject:[splittedCurves3 objectAtIndex:0]];
            [splittedCurves addObject:[splittedCurves3 objectAtIndex:1]];
        }
        for ( sc=0; sc < ((splittedCurves) ? 4 : 1); sc++ )
        {   BOOL	calcBegOWithCut = 0, calcEndOWithCut = 0;

            if ( splittedCurves )
                gThis = [splittedCurves objectAtIndex:sc];

            if ( sc == 1 )
                gPrev = [splittedCurves objectAtIndex:0];
            else if ( sc == 2 )
                gPrev = [splittedCurves objectAtIndex:1];
            else if ( sc == 3 )
                gPrev = [splittedCurves objectAtIndex:2];
            else
            {
                gPrev = (i>begIx) ? [list objectAtIndex:i-1] : [list objectAtIndex:endIx];
                if ( [gPrev isKindOfClass:[VCurve class]] )
                {   NSArray	*splittedCurvePrev = nil, *splittHalf = nil;

                    splittHalf = [gPrev splittedObjectsAt:0.5];
                    if ( (splittedCurvePrev = [[splittHalf objectAtIndex:1] splittedObjectsAt:0.7]) )
                        gPrev = [splittedCurvePrev objectAtIndex:1]; // the last of third parts of prev curve
                }
            }
            bAngle = angleBetweenGraphicsInStartOrEnd(gThis, gPrev, 0);
            begOrth = orthPointAtBegOrEnd(gThis, r, dirInd, 0);		/* beg orthogonal to beg of gThis */

            /* in this cases we need an arc between the graphics (added only at end points)
             * angle is greater than 180 at correction side
             */
            if ( NeedArc(dir, w, bAngle) )
                begO = begOrth;
            else if ( ([gThis isKindOfClass:[VLine class]] && [gPrev isKindOfClass:[VLine class]])
                     || AngleNotSmallEnough(dir, w, bAngle) )
                begO = parallelPointbetweenObjects(gThis, gPrev, bAngle, r, dirInd, 0);
            else
                calcBegOWithCut=1; // begO = parallelPointbetweenObjects(gThis, gPrev, bAngle, r, dirInd, 0);

            /* cut of prevG(parallel) with gThis(parallel) is begO
             */
            if ( calcBegOWithCut || SmallAngle(dir, w, bAngle) )
            {   VGraphic    *pG, *thG;
                NSPoint     bPrevOrth, ePrevOrth, *iPts = NULL;
                int         iCnt = 0;

                bPrevOrth = orthPointAtBegOrEnd(gPrev, r, dirInd, 0);
                ePrevOrth = orthPointAtBegOrEnd(gPrev, r, dirInd, 1);
                // get parallel object to gPrev and gThis
                pG = [gPrev parallelObject:bPrevOrth :ePrevOrth :bPrevOrth :ePrevOrth];
                endOrth = orthPointAtBegOrEnd(gThis, r, dirInd, 1);
                thG = [gThis parallelObject:begOrth :endOrth :begOrth :endOrth];

                if ( pG && thG && (iCnt = [pG getIntersections:&iPts with:thG])==1 )
                    begO = iPts[0];
                else
                    begO = begOrth;
                if (iPts)
                    free(iPts);
            }

            if ( !sc && splittedCurves )
                gNext = [splittedCurves objectAtIndex:1];
            else if ( sc == 1 && splittedCurves )
                gNext = [splittedCurves objectAtIndex:2];
            else if ( sc == 2 && splittedCurves )
                gNext = [splittedCurves objectAtIndex:3];
            else
            {   gNext = (i<endIx) ? [list objectAtIndex:i+1] : [list objectAtIndex:begIx];
                if ( [gNext isKindOfClass:[VCurve class]] )
                {   NSArray	*splittedCurveNext = nil, *splittHalf = nil;

                    splittHalf = [gNext splittedObjectsAt:0.5];
                    if ( (splittedCurveNext=[[splittHalf objectAtIndex:0] splittedObjectsAt:0.3]) )
                        gNext = [splittedCurveNext objectAtIndex:0]; // the first of third parts of next curve
                }
            }
            eAngle = angleBetweenGraphicsInStartOrEnd(gThis, gNext, 1);
            endOrth = orthPointAtBegOrEnd(gThis, r, dirInd, 1);		/* beg orthogonal to beg of gThis */

            if ( NeedArc(dir, w, eAngle) )
            {   endO = endOrth;
                needArc = 1;
            }
            else if ( ([gThis isKindOfClass:[VLine class]] && [gNext isKindOfClass:[VLine class]])
                     || AngleNotSmallEnough(dir, w, eAngle) )
                endO = parallelPointbetweenObjects(gThis, gNext, eAngle, r, dirInd, 1);
            else
                calcEndOWithCut = 1; // endO = parallelPointbetweenObjects(gThis, gNext, eAngle, r, dirInd, 1);

            /* intersect parallel of gThis with parallel of gNext. Intersection point: begO
             */
            if ( calcEndOWithCut || SmallAngle(dir, w, eAngle) )
            {   VGraphic	*nG, *thG;
                NSPoint	bNextOrth, eNextOrth, *iPts = NULL;
                int		iCnt;

                bNextOrth = orthPointAtBegOrEnd(gNext, r, dirInd, 0);
                eNextOrth = orthPointAtBegOrEnd(gNext, r, dirInd, 1);
                // get parallel object to gNext and gThis
                nG = [gNext parallelObject:bNextOrth :eNextOrth :bNextOrth :eNextOrth];
                thG = [gThis parallelObject:begOrth :endOrth :begOrth :endOrth];

                if ( nG && thG && (iCnt = [thG getIntersections:&iPts with:nG])==1 )
                    endO = iPts[0];
                else
                {
                    needArc = 2;	// here we calc edge orhtogonal with an arc
                    endO = endOrth;
                }
                if (iPts)
                    free(iPts);
            }

            /* now we can calc our parallel object of gThis */
            if ( (g = [gThis parallelObject:begOrth :endOrth :begO :endO]) )	/* build parallel objects */
            {
                if ( [g isKindOfClass:[VPath class]] ) // VPolyLine
                {   int	j, gCnt = [[g list] count];

                    for (j=0; j<gCnt; j++)
                        [[subPath list] addObject:[[g list] objectAtIndex:j]];
                }
                else
                    [[subPath list] addObject:g];
            }

            /* calulate arc to close ends
             * if we have to add an arc we use the end of gThis as center,
             * endO as start point, new angle is calculated
             */
            if ( needArc )
            {   VArc	*arc = [VArc arc];
                float	newA;

                [arc setWidth:[gThis width]];
                [arc setColor:[gThis color]];
                if ( needArc == 2 )	// not cut
                {   ( eAngle > 360.0-eAngle ) ? (newA = (360-eAngle)+180.0) : (newA = eAngle+180.0);
                    if ( (!dir && w >= 0 && eAngle > 180.0) || (dir && w <= 0 && eAngle > 180.0) )
                    {   newA *= -1.0;
                        if ( width && (calcEndOWithCut || SmallAngle(dir, w, eAngle)) )
                        {   newA = 360.0 + newA;
                            if (newA < -360.0) newA += 360.0;
                        }
                    }
                    else if ( width && (calcEndOWithCut || SmallAngle(dir, w, eAngle)) )
                    {   newA = - (360.0-newA);
                        if (newA < -360.0) newA += 360.0;
                    }
                }	
                else
                {   /* eAngle > 180 */
                    newA = ( eAngle > 360.0-eAngle ) ? (eAngle-180.0) : ((360.0-eAngle)-180.0);
                    if ( (!dir && w >= 0 && eAngle < 180.0) || (dir && w <= 0 && eAngle < 180.0) )
                        newA *= -1.0;	/* cw */
                }
                center = [gThis pointWithNum:MAXINT]; // end pt of object is arc center - with out smoot edges
                if (Abs(newA) < 235.0) // we dont want arc greater than 180 degree (not possible in a contour)
                {   [arc setCenter:center start:endO angle:newA];
                    [[subPath list] addObject:arc];
                }
            }
        }
    }

    [self removeFaultGraphicsInSubpaths:path :w];

    [path unnest];	/* copy elements of subpath to list of path */
    [path setSelected:[self isSelected]];

    return path;
}
#endif

- (id)contourOpenLeftOrRight:(float)w
{   VPath	*path = [VPath path];
    int		i, cnt = [list count], to = -1, from = -1;
    VFloat	cw = Abs((w + width)), oldWidth = 0.0, r=0.0;
    NSPoint opS, opE;

    /* we just return a copy */
    if ( (Diff(w, 0.0) < 0.0001 && width == 0.0) )
        return [[self copy] autorelease];

    if ( [self closed] )
    {   BOOL    dir = [self isDirectionCCW];

        if ( w < 0.0 && !dir )
            w = -w; // correction to left (inside) needed
        else if ( w > 0.0 && !dir )
            w = -w; // correction to right(outside here) needed

        [self setFilled:YES];
        path = [self contour:w inlay:NO splitCurves:YES];
        [self setFilled:NO];
        return path;
    }

    /* remove Elements with no length
     * the problem is that we destroy our closed path!
     */
    for ( i=0, cnt = [list count]; i<cnt; i++ )
    {	VGraphic	*gThis = [list objectAtIndex:i];

        if ( [gThis length] < 10.0*TOLERANCE )
        {
            [list removeObject:gThis];
            i--;
            cnt = [list count];
            continue;
        }
    }

    [path setColor:[self color]];
    // build contour of all elements in path
    for (i=0; i<cnt; i++)
    {   VGraphic    *gr = [list objectAtIndex:i], *ng;

        //if ( [gr isKindOfClass:[VLine class]] ) // line did not have a width here ! arc/rect eigentlich auch nicht ?
        // falls doch -> [gr setWidth:0.0]; // nachher alten fillstyle wieder setzen ???
        oldWidth = [gr width];
        [gr setWidth:0.0];
        ng = [gr contour:cw];
        [gr setWidth:oldWidth];
        if ( [ng isKindOfClass:[VPath class]] ) // line, open arc
            [(VPath*)ng setFilled:YES optimize:NO]; // allready optimized
        else // full arc, rectangle
            [ng setFilled:YES]; // need objects filled for uniteAreas
        [[path list] addObject:ng];
    }

    // unite these elements
    {   HiddenArea	*hiddenArea = [HiddenArea new];
        [hiddenArea uniteAreas:[path list]];
        [hiddenArea release];
    }
    // unfill
    [path unnest];
    [path setFilled:NO];


    /* search s/e on right/left side - remove elements from e to start */
    r = cw / 2.0;	// the amount of growth

    /* orthpoint right/left of start */
    opS = orthPointAtBegOrEnd([[self list] objectAtIndex:0], r, ((w < 0) ? (-1.0):(1.0)), 0);
    /* orthpoint right/left of end */
    opE = orthPointAtBegOrEnd([[self list] objectAtIndex:cnt-1], r, ((w < 0) ? (-1.0):(1.0)), 1);

    cnt = [[path list] count];
    /* should be both a 180 degree arc */
    /* search opS (end of Graphic) inside path - to */
    for (i=0; i < cnt; i++)
    {
        if ( w > 0.0 &&
             SqrDistPoints(opS, [[[path list] objectAtIndex:i] pointWithNum:MAXINT]) < 25.0*TOLERANCE)
        {   to = i;
            break;
        }
        else if ( w < 0.0 &&
             SqrDistPoints(opS, [[[path list] objectAtIndex:i] pointWithNum:0]) < 25.0*TOLERANCE)
        {   from = i;
            break;
        }
    }
    /* search opE (start of Graphic) inside path - from */
    for (i=0; i < cnt; i++)
    {
        if ( w > 0.0 &&
             SqrDistPoints(opE, [[[path list] objectAtIndex:i] pointWithNum:0]) < 25.0*TOLERANCE)
        {   from = i;
            break;
        }
        else if ( w < 0.0 &&
             SqrDistPoints(opE, [[[path list] objectAtIndex:i] pointWithNum:MAXINT]) < 25.0*TOLERANCE)
        {   to = i;
            break;
        }
    }

    if ( from == -1 || to == -1 )
            return path;

#   if 0
    {
        /* second try search missing from/to with other opSE */
        if (from == -1) // start not found
        {
        }
        if (to == -1) // end not found
        {   VGraphic        *lastG = [[self list] objectAtIndex:[[self list] count]-1];
            NSMutableArray  *nglist=nil;
            VArc            *arc = [VArc arc];
            NSPoint         *pts, e = [lastG pointWithNum:MAXINT];
            double          distTol = (Abs(w)/4.0)*(Abs(w)/4.0);

            [arc setCenter:e start:NSMakePoint(e.x+Abs(w/2.0), e.y) angle:360.0];
            if ( [lastG getIntersections:&pts with:arc] ) // only one possible (else to short)
            {
                if ((nglist=[lastG getListOfObjectsSplittedAtPoint:pts[0]]))
                {
                    /* orthpoint right/left of shortened end */
                    opE = orthPointAtBegOrEnd([nglist objectAtIndex:0], r, ((w < 0) ? (-1.0):(1.0)), 1);
                    /* search opE (start of Graphic) inside path - to*/
                    for (i=0; i < cnt; i++)
                    {
                        if ( w > 0.0 &&
                            SqrDistPoints(opS, [[[path list] objectAtIndex:i] pointWithNum:MAXINT])
                            < distTol)
                        {   to = i;
                            break;
                        }
                        else if ( w < 0.0 &&
                             SqrDistPoints(opE, [[[path list] objectAtIndex:i] pointWithNum:MAXINT])
                             < distTol)
                        {   to = i;
                            break;
                        }
                    }
                }
            }
        }
        if ( from == -1 || to == -1 )
            return path;
    }
#   endif

    /* remove from to to */
    for (i=to; i >= ((!to || to < from) ? 0:from); i--)
    {
        [[path list] removeObjectAtIndex:i];
        cnt--;
        /* we removed befor j -> j move one down in list !!! */
        if (i < from) { from--; to--; }
        
        if (!i && to < from) // we step over 0 - second part until from !
        {   i = cnt;
            to = from+1; // little hack mh - second part until from !
        }
    }
    if (w < 0.0) // inside need a correction so we can also milling again direction (Gegenlauf)
        [path changeDirection];
    return path;
}

/* Build Contour of unfilled path
 * modified: 2011-03-11 (build outline with stroke width + distance)
 */
- (id)contourOpen:(float)w
{   VPath	*path = [VPath path];
    int		i, cnt = [list count];
    float	cw = (w + width), oldWidth = 0.0;

    /* we just return a copy */
    //if ( (w < 0.0 && Abs(w) >= width) || Diff(w, 0.0) < 0.0001 )
    if ( (Diff(w, 0.0) < 0.0001 && width == 0.0) || (w < 0.0 && Abs(w) >= width) )
        return [[self copy] autorelease];

    /* remove Elements with no length
     * the problem is that we destroy our closed path!
     */
    for ( i=0, cnt = [list count]; i<cnt; i++ )
    {	VGraphic	*gThis = [list objectAtIndex:i];

        if ( [gThis length] < 10.0*TOLERANCE )
        {
            [list removeObject:gThis];
            i--;
            //[self closePath];
            cnt = [list count];
            continue;
        }
    }

    [path setColor:[self color]];
    // build contour of all elements in path
    for (i=0; i<cnt; i++)
    {   VGraphic    *gr = [list objectAtIndex:i], *ng;

        //if ( [gr isKindOfClass:[VLine class]] ) // line did not have a width here ! arc/rect eigentlich auch nicht ?
        // falls doch -> [gr setWidth:0.0]; // nachher alten fillstyle wieder setzen ???
        oldWidth = [gr width];
        [gr setWidth:0.0];
        ng = [gr contour:cw];
        [gr setWidth:oldWidth];
        if ( [ng isKindOfClass:[VPath class]] ) // line, open arc
            [(VPath*)ng setFilled:YES optimize:NO]; // allready optimized
        else // full arc, rectangle
            [ng setFilled:YES]; // need objects filled for uniteAreas
        [[path list] addObject:ng];
    }

    // unite these elements
    {   HiddenArea	*hiddenArea = [HiddenArea new];
        [hiddenArea uniteAreas:[path list]];
        [hiddenArea release];
    }
    // unfill
    [path unnest];
    [path setFilled:NO];
    return path;
}

/* get contour with pixels
 * return the calculated path and the linePath (with the up and down engraving lines)
 */
- (VPath*)contourWithPixel:(float)w
{   PathContour	*pathContour;
    VPath	*path;

    if ( !(w+width) )
    {	NSMutableData	*data;
        NSArchiver      *ts;
        NSUnarchiver	*tsu;

        /* writes the path to a stream and reads it back from this stream */
        data = [[NSMutableData alloc] init];
        ts = [[NSArchiver alloc] initForWritingWithMutableData:data];
        [ts encodeRootObject:self];
        [ts release];
        tsu = [[NSUnarchiver alloc] initForReadingWithData:data];
        path = [[tsu decodeObject] retain];
        [tsu release];
        [data release];

        [path setFilled:NO];
        [path setSelected:[self isSelected]];

        return path;
    }

    pathContour = [[PathContour new] autorelease];

    return [pathContour contourPath:self width:w];
}

/* returns a flattened copy of path
 */
/*- flattenedObject
{   VPath		*newPath = [[self copy] autorelease];
    NSMutableArray	*plist;
    int			i, cnt;

    cnt = [list count];
    plist = [NSMutableArray array];
    for ( i=0; i<cnt; i++)
    {	id	fg, g = [list objectAtIndex:i];

        fg = [g flattenedObject];
        if ( [fg isKindOfClass:[VPath class]] )	// copy list of fg to path list
        {   int	j;

            for (j=0; j<[fg count]; j++)
                [plist addObject:[[fg list] objectAtIndex:j]];
        }
        else if (fg)
            [plist addObject:fg];
    }
    [newPath setList:plist];
    [newPath setSelected:[self isSelected]];

    return newPath;
}*/

- (NSMutableArray*)getListOfObjectsSplittedFromGraphic:g
{   NSMutableArray	*splitList = [NSMutableArray array], *spList = nil;
    int			i, j, cnt = [list count];
    NSAutoreleasePool 	*pool = [NSAutoreleasePool new];

    /* tile each graphic from path with pArray
     * add splitted objects to splitList (else object)
     */
    for (i=0; i<cnt; i++)
    {	VGraphic	*gr = [list objectAtIndex:i];

        spList = [gr getListOfObjectsSplittedFromGraphic:g];
        if ( spList )
        {   for ( j=0; j<(int)[spList count]; j++ )
                [splitList addObject:[spList objectAtIndex:j]];
        }
        else
            [splitList addObject:[[gr copy] autorelease]];
    }
    [pool release];
    if ( [splitList count] > [list count] )
        return splitList;
    return nil;
}

- getListOfObjectsSplittedFrom:(NSPoint*)pArray :(int)iCnt
{   NSMutableArray	*splitList = [NSMutableArray array], *spList = nil;
    int			i, j, cnt = [list count];
    NSAutoreleasePool 	*pool = [NSAutoreleasePool new];

    /* tile each graphic from path with pArray
     * add splitted objects to splitList (else object)
     */
    for (i=0; i<cnt; i++)
    {	VGraphic	*g = [list objectAtIndex:i];

        spList = [g getListOfObjectsSplittedFrom:pArray :iCnt];
        if ( spList )
        {   for ( j=0; j<(int)[spList count]; j++ )
                [splitList addObject:[spList objectAtIndex:j]];
        }
        else
            [splitList addObject:[[g copy] autorelease]];
    }
    [pool release];
    if ( [splitList count] > [list count] )
        return splitList;
    return nil;
}

- (NSMutableArray*)getListOfObjectsSplittedAtPoint:(NSPoint)pt
{   NSMutableArray	*splitList = [NSMutableArray array], *spList = nil;
    int			i, cnt = [list count], splitI = -1;
    NSPoint		cpt, start, end, sgStart, sgEnd;
    NSAutoreleasePool 	*pool = [NSAutoreleasePool new];
    float		distance=MAXCOORD;
    VGraphic		*splitg=nil;

    cpt = [self nearestPointOnObject:&splitI distance:&distance toPoint:pt];

    start = [self pointWithNum:0];
    end = [self pointWithNum:MAXINT];
    if ( (Diff(start.x, cpt.x) < 100.0*TOLERANCE && Diff(start.y, cpt.y) < 100.0*TOLERANCE) ||
         (Diff(end.x, cpt.x) < 100.0*TOLERANCE && Diff(end.y, cpt.y) < 100.0*TOLERANCE) )
    {   [pool release];
        return nil;
    }
    splitg = [list objectAtIndex:splitI];
    sgStart = [splitg pointWithNum:0];
    sgEnd = [splitg pointWithNum:MAXINT];
    if ((Diff(sgStart.x, cpt.x) > 100.0*TOLERANCE || Diff(sgStart.y, cpt.y) > 100.0*TOLERANCE) &&
        (Diff(sgEnd.x, cpt.x) > 100.0*TOLERANCE || Diff(sgEnd.y, cpt.y) > 100.0*TOLERANCE))
        spList = [splitg getListOfObjectsSplittedFrom:&cpt :1];
    if (splitI == 0 && Diff(sgEnd.x, cpt.x) <= 100.0*TOLERANCE && Diff(sgEnd.y, cpt.y) <= 100.0*TOLERANCE)
        splitI = 1; // (splitI+1 < cnt) ? (splitI+1) : (0);

    if (splitI != -1)
    {   VPath		*sPath = [VPath path];
        VGraphic	*gr;

        [sPath setWidth:width];
        [sPath setColor:color];
        for (i=0; i<splitI; i++)
        {
            if ([[sPath list] count] > 0)
            {   NSPoint	pEnd, cBeg;

                pEnd = [[[sPath list] objectAtIndex:[[sPath list] count]-1] pointWithNum:MAXINT];
                cBeg = [[list objectAtIndex:i] pointWithNum:0];
                if (SqrDistPoints(pEnd, cBeg) < (TOLERANCE*15.0)*(TOLERANCE*15.0))
                    [[sPath list] addObject:[[[list objectAtIndex:i] copy] autorelease]];
                else
                {
                    if ([[sPath list] count] == 1)
                        [splitList addObject:[[sPath list] objectAtIndex:0]];
                    else
                        [splitList addObject:sPath];
                    sPath = [VPath path];
                    [sPath setWidth:width];
                    [sPath setColor:color];
                    [[sPath list] addObject:[[[list objectAtIndex:i] copy] autorelease]];
                }
            }
            else
                [[sPath list] addObject:[[[list objectAtIndex:i] copy] autorelease]];
        }
        if ([spList count] > 1)
        {
            gr = [spList objectAtIndex:0];
            if ([gr isKindOfClass:[VPath class]])
            {   int j, pCnt = [[(VPath*)gr list] count];

                if ([[sPath list] count] > 0)
                {   NSPoint	pEnd, cBeg;

                    pEnd = [[[sPath list] objectAtIndex:[[sPath list] count]-1] pointWithNum:MAXINT];
                    cBeg = [gr pointWithNum:0];
                    if (SqrDistPoints(pEnd, cBeg) < (TOLERANCE*15.0)*(TOLERANCE*15.0))
                    {
                        for (j=1; j<pCnt; j++)
                            [[sPath list] addObject:[[(VPath*)gr list] objectAtIndex:j]];
                    }
                    else
                    {   if ([[sPath list] count] == 1)
                        [splitList addObject:[[sPath list] objectAtIndex:0]];
                        else
                            [splitList addObject:sPath];
                        sPath = [VPath path];
                        [sPath setWidth:width];
                        [sPath setColor:color];
                        for (j=1; j<pCnt; j++)
                            [[sPath list] addObject:[[(VPath*)gr list] objectAtIndex:j]];
                    }
                }
                else
                    for (j=1; j<pCnt; j++)
                        [[sPath list] addObject:[[(VPath*)gr list] objectAtIndex:j]];
            }
            else
            {
                if ([[sPath list] count] > 0)
                {   NSPoint	pEnd, cBeg;

                    pEnd = [[[sPath list] objectAtIndex:[[sPath list] count]-1] pointWithNum:MAXINT];
                    cBeg = [gr pointWithNum:0];
                    if (SqrDistPoints(pEnd, cBeg) < (TOLERANCE*15.0)*(TOLERANCE*15.0))
                        [[sPath list] addObject:gr];
                    else
                    {   if ([[sPath list] count] == 1)
                            [splitList addObject:[[sPath list] objectAtIndex:0]];
                        else
                            [splitList addObject:sPath];
                        sPath = [VPath path];
                        [sPath setWidth:width];
                        [sPath setColor:color];
                        [[sPath list] addObject:gr];
                    }
                }
                else
                    [[sPath list] addObject:gr];
            }
        }
        if ([[sPath list] count] == 1) // 360 Arc or Rectangle
            [splitList addObject:[[sPath list] objectAtIndex:0]];
        else
            [splitList addObject:sPath];


        sPath = [VPath path];
        [sPath setWidth:width];
        [sPath setColor:color];
        if ([spList count] > 1)
        {
            gr = [spList objectAtIndex:1];
            if ([gr isKindOfClass:[VPath class]])
            {   int j, pCnt = [[(VPath*)gr list] count];

                for (j=1; j<pCnt; j++)
                    [[sPath list] addObject:[[(VPath*)gr list] objectAtIndex:j]];
            }
            else
                [[sPath list] addObject:gr];
        }
        for (i=(([spList count] > 1) ? splitI+1 : splitI); i<cnt; i++)
        {
            if ([[sPath list] count] > 0)
            {   NSPoint	pEnd, cBeg;

                pEnd = [[[sPath list] objectAtIndex:[[sPath list] count]-1] pointWithNum:MAXINT];
                cBeg = [[list objectAtIndex:i] pointWithNum:0];
                if (SqrDistPoints(pEnd, cBeg) < (TOLERANCE*15.0)*(TOLERANCE*15.0))
                    [[sPath list] addObject:[[[list objectAtIndex:i] copy] autorelease]];
                else
                {
                    if ([[sPath list] count] == 1)
                        [splitList addObject:[[sPath list] objectAtIndex:0]];
                    else
                        [splitList addObject:sPath];
                    sPath = [VPath path];
                    [sPath setWidth:width];
                    [sPath setColor:color];
                    [[sPath list] addObject:[[[list objectAtIndex:i] copy] autorelease]];
                }
            }
            else
                [[sPath list] addObject:[[[list objectAtIndex:i] copy] autorelease]];
        }
        if ([[sPath list] count] == 1) // 360 Arc or Rectangle
            [splitList addObject:[[sPath list] objectAtIndex:0]];
        else
            [splitList addObject:sPath];
    }
    [pool release];
    if ([splitList count])
        return splitList;
    return nil;
}

- (BOOL)intersects:g
{   NSPoint	*pts;

    if ( [self getIntersections:&pts with:g] )
    {   free(pts);
        return YES;
    }
    return NO;
}
- (int)getIntersections:(NSPoint**)ppArray with:g
{   int			i, j, iCnt = 0;
    int			len = Min(100, [self numPoints]);
    NSPoint		*pts = NULL;
    //NSMutableData	*data = [NSMutableData dataWithLength:([list count]*9) * sizeof(NSPoint)];
    NSAutoreleasePool	*pool = [NSAutoreleasePool new];

    //*ppArray = [data mutableBytes];
    *ppArray = malloc(len * sizeof(NSPoint));
    //*ppArray = NSZoneMalloc((NSZone*)[(NSObject*)NSApp zone], len * sizeof(NSPoint));
    for (i=[list count]-1; i>=0; i--)
    {	id	gp = [list objectAtIndex:i];
        int	cnt, oldCnt = iCnt;

        if ( gp == g )
            continue;

        cnt = [gp getIntersections:&pts with:g];	/* line, arc, curve, rectangle */
        if (iCnt+cnt >= len)
        {   //[data increaseLengthBy:cnt];
            //*ppArray = [data mutableBytes];
            *ppArray = realloc(*ppArray, (len+=cnt*2) * sizeof(NSPoint));
	    //*ppArray = NSZoneRealloc((NSZone*)[(NSObject*)NSApp zone], *ppArray, (len+=cnt) * sizeof(NSPoint));
        }
        for (j=0; j<cnt; j++)
        {
            if ( !pointInArray(pts[j], *ppArray, oldCnt) )
                (*ppArray)[iCnt++] = pts[j];
            else
            {   NSPoint	start, end;

                if ( [gp isKindOfClass:[VLine class]] )		/* line */
                    [(VLine*)gp getVertices:&start :&end];
                else if ( [gp isKindOfClass:[VArc class]] || [gp isKindOfClass:[VCurve class]] )
                {   start = [gp pointWithNum:0];
                    end = [gp pointWithNum:MAXINT];
                }
                else if ( [gp isKindOfClass:[VRectangle class]] )
                {   NSPoint	ur, ul, size;
                    [(VRectangle*)gp getVertices:&start :&size]; // origin size
                    end = start; end.x += size.x;
                    ul = start; ul.y += size.y;
                    ur = end; ur.y += size.y;
                    if ( (Diff(pts[j].x, ul.x) + Diff(pts[j].y, ul.y) < 10.0*TOLERANCE) ||
                         (Diff(pts[j].x, ur.x) + Diff(pts[j].y, ur.y) < 10.0*TOLERANCE) )
                        continue; // do not add
                }
                else if ( [gp isKindOfClass:[VPolyLine class]] )
                {   int	k, pCnt = [(VPolyLine*)gp ptsCount], stop = 0;

                    for (k=1; k<pCnt-1; k++)
                    {   NSPoint	pt = [(VPolyLine*)gp pointWithNum:k];
                        if ( Diff(pts[j].x, pt.x) + Diff(pts[j].y, pt.y) < 10.0*TOLERANCE )
                        {   stop = 1; break; }
                    }
                    if (stop)
                        continue; // do not add
                    [(VPolyLine*)gp getEndPoints:&start :&end];
                }
                else
                {
                    start.x = end.x = pts[j].x; start.y = end.y = pts[j].y;
                }
                /* point is no edge point of gp -> add */
                if ( (Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) > 10.0*TOLERANCE) &&
                     (Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) > 10.0*TOLERANCE) )
                    (*ppArray)[iCnt++] = pts[j];
            }
        }
        if (pts)
            free(pts);
    }

    if (!iCnt)
    {   free(*ppArray);
        //NSZoneFree((NSZone*)[(NSObject*)NSApp zone], *ppArray);
        *ppArray = NULL;
    }
    [pool release];
    return iCnt;
}
#if 0

/*
 * FIXME: better intersection function - should be used for point in polygon test
 *
 * schiebt start/end punkte von horizontaler linie weg
 */
- (int)getIntersectionsForFilling:(NSPoint**)ppArray with:g
{   int			i, j, iCnt = 0;
    int			len = Min(100, [self numPoints]);
    NSPoint		*pts = NULL, ls, le;

    *ppArray = malloc(len * sizeof(NSPoint));
    //*ppArray = NSZoneMalloc((NSZone*)[(NSObject*)NSApp zone], len * sizeof(NSPoint));

    /* g is allways a line here */
    [g getVertices:&ls :&le];

    for (i=[list count]-1; i>=0; i--)
    {	id	gp = [list objectAtIndex:i], tgp = nil;
        int	cnt = 0, oldCnt = iCnt;
        float	d=0.0;

        if ( gp == g )
            continue;

        /* here we must move the s/e pts of gp far away from line */
        if ( [gp isKindOfClass:[VLine class]] )
        {   NSPoint	p0, p1;

            [(VLine*)gp getVertices:&p0 :&p1];
            d = p0.y - ls.y;
            if (d >= 0.0 && d <= 3.0*TOLERANCE)
                p0.y += 3.0*TOLERANCE;
            if (d < 0.0 && -d <= 3.0*TOLERANCE)
                p0.y -= 3.0*TOLERANCE;
            d = p1.y - ls.y;
            if (d >= 0.0 && d <= 3.0*TOLERANCE)
                p1.y += 3.0*TOLERANCE;
            if (d < 0.0 && -d <= 3.0*TOLERANCE)
                p1.y -= 3.0*TOLERANCE;

            tgp = [[VLine allocWithZone:[self zone]] init];
            [tgp setVertices:p0 :p1];
        }
        else if ( [gp isKindOfClass:[VCurve class]] )
        {   NSPoint	p0, p1, p2, p3;

            [(VCurve*)gp getVertices:&p0 :&p1 :&p2 :&p3];
            d = p0.y - ls.y;
            if (d >= 0.0 && d <= 3.0*TOLERANCE)
            {   p0.y += 3.0*TOLERANCE;
                p1.y += 3.0*TOLERANCE;
            }
            if (d < 0.0 && -d <= 3.0*TOLERANCE)
            {   p0.y -= 3.0*TOLERANCE;
                p1.y -= 3.0*TOLERANCE;
            }
            d = p3.y - ls.y;
            if (d >= 0.0 && d <= 3.0*TOLERANCE)
            {   p3.y += 3.0*TOLERANCE;
                p2.y += 3.0*TOLERANCE;
            }
            if (d < 0.0 && -d <= 3.0*TOLERANCE)
            {   p3.y -= 3.0*TOLERANCE;
                p2.y -= 3.0*TOLERANCE;
            }
            tgp = [[VCurve allocWithZone:[self zone]] init];
            [(VCurve*)tgp setVertices:p0 :p1 :p2 :p3];
        }
        else if ( [gp isKindOfClass:[VRectangle class]] )
        {   NSPoint	o, s;

            [(VRectangle*)gp getVertices:&o :&s];
            d = o.y - ls.y;
            if (d >= 0.0 && d <= 3.0*TOLERANCE)
                o.y += 3.0*TOLERANCE;
            if (d < 0.0 && -d <= 3.0*TOLERANCE)
                o.y -= 3.0*TOLERANCE;
            d = (o.y+s.y) - ls.y; // upper line - Fix me: - - - -  rotation not checked !
            if (d >= 0.0 && d <= 3.0*TOLERANCE)
                o.y += 3.0*TOLERANCE; // we move also the origin
            if (d < 0.0 && -d <= 3.0*TOLERANCE)
                o.y -= 3.0*TOLERANCE;
            tgp = [[VRectangle allocWithZone:[self zone]] init];
            [(VRectangle*)tgp setVertices:o :s];
        }
        else if ( [gp isKindOfClass:[VArc class]] )
        {   NSPoint	p0=[(VArc*)gp pointWithNum:0], p1=[(VArc*)gp pointWithNum:MAXINT];

            tgp = [(VArc*)gp copy];

            d = p0.y - ls.y;
            if (d >= 0.0 && d <= 3.0*TOLERANCE)
                [tgp movePoint:0 by:NSMakePoint(0.0, 3.0*TOLERANCE)];
            if (d < 0.0 && -d <= 3.0*TOLERANCE)
                [tgp movePoint:0 by:NSMakePoint(0.0, -3.0*TOLERANCE)];
            d = p1.y - ls.y;
            if (d >= 0.0 && d <= 3.0*TOLERANCE)
                [tgp movePoint:MAXINT by:NSMakePoint(0.0, 3.0*TOLERANCE)];
            if (d < 0.0 && -d <= 3.0*TOLERANCE)
                [tgp movePoint:MAXINT by:NSMakePoint(0.0, -3.0*TOLERANCE)];
        }
        else if ( [gp isKindOfClass:[VPolyLine class]] )
        {   int		pCnt = [gp ptsCount];

            cnt = 0;
            pts = malloc(pCnt * sizeof(NSPoint));

            /* each line by itself */
            for (j=0; j < pCnt-1; j++)
            {   NSPoint	pl0 = [gp pointWithNum:j], pl1 = [gp pointWithNum:j+1], pt;

                /* we move the points away from our intersecting line, so we don't hit an edge */
                d = pl0.y - ls.y;
                if (d >= 0.0 && d <= 3.0*TOLERANCE)
                    pl0.y += 3.0*TOLERANCE;
                if (d < 0.0 && -d <= 3.0*TOLERANCE)
                    pl0.y -= 3.0*TOLERANCE;
                d = pl1.y - ls.y;
                if (d >= 0.0 && d <= 3.0*TOLERANCE)
                    pl1.y += 3.0*TOLERANCE;
                if (d < 0.0 && -d <= 3.0*TOLERANCE)
                    pl1.y -= 3.0*TOLERANCE;

                if (vhfIntersectLines(&pt, ls, le, pl0, pl1))
                {
                    pts[cnt++] = pt;
if (cnt >= pCnt)
    NSLog(@"'VPath.m Fuck");
                }
            }
        }

        if ( ![gp isKindOfClass:[VPolyLine class]] )
            cnt = [tgp getIntersections:&pts with:g];	/* line, arc, curve, rectangle */

        if (iCnt+cnt >= len)
            *ppArray = realloc(*ppArray, (len+=cnt*2) * sizeof(NSPoint));

        for (j=0; j<cnt; j++)
        {
            if ( !pointInArray(pts[j], *ppArray, oldCnt) )
                (*ppArray)[iCnt++] = pts[j];

            /* we need this allways - RubOut z.B. kann aufeinanderliegende linien erzeugen ! */
            else
            {   NSPoint	start, end;

                if ( [gp isKindOfClass:[VLine class]] )		/* line */
                    [(VLine*)gp getVertices:&start :&end];
                else if ( [gp isKindOfClass:[VArc class]] || [gp isKindOfClass:[VCurve class]] )
                {   start = [gp pointWithNum:0];
                    end = [gp pointWithNum:MAXINT];
                }
                else if ( [gp isKindOfClass:[VRectangle class]] )
                {   NSPoint	ur, ul, size;
                    [(VRectangle*)gp getVertices:&start :&size]; // origin size
                    end = start; end.x += size.x;
                    ul = start; ul.y += size.y;
                    ur = end; ur.y += size.y;
                    if ( (Diff(pts[j].x, ul.x) + Diff(pts[j].y, ul.y) < 10.0*TOLERANCE) ||
                         (Diff(pts[j].x, ur.x) + Diff(pts[j].y, ur.y) < 10.0*TOLERANCE) )
                        continue; // do not add
                }
                else if ( [gp isKindOfClass:[VPolyLine class]] )
                {   int	k, pCnt = [(VPolyLine*)gp ptsCount], stop = 0;

                    for (k=1; k<pCnt-1; k++)
                    {   NSPoint	pt = [(VPolyLine*)gp pointWithNum:k];
                        if ( Diff(pts[j].x, pt.x) + Diff(pts[j].y, pt.y) < 10.0*TOLERANCE )
                        {   stop = 1; break; }
                    }
                    if (stop)
                        continue; // do not add
                    [(VPolyLine*)gp getEndPoints:&start :&end];
                }
                else
                {
                    start.x = end.x = pts[j].x; start.y = end.y = pts[j].y;
                }
                /* point is no edge point of gp -> add */
                if ( (Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) > 10.0*TOLERANCE) &&
                     (Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) > 10.0*TOLERANCE) )
                    (*ppArray)[iCnt++] = pts[j];
//                else
//                    NSLog(@"VPath.m -getIntersectionsForFilling: point not added !!");
            }
        }
        if ( tgp )
            [tgp release];
        if ( cnt )
            free(pts);
        pts = 0;
    }

    if (!iCnt)
    {   free(*ppArray);
        //NSZoneFree((NSZone*)[(NSObject*)NSApp zone], *ppArray);
        *ppArray = NULL;
    }
    return iCnt;
}
#endif

/* get intersections with line segment
 */
- (int)intersectLine:(NSPoint*)pArray :(NSPoint)pl0 :(NSPoint)pl1
{   NSPoint	*pts;
    VLine	*line = [VLine lineWithPoints:pl0 :pl1];
    int		cnt;

    if ( (cnt = [self getIntersections:&pts with:line]) )
    {   free(pts);
        return cnt;
    }
    return 0;
}

#define	INFO_OK			0
#define	INFO_HORICONTAL_UP	1
#define	INFO_HORICONTAL_DOWN	2
#define	INFO_TANGENT		3
#define	INFO_EDGE_UP		4
#define	INFO_EDGE_DOWN		5

#if 0 // new
- (int)intersectionsForPtInside:(NSPoint**)ppArray :(int**)ppInfo with:g
{   int		i, j, listCnt = [list count], iCnt = 0, horicontals = 0;
    NSPoint	p0 = [g pointWithNum:0]; // allway a line !
    NSRect	gBounds = [g bounds];

    *ppArray = malloc([self numPoints] * sizeof(NSPoint));
    *ppInfo = malloc([self numPoints] * sizeof(int));
    for (i=0; i<listCnt; i++)
    {	id      gp = [list objectAtIndex:i];
        int     cnt, oldCnt = iCnt;
        NSRect  gpBounds = [gp bounds];
        NSPoint	*pts = NULL;

        if ( gp == g )
            continue;
        // check bounds
        if ( NSIsEmptyRect(NSIntersectionRect(gBounds , gpBounds)) )
            continue;

        cnt = [gp getIntersections:&pts with:g];	// line, arc, curve, rectangle
        if ( cnt == 2 &&
             ( [gp isKindOfClass:[VLine class]] ||
              ([gp isKindOfClass:[VArc class]] && pts[0].x == pts[1].x) ) )
        {   int	info0 = INFO_HORICONTAL_UP, info1 = INFO_HORICONTAL_UP;

            /* if there are two intersections with horicontal line the line of the polygon is allso horicontal */
            /* or an arc tangent */
            if ([gp isKindOfClass:[VLine class]])
            {   VGraphic    *prevG = nil, *nextG = nil;
                NSPoint     start, end, s, e;
                int         k, l;

                if (pointInArray(pts[0], *ppArray, oldCnt))
                {   /* remove all edge points */
                    for (k=0; k<oldCnt; k++)
                        if ( (*ppInfo)[k] >= INFO_EDGE_UP &&
                             SqrDistPoints(pts[0], (*ppArray)[k]) < (10.0*TOLERANCE)*(10.0*TOLERANCE) )
                        {
                            for (l=k; l<oldCnt-1; l++)
                            {   (*ppArray)[l] = (*ppArray)[l+1];
                                (*ppInfo)[l] = (*ppInfo)[l+1];
                            }
                            oldCnt--; k--; iCnt--;
                        }
                }
                if (pointInArray(pts[1], *ppArray, oldCnt))
                {   /* remove all edge points */
                    for (k=0; k<oldCnt; k++)
                        if ( (*ppInfo)[k] >= INFO_EDGE_UP &&
                             SqrDistPoints(pts[1], (*ppArray)[k]) < (10.0*TOLERANCE)*(10.0*TOLERANCE) )
                        {
                            for (l=k; l<oldCnt-1; l++)
                            {   (*ppArray)[l] = (*ppArray)[l+1];
                                (*ppInfo)[l] = (*ppInfo)[l+1];
                            }
                            oldCnt--; k--; iCnt--;
                        }
                }
                /* search prevG/nextG */
                prevG = nextG = nil;
                [(VLine*)gp getVertices:&start :&end];
                for (k=0; k<listCnt;k++)
                {   VGraphic	*gr = [list objectAtIndex:k];

                    if (k == i)
                        continue;

                    s = [gr pointWithNum:0];
                    e = [gr pointWithNum:MAXINT];
                    if (!prevG && SqrDistPoints(e, start) <= TOLERANCE) // prevG found
                        prevG = gr;
                    if (!nextG && SqrDistPoints(s, end) <= TOLERANCE) // nextG found
                        nextG = gr;
                    if (prevG && nextG)
                        break;
                }
                /* check if prevG/nextG come from up and/or down */
                if ( [prevG isKindOfClass:[VLine class]] )		/* prevG is a line */
                {   [(VLine*)prevG getVertices:&start :&end]; // horicontals are not down !
                    info0 = (start.y < pts[0].y - TOLERANCE) ? INFO_HORICONTAL_DOWN : INFO_HORICONTAL_UP;
                }
                else if ( [prevG isKindOfClass:[VArc class]] || [prevG isKindOfClass:[VCurve class]] )
                {   start = [prevG pointAt:0.85];
                    info0 = (start.y < pts[0].y) ? INFO_HORICONTAL_DOWN : INFO_HORICONTAL_UP;
                }
                else if ( [prevG isKindOfClass:[VPolyLine class]] )
                {   int		pCnt = [(VPolyLine*)prevG ptsCount];
                    NSPoint	pt = [(VPolyLine*)prevG pointWithNum:pCnt-2];

                    info0 = (pt.y < pts[0].y - TOLERANCE) ? INFO_HORICONTAL_DOWN : INFO_HORICONTAL_UP;
                }
                if ( [nextG isKindOfClass:[VLine class]] )		/* nextG is a line */
                {   [(VLine*)nextG getVertices:&start :&end]; // horicontals are not down !
                    info1 = (end.y < pts[0].y - 2.0*TOLERANCE) ? INFO_HORICONTAL_DOWN : INFO_HORICONTAL_UP;
                }
                else if ( [nextG isKindOfClass:[VArc class]] || [nextG isKindOfClass:[VCurve class]] )
                {   end = [nextG pointAt:0.15];
                    info1 = (end.y < pts[0].y) ? INFO_HORICONTAL_DOWN : INFO_HORICONTAL_UP;
                }
                else if ( [nextG isKindOfClass:[VPolyLine class]] )
                {   NSPoint	pt = [(VPolyLine*)nextG pointWithNum:1];

                    info1 = (pt.y < pts[0].y - TOLERANCE) ? INFO_HORICONTAL_DOWN : INFO_HORICONTAL_UP;
                }
                if (info0 != info1)
                    horicontals++;
            }
            (*ppArray)[iCnt] = pts[0];
            (*ppInfo)[iCnt++] = ([gp isKindOfClass:[VArc class]]) ? INFO_TANGENT : info0;
            (*ppArray)[iCnt] = pts[1];
            (*ppInfo)[iCnt++] = ([gp isKindOfClass:[VArc class]]) ? INFO_TANGENT : info1;
            if (pts)
                free(pts);
            continue;
        }
        else if ( [gp isKindOfClass:[VRectangle class]] && cnt == 2 )
        {   /* if one intersectionpoint layes on the uppest OR lowest y value of the rectangle
            * -> -1 !!! (horicontal...)
            */
            for (j=0; j<cnt; j++)
            {
                if ( (Diff(pts[j].y, gpBounds.origin.y) <= TOLERANCE) ||
                     (Diff(pts[j].y, (gpBounds.origin.y+gpBounds.size.height)) <= TOLERANCE) )
                {
                    if ( cnt > 1 )
                    {
                        (*ppArray)[iCnt].x = gpBounds.origin.x;
                        (*ppArray)[iCnt].y = pts[j].y;
                        (*ppInfo)[iCnt++] = INFO_HORICONTAL_DOWN;
                        (*ppArray)[iCnt].x = gpBounds.origin.x + gpBounds.size.width;
                        (*ppArray)[iCnt].y = pts[j].y;
                        (*ppInfo)[iCnt++] = INFO_HORICONTAL_DOWN;
                    }
                    else
                    {   (*ppArray)[iCnt] = pts[j];
                        (*ppInfo)[iCnt++] = INFO_HORICONTAL_DOWN;
                        (*ppArray)[iCnt] = pts[j];
                        (*ppInfo)[iCnt++] = INFO_HORICONTAL_DOWN;
                    }
                    free(pts);
                    continue;
                }
            }
        }
        else if ( [gp isKindOfClass:[VCurve class]] && cnt )
        {   NSPoint	p0, p1, p2, p3, tpoints[3];
            int		i, cpt, realSol=0, numSol=0, stop = 0;
            double	cy, by, ay, t[3];

            [gp getVertices:&p0 :&p1 :&p2 :&p3];
            /* we must look if one of the intersection points lying on a extrem point of the curve
                * represent the curve with the equations
                * x(t) = ax*t^3 + bx*t^2 + cx*t + x(0)
                * y(t) = ay*t^3 + by*t^2 + cy*t + y(0)
                * -> 3ay*t^2 + 2by*t + cy = 0
                */
            cy = 3*(p1.y - p0.y);
            by = 3*(p2.y - p1.y) - cy;
            ay = p3.y - p0.y - by - cy;

            /* get the ts in which the tangente is horicontal
                */
            numSol = svPolynomial2( 3.0*ay, 2.0*by, cy, t);

            /* when t is on curve */
            realSol=0;
            for ( i=0 ; i<numSol ; i++)
                if ( t[i] >= 0.0 && t[i] <= 1.0 )
                    tpoints[realSol++] = [gp pointAt:t[i]];

            /* if intersection point is a tangent point */
            for ( i=0 ; i<realSol ;i++ )
            {
                for ( cpt=0 ; cpt<cnt ; cpt++ )
                    if ( Diff(tpoints[i].x, pts[cpt].x) <= 25.0*TOLERANCE &&
                         Diff(tpoints[i].y, pts[cpt].y) <= 25.0*TOLERANCE)
                    {
                        (*ppArray)[iCnt] = pts[cpt];
                        (*ppInfo)[iCnt++] = INFO_TANGENT;
                        (*ppArray)[iCnt] = pts[cpt];
                        (*ppInfo)[iCnt++] = INFO_TANGENT;
                        if (cnt == 1)
                        {   free(pts);
                            stop = 1;
                            break;
                        }
                        else
                        {   for (j = cpt; j<cnt-1; j++)
                               pts[j] = pts[j+1];
                            cnt--; cpt--;
                        }
                    }
                    if (stop)
                        break;
            }
            if (stop)
            {   free(pts);
                continue;
            }
        }
        // polyline ?
        else if ( [gp isKindOfClass:[VPolyLine class]] && cnt )
            NSLog(@"VPath.m - intersectionsForPtInside::with:: VPolyLine not implemented");

        /* add points if not allways inside pparray
         * else check if pt is edge pt of graphic
         */
        for (j=0; j<cnt; j++)
        {   NSPoint	start, end;
            BOOL	edgePoint = NO, edgeInfo = NO;

            /* check if edge point of gp */
            /* and check if gp laying up or down the graphic */
            if ( [gp isKindOfClass:[VLine class]] )		/* line */
            {    [(VLine*)gp getVertices:&start :&end];
                if (((Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) < 10.0*TOLERANCE) &&
                     (start.y > pts[j].y /* + 2.0*TOLERANCE */)) ||
                    ((Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) < 10.0*TOLERANCE) &&
                     (end.y > pts[j].y /* + 2.0*TOLERANCE */)))
                {    edgePoint = YES; edgeInfo = INFO_EDGE_UP; }
                else if (((Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) < 10.0*TOLERANCE) &&
                          (start.y < pts[j].y /* - 2.0*TOLERANCE */)) ||
                         ((Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) < 10.0*TOLERANCE) &&
                          (end.y < pts[j].y /* - 2.0*TOLERANCE */)))
                {    edgePoint = YES; edgeInfo = INFO_EDGE_DOWN; }
                else if ((Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) < 10.0*TOLERANCE) ||
                         (Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) < 10.0*TOLERANCE))
                    NSLog(@"VPath.m -intersectionsForPtInside::with:: line is not up or down ??");
            }
            else if ( [gp isKindOfClass:[VArc class]] || [gp isKindOfClass:[VCurve class]] )
            {   start = [gp pointWithNum:0];
                end = [gp pointWithNum:MAXINT];

                if ((Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) < 10.0*TOLERANCE) ||
                    (Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) < 10.0*TOLERANCE))
                {   NSPoint	p12 = {0,0};

                    edgePoint = YES;
                    if ((Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) < 10.0*TOLERANCE))
                        p12 = [gp pointAt:0.15];	
                    else
                        p12 = [gp pointAt:0.85];
                    edgeInfo = (p12.y > pts[j].y) ? INFO_EDGE_UP : INFO_EDGE_DOWN;
                }
            }
            else if ( [gp isKindOfClass:[VRectangle class]] )
            {   NSPoint	ur, ul, size;
                [(VRectangle*)gp getVertices:&start :&size]; // origin size
                end = start; end.x += size.x;
                ul = start; ul.y += size.y;
                ur = end; ur.y += size.y;
                if ( (Diff(pts[j].x, ul.x) + Diff(pts[j].y, ul.y) < 10.0*TOLERANCE) ||
                     (Diff(pts[j].x, ur.x) + Diff(pts[j].y, ur.y) < 10.0*TOLERANCE) )
                {   edgePoint = YES;
                    edgeInfo = INFO_EDGE_DOWN;
                }
                else if ( (Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) < 10.0*TOLERANCE) &&
                          (Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) < 10.0*TOLERANCE) )
                {   edgePoint = YES;
                    edgeInfo = INFO_EDGE_UP;
                }
            }
            else if ( [gp isKindOfClass:[VPolyLine class]] )
            {   int	k, pCnt = [(VPolyLine*)gp ptsCount];
                NSPoint	pt = [(VPolyLine*)gp pointWithNum:1];

                for (k=1; k<pCnt-1; k++)
                {   NSPoint	pt = [(VPolyLine*)gp pointWithNum:k];
                    if ( Diff(pts[j].x, pt.x) + Diff(pts[j].y, pt.y) < 10.0*TOLERANCE )
                    {   NSPoint	pm1 = [(VPolyLine*)gp pointWithNum:(((k-1) < 0)?(pCnt-1):(k-1))];
                        NSPoint	pp1 = [(VPolyLine*)gp pointWithNum:(((k+1) < pCnt) ? (k+1):(0))];

                        if ((pm1.y > pts[j].y /* + 2.0*TOLERANCE */ && pp1.y > pts[j].y + 2.0*TOLERANCE) ||
                            (pm1.y < pts[j].y /* - 2.0*TOLERANCE */ && pp1.y < pts[j].y - 2.0*TOLERANCE))
                        {   edgePoint = YES; break; }
                    }
                }
                if (edgePoint == YES)
                    continue; // do not add !!!!!!!!!!!!!!

                pt = [(VPolyLine*)gp pointWithNum:1];
                [(VPolyLine*)gp getEndPoints:&start :&end];
                if (Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) < 10.0*TOLERANCE)
                {   edgePoint = YES;
                    edgeInfo = (pt.y > pts[j].y /* + 2.0*TOLERANCE */) ? INFO_EDGE_UP : INFO_EDGE_DOWN;
                }
                if (Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) < 10.0*TOLERANCE)
                {   edgePoint = YES;
                    pt = [(VPolyLine*)gp pointWithNum:pCnt-2];
                    edgeInfo = (pt.y > pts[j].y /* + 2.0*TOLERANCE */) ? INFO_EDGE_UP : INFO_EDGE_DOWN;
                }
            }
            else
                NSLog(@"VPath.m -intersectionsForPtInside::with:: unknown graphic ");

            /* point is not in array OR no edge point of gp -> add */
            if ( !pointInArray(pts[j], *ppArray, oldCnt) || edgePoint == NO )
            {   (*ppArray)[iCnt] = pts[j];
                (*ppInfo)[iCnt++] = (edgePoint == YES) ? edgeInfo : INFO_OK;
            }
            else if (edgePoint == YES) // check if prevG/curG(gp) up end down the line
            {   int	k, l;

                for (k=0; k<oldCnt; k++)
                    if ( SqrDistPoints(pts[j], (*ppArray)[k]) < (10.0*TOLERANCE)*(10.0*TOLERANCE) )
                    {
                        /* up and down - do not add second point */
                        if (((*ppInfo)[k] == INFO_EDGE_UP && edgeInfo == INFO_EDGE_DOWN) ||
                            ((*ppInfo)[k] == INFO_EDGE_DOWN && edgeInfo == INFO_EDGE_UP))
                            continue;
                        else if ((*ppInfo)[k] >= INFO_EDGE_UP) // remove only edge points from ppArray !!
                        {   /* only up or on/down remove allso other edge from point array - but horicontal points ! */
                            for (l=k; l<oldCnt-1; l++)
                            {   (*ppArray)[l] = (*ppArray)[l+1];
                                (*ppInfo)[l] = (*ppInfo)[l+1];
                            }
                            oldCnt--; k--; iCnt--;
                        }
                    }
            }
        }
        if (pts)
            free(pts);
    }
    /* sort points from left to right */
    for (i=0; i<iCnt-1; i++)
    {	int	j, jMin, info;
        float	lastDist, newDist;
        NSPoint	p;

        jMin = iCnt;
        lastDist=SqrDistPoints((*ppArray)[i], p0);
        for (j=i+1; j<iCnt; j++)
        {
            if ((newDist=SqrDistPoints((*ppArray)[j], p0)) < lastDist)
            {	lastDist = newDist;
                jMin = j;
            }
        }
        if (jMin<iCnt)
        {   p = (*ppArray)[i];
            info = (*ppInfo)[i];
            (*ppArray)[i] = (*ppArray)[jMin];
            (*ppInfo)[i] = (*ppInfo)[jMin];
            (*ppArray)[jMin] = p;
            (*ppInfo)[jMin] = info;
        }
    }

    if ((Even(horicontals) && !Even(iCnt)) || (!Even(horicontals) && Even(iCnt)))
        NSLog(@"VPath.m -intersectionsForPtInside:.with: one point less; y: %.3f, cnt: %d, hs: %d", p0.y, iCnt, horicontals);

    if (!iCnt)
    {	free(*ppArray); *ppArray = NULL;
     	free(*ppInfo);  *ppInfo  = NULL;
    }
    return iCnt;
}
#endif

/* return -1 if we hit a horicontal graphic or tangential point
 * return -2 if pt is ON a horicontal graphic or ON the tangential point
 */
- (int)intersectionsForPtInside:(NSPoint**)ppArray with:g :(NSPoint)pt
{   int		i, j, iCnt = 0, ptsCnt = Min(100, [self numPoints]);
    NSRect	gBounds = [g bounds];
    BOOL	tangential = NO;

    *ppArray = malloc(ptsCnt * sizeof(NSPoint));
    for (i=[list count]-1; i>=0; i--)
    {	id      gp = [list objectAtIndex:i];
        int     cnt, oldCnt = iCnt;
        NSRect  gpBounds = [gp bounds];
        NSPoint	*pts = NULL;

        if ( gp == g )
            continue;
        // check bounds
        if ( NSIsEmptyRect(NSIntersectionRect(gBounds, gpBounds)) )
            continue;

        cnt = [gp getIntersections:&pts with:g];	// line, arc, curve, rectangle
        if ( cnt == 2 &&
             ( [gp isKindOfClass:[VLine class]] ||
              ([gp isKindOfClass:[VArc class]] &&
               (pts[0].x == pts[1].x ||
                ((pt.x >= pts[0].x && pt.x <= pts[1].x) || (pt.x <= pts[0].x && pt.x >= pts[1].x)))) ) )
        {
            /* if there are two intersections with horicontal line the line of the polygon is allso horicontal */
            /* or an arc tangent */
            if ([gp isKindOfClass:[VLine class]] || ([gp isKindOfClass:[VArc class]] && pts[0].x == pts[1].x))
            {   tangential = YES;
                (*ppArray)[0] = pts[0];
                (*ppArray)[1] = pts[1];
            }
            if ([gp isKindOfClass:[VLine class]] &&
                ((pt.x >= pts[0].x && pt.x <= pts[1].x) || (pt.x <= pts[0].x && pt.x >= pts[1].x)))
            {   free(pts);
                return -2; // on
            }
            else if ( pts[0].x != pts[1].x &&
                      ((pt.x >= pts[0].x && pt.x <= pts[1].x) || (pt.x <= pts[0].x && pt.x >= pts[1].x)) )
            {	NSPoint	p0 = [g pointWithNum:0], p1 = [g pointWithNum:MAXINT], *aPts;
                int	aCnt = 0;

                /* we have made a sidestep */
                if (Diff(pt.y, p0.y) > TOLERANCE/2.0)
                {   VLine	*line = [VLine line];

                    p0.y = p1.y = pt.y;
                    [line setVertices:p0 :p1];
                    if (!(aCnt = [line getIntersections:&aPts with:gp]) || aCnt == 2)
                    {
                        if (!aCnt || aPts[0].x == aPts[1].x)
                        {
                            /* not inside  !! */
                            free(pts);
                            free(aPts);
                            return -1; // need a sidestep to other side !
                        }
                    }
                }
                if (aCnt)
                    free(aPts);
            }
            else if ([gp isKindOfClass:[VArc class]] && Diff(pt.x, pts[0].x) <= 5.0*TOLERANCE)
            {   free(pts);
                return -2; // on
            }
            else if ([gp isKindOfClass:[VArc class]])
            {	NSPoint	tpt = pts[0], p0 = [g pointWithNum:0], p1 = [g pointWithNum:MAXINT], *aPts;
                VLine	*line = [VLine line];
                int	aCnt = 0;

                p0.y += TOLERANCE;
                p1.y += TOLERANCE;
                [line setVertices:p0 :p1];
                aCnt = [line getIntersections:&aPts with:gp];
                if (!aCnt)
                {   p0.y -= 2.0*TOLERANCE;
                    p1.y -= 2.0*TOLERANCE;
                    [line setVertices:p0 :p1];
                    aCnt = [line getIntersections:&aPts with:gp];
                }
                if (((aCnt == 2 &&
                      ((pt.x >= aPts[0].x && pt.x <= aPts[1].x) || (pt.x <= aPts[0].x && pt.x >= aPts[1].x)))) ||
                    (aCnt == 1 &&
                     ((pt.x >= aPts[0].x && pt.x <= tpt.x) || (pt.x <= aPts[0].x && pt.x >= tpt.x))))
                {   free(pts);
                    free(aPts);
                    return -2; // on
                }
                if (aCnt)
                    free(aPts);
            }
        }
        else if ( [gp isKindOfClass:[VRectangle class]] && cnt )
        {   /* if one intersectionpoint layes on the uppest OR lowest y value of the rectangle
             * -> -1 !!! (horicontal...)
             */
            for (j=0; j<cnt; j++)
            {
                if ( (Diff(pts[j].y, gpBounds.origin.y) <= TOLERANCE) ||
                    (Diff(pts[j].y, (gpBounds.origin.y+gpBounds.size.height)) <= TOLERANCE) )
                {   //free(*ppArray); *ppArray = NULL;
                    if ( cnt > 1 )
                    {   if ( Diff(pts[j].y, gpBounds.origin.y) <= TOLERANCE )
                        {   (*ppArray)[0].x = gpBounds.origin.x;
                            (*ppArray)[1].x = gpBounds.origin.x + gpBounds.size.width;
                        }
                        else
                        {   (*ppArray)[0].x = gpBounds.origin.x;
                            (*ppArray)[1].x = gpBounds.origin.x + gpBounds.size.width;
                        }
                        (*ppArray)[0].y = (*ppArray)[1].y = pts[j].y;
                    }
                    else
                    {   (*ppArray)[0] = (*ppArray)[1] = pts[j]; }

                    if ((pt.x >= (*ppArray)[0].x && pt.x <= (*ppArray)[1].x) ||
                        (pt.x <= (*ppArray)[0].x && pt.x >= (*ppArray)[1].x))
                    {   free(pts);
                        return -2; // on
                    }
                    tangential = YES;
                }
            }
        }
        else if ( [gp isKindOfClass:[VCurve class]] && cnt )
        {   NSPoint	p0, p1, p2, p3, tpoints[3];
            int		i, cpt, realSol=0, numSol=0;
            double	cy, by, ay, t[3];

            [gp getVertices:&p0 :&p1 :&p2 :&p3];
            /* we must look if one of the intersection points lying on a extrem point of the curve
             * represent the curve with the equations
             * x(t) = ax*t^3 + bx*t^2 + cx*t + x(0)
             * y(t) = ay*t^3 + by*t^2 + cy*t + y(0)
             * -> 3ay*t^2 + 2by*t + cy = 0
             */
            cy = 3*(p1.y - p0.y);
            by = 3*(p2.y - p1.y) - cy;
            ay = p3.y - p0.y - by - cy;

            /* get the ts in which the tangente is horicontal
             */
            numSol = svPolynomial2( 3.0*ay, 2.0*by, cy, t);

            /* when t is on curve */
            realSol=0;
            for ( i=0 ; i<numSol ; i++)
                if ( t[i] >= 0.0 && t[i] <= 1.0 )
                    tpoints[realSol++] = [gp pointAt:t[i]];

            /* if one intersection point is identical with one tpoint -> -1 */
            for ( i=0 ; i<realSol ;i++ )
                for ( cpt=0 ; cpt<cnt ; cpt++ )
                    if (Diff(tpoints[i].x, pts[cpt].x) <= TOLERANCE && Diff(tpoints[i].y, pts[cpt].y) <= TOLERANCE)
                    {   //free(*ppArray);
                        //*ppArray = NULL;
                        (*ppArray)[0] = (*ppArray)[1] = pts[cpt];
                        if (Diff(pt.x, pts[cpt].x) <= TOLERANCE)
                        {   free(pts);
                            return -2; // on
                        }
                        tangential = YES;
                    }
        }
        else if ( cnt > 1 && [gp isKindOfClass:[VPolyLine class]] )
        {   int		p, nPts = [gp numPoints];
            NSPoint	pl0, pl1;

            /* check each line in PolyLine if horicontal */
            for (p=0; p < nPts-1; p++)
            {
                pl0 = [gp pointWithNum:p];
                pl1 = [gp pointWithNum:p+1];

                if (pointWithToleranceInArray(pl0, TOLERANCE, pts, cnt) && // both point are in pts
                    pointWithToleranceInArray(pl1, TOLERANCE, pts, cnt))
                {
                    tangential = YES;
                    (*ppArray)[0] = pts[0];
                    (*ppArray)[1] = pts[1];
                    if ((pt.x >= pts[0].x && pt.x <= pts[1].x) || (pt.x <= pts[0].x && pt.x >= pts[1].x))
                    {
                        free(pts);
                        return -2; // on
                    }
                }
            }
        }

        if (iCnt+cnt >= ptsCnt)
            *ppArray = realloc(*ppArray, (ptsCnt+=cnt*2) * sizeof(NSPoint));

        // add points if not allways inside pparray
        // else check if pt is edge pt of graphic -> return -1
        for (j=0; j<cnt; j++)
        {
            if ( !pointInArray(pts[j], *ppArray, oldCnt) )
                (*ppArray)[iCnt++] = pts[j];
            else
            {   NSPoint	start, end;

                if ( [gp isKindOfClass:[VLine class]] )		/* line */
                    [(VLine*)gp getVertices:&start :&end];
                else if ( [gp isKindOfClass:[VArc class]] || [gp isKindOfClass:[VCurve class]] )
                {   start = [gp pointWithNum:0];
                    end = [gp pointWithNum:MAXINT];
                }
                else if ( [gp isKindOfClass:[VRectangle class]] )
                {   NSPoint	ur, ul, size;
                    [(VRectangle*)gp getVertices:&start :&size]; // origin size
                    end = start; end.x += size.x;
                    ul = start; ul.y += size.y;
                    ur = end;   ur.y += size.y;
                    if ( (Diff(pts[j].x, ul.x) + Diff(pts[j].y, ul.y) < 10.0*TOLERANCE) ||
                        (Diff(pts[j].x, ur.x) + Diff(pts[j].y, ur.y) < 10.0*TOLERANCE) )
                        continue; // do not add
                }
                else if ( [gp isKindOfClass:[VPolyLine class]] )
                {   int	k, pCnt = [(VPolyLine*)gp ptsCount], stop = 0;

                    for (k=1; k<pCnt-1; k++)
                    {   NSPoint	pt = [(VPolyLine*)gp pointWithNum:k];
                        if ( Diff(pts[j].x, pt.x) + Diff(pts[j].y, pt.y) < 10.0*TOLERANCE )
                        {   stop = 1; break; }
                    }
                    if (stop)
                        continue; // do not add
                    [(VPolyLine*)gp getEndPoints:&start :&end];
                }
                else
                {   start.x = end.x = pts[j].x; start.y = end.y = pts[j].y;
                }
                /* point is no edge point of gp -> add */
                if ( (Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) > 10.0*TOLERANCE) &&
                     (Diff(pts[j].x, end.x)   + Diff(pts[j].y, end.y)   > 10.0*TOLERANCE) )
                    (*ppArray)[iCnt++] = pts[j];
                else
                {   (*ppArray)[0] = (*ppArray)[1] = pts[j];
                    if (Diff(pt.x, pts[j].x) <= TOLERANCE)
                    {   free(pts);
                        return -2; // on
                    }
                    tangential = YES;
                }
            }
        }
        if (pts)
            free(pts);
    }
    if (!iCnt)
    {	free(*ppArray);
        *ppArray = NULL;
    }
    else if (tangential)
        return -1;
    return iCnt;
}

- (int)intersectionsForPtInside:(NSPoint**)ppArray with:g :(NSPoint)pt subPath:(int)begIx :(int)endIx
{   int		i, j, iCnt = 0, ptsCnt = Min(100, [self numPoints]);
    NSRect	gBounds = [g bounds];
    BOOL	tangential = NO;

    *ppArray = malloc(ptsCnt * sizeof(NSPoint));
    for (i=endIx; i>=begIx; i--)
    {	id	gp = [list objectAtIndex:i];
        int	cnt, oldCnt = iCnt;
        NSRect	gpBounds = [gp bounds];
        NSPoint	*pts = NULL;

        if ( gp == g )
            continue;
        // check bounds
        if ( NSIsEmptyRect(NSIntersectionRect(gBounds, gpBounds)) )
            continue;

        cnt = [gp getIntersections:&pts with:g];	// line, arc, curve, rectangle
        if ( cnt == 2 &&
             ( [gp isKindOfClass:[VLine class]] ||
              ([gp isKindOfClass:[VArc class]] &&
               (pts[0].x == pts[1].x ||
                ((pt.x >= pts[0].x && pt.x <= pts[1].x) || (pt.x <= pts[0].x && pt.x >= pts[1].x)))) ) )
        {
            /* if there are two intersections with horicontal line the line of the polygon is allso horicontal */
            /* or an arc tangent */
            if ([gp isKindOfClass:[VLine class]] || ([gp isKindOfClass:[VArc class]] && pts[0].x == pts[1].x))
            {   tangential = YES;
                (*ppArray)[0] = pts[0];
                (*ppArray)[1] = pts[1];
            }
            if ([gp isKindOfClass:[VLine class]] &&
                ((pt.x >= pts[0].x && pt.x <= pts[1].x) || (pt.x <= pts[0].x && pt.x >= pts[1].x)))
            {   free(pts);
                return -2; // on
            }
            else if ( pts[0].x != pts[1].x &&
                      ((pt.x >= pts[0].x && pt.x <= pts[1].x) || (pt.x <= pts[0].x && pt.x >= pts[1].x)) )
            {	NSPoint	p0 = [g pointWithNum:0], p1 = [g pointWithNum:MAXINT], *aPts;
                int	aCnt = 0;

                /* we have made a sidestep */
                if (Diff(pt.y, p0.y) > TOLERANCE/2.0)
                {   VLine	*line = [VLine line];

                    p0.y = p1.y = pt.y;
                    [line setVertices:p0 :p1];
                    if (!(aCnt = [line getIntersections:&aPts with:gp]) || aCnt == 2)
                    {
                        if (!aCnt || aPts[0].x == aPts[1].x)
                        {
                            /* not inside  !! */
                            free(pts);
                            free(aPts);
                            return -1; // need a sidestep to other side !
                        }
                    }
                }
                if (aCnt)
                    free(aPts);
            }
            else if ([gp isKindOfClass:[VArc class]] && Diff(pt.x, pts[0].x) <= 5.0*TOLERANCE)
            {   free(pts);
                return -2; // on
            }
            else if ([gp isKindOfClass:[VArc class]])
            {	NSPoint	tpt = pts[0], p0 = [g pointWithNum:0], p1 = [g pointWithNum:MAXINT], *aPts;
                VLine	*line = [VLine line];
                int	aCnt = 0;

                p0.y += TOLERANCE;
                p1.y += TOLERANCE;
                [line setVertices:p0 :p1];
                aCnt = [line getIntersections:&aPts with:gp];
                if (!aCnt)
                {   p0.y -= 2.0*TOLERANCE;
                    p1.y -= 2.0*TOLERANCE;
                    [line setVertices:p0 :p1];
                    aCnt = [line getIntersections:&aPts with:gp];
                }
                if (((aCnt == 2 &&
                      ((pt.x >= aPts[0].x && pt.x <= aPts[1].x) || (pt.x <= aPts[0].x && pt.x >= aPts[1].x)))) ||
                    (aCnt == 1 &&
                     ((pt.x >= aPts[0].x && pt.x <= tpt.x) || (pt.x <= aPts[0].x && pt.x >= tpt.x))))
                {   free(pts);
                    free(aPts);
                    return -2; // on
                }
                if (aCnt)
                    free(aPts);
            }
        }
        else if ( [gp isKindOfClass:[VRectangle class]] && cnt )
        {   /* if one intersectionpoint layes on the uppest OR lowest y value of the rectangle
             * -> -1 !!! (horicontal...)
             */
            for (j=0; j<cnt; j++)
            {
                if ( (Diff(pts[j].y, gpBounds.origin.y) <= TOLERANCE) ||
                    (Diff(pts[j].y, (gpBounds.origin.y+gpBounds.size.height)) <= TOLERANCE) )
                {   //free(*ppArray); *ppArray = NULL;
                    if ( cnt > 1 )
                    {   if ( Diff(pts[j].y, gpBounds.origin.y) <= TOLERANCE )
                        {   (*ppArray)[0].x = gpBounds.origin.x;
                            (*ppArray)[1].x = gpBounds.origin.x + gpBounds.size.width;
                        }
                        else
                        {   (*ppArray)[0].x = gpBounds.origin.x;
                            (*ppArray)[1].x = gpBounds.origin.x + gpBounds.size.width;
                        }
                        (*ppArray)[0].y = (*ppArray)[1].y = pts[j].y;
                    }
                    else
                    {   (*ppArray)[0] = (*ppArray)[1] = pts[j]; }

                    if ((pt.x >= (*ppArray)[0].x && pt.x <= (*ppArray)[1].x) ||
                        (pt.x <= (*ppArray)[0].x && pt.x >= (*ppArray)[1].x))
                    {   free(pts);
                        return -2; // on
                    }
                    tangential = YES;
                }
            }
        }
        else if ( [gp isKindOfClass:[VCurve class]] && cnt )
        {   NSPoint	p0, p1, p2, p3, tpoints[3];
            int		i, cpt, realSol=0, numSol=0;
            double	cy, by, ay, t[3];

            [gp getVertices:&p0 :&p1 :&p2 :&p3];
            /* we must look if one of the intersection points lying on a extrem point of the curve
             * represent the curve with the equations
             * x(t) = ax*t^3 + bx*t^2 + cx*t + x(0)
             * y(t) = ay*t^3 + by*t^2 + cy*t + y(0)
             * -> 3ay*t^2 + 2by*t + cy = 0
             */
            cy = 3*(p1.y - p0.y);
            by = 3*(p2.y - p1.y) - cy;
            ay = p3.y - p0.y - by - cy;

            /* get the ts in which the tangente is horicontal
             */
            numSol = svPolynomial2( 3.0*ay, 2.0*by, cy, t);

            /* when t is on curve */
            realSol=0;
            for ( i=0 ; i<numSol ; i++)
                if ( t[i] >= 0.0 && t[i] <= 1.0 )
                    tpoints[realSol++] = [gp pointAt:t[i]];

            /* if one intersection point is identical with one tpoint -> -1 */
            for ( i=0 ; i<realSol ;i++ )
                for ( cpt=0 ; cpt<cnt ; cpt++ )
                    if (Diff(tpoints[i].x, pts[cpt].x) <= TOLERANCE && Diff(tpoints[i].y, pts[cpt].y) <= TOLERANCE)
                    {   //free(*ppArray);
                        //*ppArray = NULL;
                        (*ppArray)[0] = (*ppArray)[1] = pts[cpt];
                        if (Diff(pt.x, pts[cpt].x) <= TOLERANCE)
                        {   free(pts);
                            return -2; // on
                        }
                        tangential = YES;
                    }
        }
        else if ( cnt > 1 && [gp isKindOfClass:[VPolyLine class]] )
        {   int		p, nPts = [gp numPoints];
            NSPoint	pl0, pl1;

            /* check each line in PolyLine if horicontal */
            for (p=0; p < nPts-1; p++)
            {
                pl0 = [gp pointWithNum:p];
                pl1 = [gp pointWithNum:p+1];

                if (pointWithToleranceInArray(pl0, TOLERANCE, pts, cnt) && // both point are in pts
                    pointWithToleranceInArray(pl1, TOLERANCE, pts, cnt))
                {
                    tangential = YES;
                    (*ppArray)[0] = pts[0];
                    (*ppArray)[1] = pts[1];
                    if ((pt.x >= pts[0].x && pt.x <= pts[1].x) || (pt.x <= pts[0].x && pt.x >= pts[1].x))
                    {
                        free(pts);
                        return -2; // on
                    }
                }
            }
        }

        if (iCnt+cnt >= ptsCnt)
            *ppArray = realloc(*ppArray, (ptsCnt+=cnt*2) * sizeof(NSPoint));

        // add points if not allways inside pparray
        // else check if pt is edge pt of graphic -> return -1
        for (j=0; j<cnt; j++)
        {
            if ( !pointInArray(pts[j], *ppArray, oldCnt) )
                (*ppArray)[iCnt++] = pts[j];
            else
            {   NSPoint	start, end;

                if ( [gp isKindOfClass:[VLine class]] )		/* line */
                    [(VLine*)gp getVertices:&start :&end];
                else if ( [gp isKindOfClass:[VArc class]] || [gp isKindOfClass:[VCurve class]] )
                {   start = [gp pointWithNum:0];
                    end = [gp pointWithNum:MAXINT];
                }
                else if ( [gp isKindOfClass:[VRectangle class]] )
                {   NSPoint	ur, ul, size;
                    [(VRectangle*)gp getVertices:&start :&size]; // origin size
                    end = start; end.x += size.x;
                    ul = start; ul.y += size.y;
                    ur = end;   ur.y += size.y;
                    if ( (Diff(pts[j].x, ul.x) + Diff(pts[j].y, ul.y) < 10.0*TOLERANCE) ||
                        (Diff(pts[j].x, ur.x) + Diff(pts[j].y, ur.y) < 10.0*TOLERANCE) )
                        continue; // do not add
                }
                else if ( [gp isKindOfClass:[VPolyLine class]] )
                {   int	k, pCnt = [(VPolyLine*)gp ptsCount], stop = 0;

                    for (k=1; k<pCnt-1; k++)
                    {   NSPoint	pt = [(VPolyLine*)gp pointWithNum:k];
                        if ( Diff(pts[j].x, pt.x) + Diff(pts[j].y, pt.y) < 10.0*TOLERANCE )
                        {   stop = 1; break; }
                    }
                    if (stop)
                        continue; // do not add
                    [(VPolyLine*)gp getEndPoints:&start :&end];
                }
                else
                {   start.x = end.x = pts[j].x; start.y = end.y = pts[j].y;
                }
                /* point is no edge point of gp -> add */
                if ( (Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) > 10.0*TOLERANCE) &&
                     (Diff(pts[j].x, end.x)   + Diff(pts[j].y, end.y)   > 10.0*TOLERANCE) )
                    (*ppArray)[iCnt++] = pts[j];
                else
                {   (*ppArray)[0] = (*ppArray)[1] = pts[j];
                    if (Diff(pt.x, pts[j].x) <= TOLERANCE)
                    {   free(pts);
                        return -2; // on
                    }
                    tangential = YES;
                }
            }
        }
        if (pts)
            free(pts);
    }
    if (!iCnt)
    {	free(*ppArray);
        *ppArray = NULL;
    }
    else if (tangential)
        return -1;
    return iCnt;
}

- (float)sqrDistanceGraphic:g
{   int		i;
    float	dist, distance = MAXCOORD;

    for (i=[list count]-1; i>=0; i--)
    {	id	gp = [list objectAtIndex:i];

        if ( (dist=[gp sqrDistanceGraphic:g]) < distance)
            distance = dist;
    }
    return distance;
}

- (float)distanceGraphic:g
{   float	distance;

    distance = [self sqrDistanceGraphic:g];
    return sqrt(distance);
}

- (BOOL)isPointInside:(NSPoint)p
{   int	iVal=0;

    return ( !(iVal=[self isPointInsideOrOn:p dist: TOLERANCE]) || iVal == 1 ) ? NO : YES;
}

/*- (BOOL)isPointInside:(NSPoint)p
{
    return ([self isPointInside:p dist:TOLERANCE]) ? YES : NO;
}*/

- (int)isPointInsideOrOn:(NSPoint)p
{
    return [self isPointInsideOrOn:p dist:TOLERANCE];
}

/* return
 * 0 = outside
 * 1 = on
 * 2 = inside
 */
#if 0 // new !!!!!!
- (int)isPointInsideOrOn:(NSPoint)p dist:(float)dist
{   int		i, cnt, leftCnt=0, *info, horicontals = 0, hStart_upDown = -1;
    BOOL	hStart = NO;
    NSPoint	p0, p1, *pts = NULL;
    VLine	*line;
    NSRect	bRect;

    bRect = [self coordBounds];

    line = [VLine line];
    p0.x = bRect.origin.x - 2000.0; p1.x = bRect.origin.x + bRect.size.width+2000.0;
    p0.y = p1.y = p.y;

    [line setVertices:p0 :p1];
    if ( !(cnt = [self intersectionsForPtInside:&pts :&info with:line]) )
        return 0; // outside

    hStart = NO;
    for (i=0; i<cnt; i++)	/* count points left of p */
    {
        if (Diff(pts[i].x, p.x) <= dist) // *7.0
        {   free(pts);
            free(info);
            return 1; // on
        }
        if (pts[i].x < p.x)
        {    leftCnt++;
            if (hStart == NO && (info[i] == INFO_HORICONTAL_UP || info[i] == INFO_HORICONTAL_DOWN))
            {   hStart = YES;
                hStart_upDown = info[i];
            }
            else if (hStart == YES && (info[i] == INFO_HORICONTAL_UP || info[i] == INFO_HORICONTAL_DOWN))
            {   hStart = NO;
                if (hStart_upDown != info[i])
                    horicontals++; // only changes from up to down change the even/odd creteria
            }
        }
        else
            break;
    }
    if (pts)
        free(pts);
    if (info)
        free(info);

    if (hStart == YES)
        return 1; // on

    /* odd number of points on the left and p is inside the polygon */
    /* inside : outside */
    return ((Even(horicontals) && Even(leftCnt)) || (!Even(horicontals) && !Even(leftCnt))) ? 0 : 2;
}
#endif

//#if 0 // original
/* return
 * 0 = outside
 * 1 = on
 * 2 = inside
 */
- (int)isPointInsideOrOn:(NSPoint)p dist:(float)dist
{   int		i, cnt, leftCnt=0, iByBreak = 0;
    NSPoint	p0, p1, *pts = NULL;
    VLine	*line;
    NSRect	bRect;

    bRect = [self coordBounds];
//    if ( !NSPointInRect(p , bRect) )
//        return 0;

    line = [VLine line];
    p0.x = bRect.origin.x - 2000.0; p1.x = bRect.origin.x + bRect.size.width+2000.0;
    p0.y = p1.y = p.y;

    for (i=2; i<16; i++)	/* we need to find a position where we don't hit an edge */
    {
        [line setVertices:p0 :p1];
        p0.y = p1.y = p.y + ((i%2) ? (-i*(TOLERANCE/2.0)) : (i*(TOLERANCE/2.0))); // i*(TOLERANCE/2.0);
        if ( !(cnt = [self intersectionsForPtInside:&pts with:line :p]) && i==2 )
            return 0;
        if ( i == 2 && cnt == -2 )
        {
            /* we checked all horicontals in this range if point is on ! */
            free(pts);
            return 1; // on
        }
        if ( cnt && Even(cnt) )
        {   if ( i != 2 )
                iByBreak = i;// /2.0;
            break;
        }
        if (pts)
        {   free(pts); pts = NULL;
        }
    }
    if ( cnt <= 1 || !Even(cnt) )	/* we hit an edge */
    {	if (cnt > 0)
            NSLog(@"VPath, -isPointInside: hit edge! p: %.3f %.3f cnt: %i", p.x, p.y, cnt);
        if (pts)
            free(pts);
        return 0;
    }
    sortPointArray(pts, cnt, p0);	/* sort from left to right */

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    /* p is on the border of the polygon
     */
    for (i=0; i<cnt; i++)	// on polygon 
        if ( Diff(pts[i].x, p.x) <= dist+(iByBreak*TOLERANCE) ) // *7.0
        {   free(pts);
            return 1;
//            return 0; // on meens not inside !
        }

    for (i=0; i<cnt && pts[i].x < p.x; i++)	/* count points left of p */
        leftCnt++;

    if (pts)
        free(pts);

    /* p is at the top or at the bottom of the polygon
     */
    if ( !Even(leftCnt) && (Diff(bRect.origin.y, p.y) <= dist*1.5
                           || Diff(bRect.origin.y+bRect.size.height, p.y) <= dist*1.5) )
        return 1;
//        return 0; // on meens not inside !

    return (Even(leftCnt)) ? 0 : 2;	/* odd number of points on the left and p is inside the polygon */
}

/* return
 * 0 = outside
 * 1 = on
 * 2 = inside
 */
- (int)isPointInsideOrOn:(NSPoint)p dist:(float)dist subPath:(int)begIx :(int)endIx
{   int		i, cnt, leftCnt=0, iByBreak = 0;
    NSPoint	p0, p1, *pts = NULL;
    VLine	*line;
    NSRect	bRect;

    bRect = [self coordBoundsOfSubPath:begIx :endIx];
//    if ( !NSPointInRect(p , bRect) )
//        return 0;

    line = [VLine line];
    p0.x = bRect.origin.x - 2000.0; p1.x = bRect.origin.x + bRect.size.width+2000.0;
    p0.y = p1.y = p.y;

    for (i=2; i<16; i++)	/* we need to find a position where we don't hit an edge */
    {
        [line setVertices:p0 :p1];
        p0.y = p1.y = p.y + ((i%2) ? (-i*(TOLERANCE/2.0)) : (i*(TOLERANCE/2.0))); // i*(TOLERANCE/2.0);
        if ( !(cnt = [self intersectionsForPtInside:&pts with:line :p subPath:begIx :endIx]) && i==2 )
            return 0;
        if ( i == 2 && cnt == -2 )
        {
            /* we checked all horicontals in this range if point is on ! */
            free(pts);
            return 1; // on
        }
        if ( cnt && Even(cnt) )
        {   if ( i != 2 )
                iByBreak = i;// /2.0;
            break;
        }
        if (pts)
        {   free(pts); pts = NULL;
        }
    }
    if ( cnt <= 1 || !Even(cnt) )	/* we hit an edge */
    {	if (cnt > 0)
            NSLog(@"VPath, -isPointInside: hit edge! p: %.3f %.3f cnt: %i", p.x, p.y, cnt);
        if (pts)
            free(pts);
        return 0;
    }
    sortPointArray(pts, cnt, p0);	/* sort from left to right */

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    /* p is on the border of the polygon
     */
    for (i=0; i<cnt; i++)	// on polygon 
        if ( Diff(pts[i].x, p.x) <= dist+(iByBreak*TOLERANCE) ) // *7.0
        {   free(pts);
            return 1;
//            return 0; // on meens not inside !
        }

    for (i=0; i<cnt && pts[i].x < p.x; i++)	/* count points left of p */
        leftCnt++;

    if (pts)
        free(pts);

    /* p is at the top or at the bottom of the polygon
     */
    if ( !Even(leftCnt) && (Diff(bRect.origin.y, p.y) <= dist*1.5
                           || Diff(bRect.origin.y+bRect.size.height, p.y) <= dist*1.5) )
        return 1;
//        return 0; // on meens not inside !

    return (Even(leftCnt)) ? 0 : 2;	/* odd number of points on the left and p is inside the polygon */
}

//#endif
#if 0
- (int)isPointInside:(NSPoint)p dist:(float)dist
{   int		i, cnt, leftCnt=0;
    NSPoint	p0, p1, *pts = NULL;
    VLine	*line;
    NSRect	bRect;

    bRect = [self coordBounds];
    if ( !NSPointInRect(p , bRect) )
        return 0;

    line = [VLine line];
    p0.x = bRect.origin.x - 2000.0; p1.x = bRect.origin.x + bRect.size.width+2000.0;
    p0.y = p1.y = p.y;

    for (i=0; i<10; i++)	/* we need to find a position where we don't hit an edge */
    {
        [line setVertices:p0 :p1];
        p0.y = p1.y = p0.y + 10.0*TOLERANCE;
        if ( !(cnt = [self getIntersections:&pts with:line]) )
            return 0;
        sortPointArray(pts, cnt, p0);	/* sort from left to right */
        if ( Even(cnt) )
            break;
    }
    if ( cnt <= 1 || !Even(cnt) )	/* we hit an edge */
    {	NSLog(@"VPath, -isPointInside: hit edge!");
        if (pts)
            free(pts);
        return 0;
    }


    /* p is on the border of the polygon
     */
    for (i=0; i<cnt; i++)	/* on polygon */
        if ( DiffPoint(pts[i], p) <= dist )
        {   free(pts);
            return 1;
        }

    for (i=0; i<cnt && pts[i].x < p.x; i++)	/* count points left of p */
        leftCnt++;

    if (pts)
        free(pts);

    /* p is at the top or at the bottom of the polygon
     */
    if ( !Even(leftCnt) && (Diff(bRect.origin.y, p.y)<=dist || Diff(bRect.origin.y+bRect.size.height, p.y)<=dist) )
        return 1;

    return (Even(leftCnt)) ? 0 : 2;	/* odd number of points on the left and p is inside the polygon */
}
#endif

/* created:  1996-10-03
 * modified: 2001-04-10
 * check for all endpoints of the path, whether a point of our Array is on an endpoint
 */
- (BOOL)pointArrayHitsCorner:(NSPoint*)pts :(int)ptsCnt
{   int	i;

    for (i=[list count]-1; i>=0; i--)
    {	id	obj = [list objectAtIndex:i];
        NSPoint	p;

        [obj getPoint:&p at:0];	/* start point */
        if (pointWithToleranceInArray(p, 0.003, pts, ptsCnt)) /* was 0.03 */
            return YES;
        [obj getPoint:&p at:3];	/* end point */
        if (pointWithToleranceInArray(p, 0.003, pts, ptsCnt)) /* was 0.03 */
            return YES;
    }

    return NO;
}

- (id)clippedWithRect:(NSRect)rect
{
    return [self clippedWithRect:rect close:NO];
}
- (id)clippedWithRect:(NSRect)rect close:(BOOL)close
{   NSMutableArray	*clipList = [NSMutableArray array];
    id			cObj;
    NSArray		*cList;
    int			i, cnt, c, cCnt;
    VPath		*path;

    /* clip objects */
    for (i=0, cnt = [list count]; i<cnt; i++)
    {
        if (!(cObj = [[list objectAtIndex:i] clippedWithRect:rect]))
            continue;
        if ([cObj isMemberOfClass:[VGroup class]])
        {
            cList = [cObj list];
            for (c=0, cCnt = [cList count]; c<cCnt; c++)
                [clipList addObject:[cList objectAtIndex:c]];
        }
        else
            [clipList addObject:cObj];
    }

    if (![clipList count])
        return nil;

    path = [VPath path];
    if (close)
    {   VRectangle	*rectangle = [VRectangle rectangle];
        NSArray		*splitList;

        [rectangle setVertices:rect.origin :NSMakePoint(rect.size.width, rect.size.height)];

        /* clip rectangle and add parts of rectangle which are inside path */
        if ( [(splitList = [rectangle getListOfObjectsSplittedFromGraphic:self]) count] > 1 )
            for (i=0; i<(int)[splitList count]; i++)
                if ( [self isPointInside:[[splitList objectAtIndex:i] pointAt:0.5]] )
                    [clipList addObject:[splitList objectAtIndex:i]];

        /* optimize */
        [path setList:clipList];
        [path sortList];
    }
    else
        [path setList:clipList];

    return path;
}

- getIntersectionsAndSplittedObjects:(NSPoint**)ppArray :(int*)iCnt with:g
{   int                 i, j, lCnt = [list count], ptsCnt = Min(100, [self numPoints]);
    NSRect              gBounds = [g bounds];
    NSMutableArray      *splitList = [NSMutableArray array], *spList = nil;
    NSAutoreleasePool   *pool = [NSAutoreleasePool new];

    *iCnt = 0;
    *ppArray = malloc(ptsCnt * sizeof(NSPoint));
//    for (i=[list count]-1; i>=0; i--)
    for (i=0; i<lCnt; i++)
    {	id      gp = [list objectAtIndex:i];
        int     cnt, oldCnt = *iCnt;
        NSRect	gpBounds = [gp bounds];
        NSPoint *pts = NULL;

        if ( gp == g )
            continue;
        // check bounds
        if ( NSIsEmptyRect(NSIntersectionRect(gBounds , gpBounds)) )
        {
            // add to splitList
            [splitList addObject:[[gp copy] autorelease]];
            continue;
        }
        /* line, arc, curve */
        if ( !(cnt = [gp getIntersections:&pts with:g]) )
            [splitList addObject:[[gp copy] autorelease]];
        else
        {   spList = [gp getListOfObjectsSplittedFrom:pts :cnt];
            if ( spList )
            {   for ( j=0; j<(int)[spList count]; j++ )
                    [splitList addObject:[spList objectAtIndex:j]];
            }
            else
                [splitList addObject:[[gp copy] autorelease]];
        }
        if ((*iCnt)+cnt >= ptsCnt)
            *ppArray = realloc(*ppArray, (ptsCnt+=cnt*2) * sizeof(NSPoint));

        for (j=0; j<cnt; j++)
        {
            if ( !pointInArray(pts[j], *ppArray, oldCnt) )
                (*ppArray)[(*iCnt)++] = pts[j];
            else
            {   NSPoint	start, end;

                if ( [gp isKindOfClass:[VLine class]] )		/* line */
                    [(VLine*)gp getVertices:&start :&end];
                else if ( [gp isKindOfClass:[VArc class]] || [gp isKindOfClass:[VCurve class]] )
                {   start = [gp pointWithNum:0];
                    end = [gp pointWithNum:MAXINT];
                }
                else if ( [gp isKindOfClass:[VRectangle class]] )
                {   NSPoint	ur, ul, size;
                    [(VRectangle*)gp getVertices:&start :&size]; // origin size
                    end = start; end.x += size.x;
                    ul = start; ul.y += size.y;
                    ur = end; ur.y += size.y;
                    if ( (Diff(pts[j].x, ul.x) + Diff(pts[j].y, ul.y) < 10.0*TOLERANCE) ||
                        (Diff(pts[j].x, ur.x) + Diff(pts[j].y, ur.y) < 10.0*TOLERANCE) )
                        continue; // do not add
                }
                else if ( [gp isKindOfClass:[VPolyLine class]] )
                {   int	k, pCnt = [(VPolyLine*)gp ptsCount], stop = 0;

                    for (k=1; k<pCnt-1; k++)
                    {   NSPoint	pt = [(VPolyLine*)gp pointWithNum:k];
                        if ( Diff(pts[j].x, pt.x) + Diff(pts[j].y, pt.y) < 10.0*TOLERANCE )
                        {   stop = 1; break; }
                    }
                    if (stop)
                        continue; // do not add
                    [(VPolyLine*)gp getEndPoints:&start :&end];
                }
                else
                {   start.x = end.x = pts[j].x; start.y = end.y = pts[j].y;
                }
                /* point is no edge point of gp -> add */
                if ( (Diff(pts[j].x, start.x) + Diff(pts[j].y, start.y) > 10.0*TOLERANCE) &&
                    (Diff(pts[j].x, end.x) + Diff(pts[j].y, end.y) > 10.0*TOLERANCE) )
                    (*ppArray)[(*iCnt)++] = pts[j];
            }
        }
        if (pts)
            free(pts);
    }

    if (!(*iCnt))
    {	free(*ppArray);
        *ppArray = NULL;
    }
    [pool release];
    if ( [splitList count] > [list count] )
        return splitList;
    return nil;
}

/* optimize list from uniteWith with same tolerance - we did not close gaps here ???
 */
- (void)optimizeList:(NSMutableArray*)olist
{   int		k, i1, i2, changeI, startIndex = 0;
    float	startDistance=MAXCOORD, d1, d2;
    float	tol = 10.0*TOLERANCE;
    NSPoint	s1, e1, s2, e2;

    if ( ![olist count] )
        return;

    for (i1 = 0; i1<(int)[olist count]-1; i1++)
    {	VGraphic	*g1 = [olist objectAtIndex:i1];
        int		closeK = -1;
	BOOL		changeDirection = NO;

        startDistance = MAXCOORD;
        changeI = i1+1;
        s1 = [g1 pointWithNum:0];
        e1 = [g1 pointWithNum:MAXINT];
        for (i2 = i1+1; i2 < (int)[olist count]; i2++)
        {   VGraphic	*g2 = [olist objectAtIndex:i2];

            s2 = [g2 pointWithNum:0];
            e2 = [g2 pointWithNum:MAXINT];
            d1 = SqrDistPoints(e1, s2); d2 = SqrDistPoints(e1, e2);
            if ( d1 < startDistance || d2 < startDistance )
            {
                if ( d2 < d1 )
                {   startDistance = d2;
                    changeDirection = YES;
                }
                else
                {   startDistance = d1;
                    changeDirection = NO;
                }
                changeI = i2;
                if ( startDistance < TOLERANCE*TOLERANCE )
                    break;
            }
        }
        closeK = changeI;
        /* if the nearest element is not the next_in_list */
        /* search until connected part end - in both directions ! */
        if (changeI != (i1+1) && changeDirection) // search backward
        {   NSPoint	prevS = e1; // first k == j == startPt

            for ( k=changeI; k >= i1+1; k-- )
            {   VGraphic	*gk;
                NSPoint		sk, ek;

                gk = [olist objectAtIndex:k];
                sk = [gk pointWithNum:0];
                ek = [gk pointWithNum:MAXINT];

                if (SqrDistPoints(prevS, ek) >= tol*tol || k == i1+1)
                {   closeK = (k == i1+1 || k == changeI) ? k : (k+1);
                    break; // end of connected part
                }
                prevS = sk;
            }

        }
        else if (changeI != (i1+1)) // search forward
        {   NSPoint	prevE = e1;

            for ( k=changeI; k < [olist count]; k++ )
            {   VGraphic	*gk;
                NSPoint		sk, ek;

                gk = [olist objectAtIndex:k];
                sk = [gk pointWithNum:0];
                ek = [gk pointWithNum:MAXINT];

                if (SqrDistPoints(prevE, sk) >= tol*tol || k == [olist count]-1)
                {   closeK = (k == [olist count]-1 || k == changeI) ? k : (k-1);
                    break; // end of connected part
                }
                prevE = ek;
            }
        }

        if ( startDistance > TOLERANCE*TOLERANCE ) /* close hole */
        {   VGraphic	*g2;
            float	dist = MAXCOORD;

            g2 = [olist objectAtIndex:( startDistance <= tol*tol ) ? changeI : startIndex];
            if ( startDistance <= tol*tol && changeDirection)
            {   s2 = [g2 pointWithNum:MAXINT];
                e2 = [g2 pointWithNum:0];
            }
            else
            {   s2 = [g2 pointWithNum:0];
                e2 = [g2 pointWithNum:MAXINT];
            }
            if ( (dist=SqrDistPoints(e1, s2)) > TOLERANCE*TOLERANCE && dist <= tol*tol )
            {	VGraphic	*lineG = [VLine line];

                [(VLine*)lineG setVertices:e1 :s2];
                [olist insertObject:lineG atIndex:i1+1];
                i1 += 1; changeI += 1; closeK += 1;
            }
            if ( startDistance > tol*tol )
            {
                /* g2 is start graphic ! if ( startDistance > tol*tol ) */
                //if ( dist > tol*tol )
                    //NSLog(@"VPath.m: -optimizeList: distance: s: %.3f %.3f e: %.3f %.3f", s1.x, s1.y, e1.x, e1.y);
                startIndex = i1+1;
            }
        }

        if ( changeI != (i1+1) && startDistance < tol*tol)
        {   int	m, insertCnt = 0, from = changeI, to = closeK;

            if (changeDirection)
            {
                for (m=to; m <= from; m++)
                {   VGraphic	*g = [olist objectAtIndex:m];

                    [g changeDirection];
                    if (m != i1+1)
                    {   [olist insertObject:g atIndex:i1+1];
                        [olist removeObjectAtIndex:m+1];
                    }
                }
            }
            else
            {   for (m=to; m >= from; m--)
                {   VGraphic	*g = [olist objectAtIndex:m+insertCnt];

                    [olist insertObject:g atIndex:i1+1];
                    insertCnt++;
                    [olist removeObjectAtIndex:m+insertCnt];
                }
            }
            if (insertCnt)
                i1 += insertCnt-1;
        }
        else if (changeDirection && startDistance < tol*tol) // else we destroy our sorted blocks !
        {   VGraphic	*g2 = [olist objectAtIndex:changeI];

            [g2 changeDirection];
        }
    }
    /* close hole from last to start element */
    if ([olist count] > 1)
    {   VGraphic	*g1=[olist objectAtIndex:[olist count]-1];
        VGraphic	*g2= [olist objectAtIndex:startIndex];
        float		dist = MAXCOORD;

        s1 = [g1 pointWithNum:0];
        e1 = [g1 pointWithNum:MAXINT];
        s2 = [g2 pointWithNum:0];
        e2 = [g2 pointWithNum:MAXINT];
        if ( (dist=SqrDistPoints(e1, s2)) > TOLERANCE*TOLERANCE && dist <= tol+tol )
        {   VGraphic	*lineG = [VLine line];

            [(VLine*)lineG setVertices:e1 :s2];
            [olist addObject:lineG];
        }
        //else if ( dist > TOLERANCE*TOLERANCE )
        //    NSLog(@"VPath.m: -optimizeList: distance 2: s: %.3f %.3f e: %.3f %.3f", s1.x, s1.y, e1.x, e1.y);
    }
    return;
}
/* unite
 * returns a new graphic or nil
 *
 * modified: 2006-01-11 2008-10-16
 */
- uniteWith:(id)ug
{   int			i, j = 0, k, l, endIx=0, uStartIs[1000], startI, listCnt, uStartIsCnt = 0, uListCnt;
    int			sPairsCnt = 0, ePairsCnt = 0, sPairsCnts[500], ePairsCnts[500];
    int			removedFromUg = 0, removedFromNg = 0, sCnt=0, eCnt=0, startIs[1000], endIs[1000];
    float		tol = 20.0*TOLERANCE;
    VPath		*ng;
    NSMutableArray	*splitListG, *splitListUg;
    NSPoint		p, startPts[1000], endPts[1000];   // start/end point of removed graphic(s)
    BOOL		first = YES, removing = NO;
    NSAutoreleasePool	*pool;
    NSPoint             gPrevE = NSZeroPoint;

    if ( ![ug isKindOfClass:[VPath class]] && ![ug isKindOfClass:[VArc class]] && ![ug isKindOfClass:[VPolyLine class]]
        && ![ug isKindOfClass:[VRectangle class]] && ![ug isKindOfClass:[VGroup class]] )
        return nil;

    ng = [VPath path];
    [ng setColor:[self color]];
    [ng setFillColor:[self fillColor]];
    [ng setEndColor:[self endColor]];
    [ng setRadialCenter:[self radialCenter]];
    [ng setStepWidth:[self stepWidth]];
    [ng setGraduateAngle:[self graduateAngle]];
    [ng setFilled:YES optimize:NO];
    [ng setWidth:[self width]];
    [ng setSelected:[self isSelected]];

    /* split self */
    if ( (splitListG = [self getListOfObjectsSplittedFromGraphic:ug]) )
        [ng setList:splitListG optimize:NO];

    if ( ![[ng list] count] )
        for (i=0; i<(int)[list count]; i++)
            [[ng list] addObject:[[[list objectAtIndex:i] copy] autorelease]];

    pool = [NSAutoreleasePool new];

    /* split ug */
    if ( !(splitListUg = [ug getListOfObjectsSplittedFromGraphic:self]) )
    {
        splitListUg = [NSMutableArray array];
        if ( [ug isKindOfClass:[VPath class]] )
            for (i=0; i<(int)[[(VPath*)ug list] count]; i++)
                [splitListUg addObject:[[[[(VPath*)ug list] objectAtIndex:i] copy] autorelease]];
        else
            [splitListUg addObject:[[ug copy] autorelease]];
    }

    /* get startIndexes from splitListUg to subpaths */
    uStartIsCnt = 1;
    uStartIs[0] = 0;
    uListCnt = [splitListUg count];
    while (endIx != uListCnt-1)
    {   NSPoint	startPt, e;
        VGraphic	*sg = [splitListUg objectAtIndex:uStartIs[uStartIsCnt-1]];

        endIx = -1;

        startPt = [sg pointWithNum:0];
        for ( i=uStartIs[uStartIsCnt-1]; i < uListCnt; i++ )
        {
            e = [[splitListUg objectAtIndex:i] pointWithNum:MAXINT];
            if ( SqrDistPoints(startPt, e) < tol*tol )
            {
                if (i+1 < uListCnt)
                {   NSPoint	begN = [[splitListUg objectAtIndex:i+1] pointWithNum:0];

                    if ( SqrDistPoints(e, begN) < (TOLERANCE*15)*(TOLERANCE*15) )
                        continue; // dist to next gr is smaller !
                }
                endIx = i;
                break;
            }
        }
        if (endIx == -1)
        {   uStartIs[uStartIsCnt++] = uListCnt-1;
            NSLog(@"VPath.m: -uniteWith: endIx not found !");
            break;
        }
        else
            uStartIs[uStartIsCnt++] = endIx+1;
    }

    /* first remove graphics from splitListUg inside self */
#if 0  // so war es
    for (i=0; i<[splitListUg count]; i++)
    {   VGraphic	*gr = [splitListUg objectAtIndex:i];

        p = [gr pointAt:0.4];
        if ( [self isPointInside:p] )
        {
            [splitListUg removeObjectAtIndex:i];
            /* correct all uStartIs behind i */
            for (k=0; k < uStartIsCnt; k++)
                if (uStartIs[k] > i) uStartIs[k] -= 1;
            i--;
            removedFromUg++;
        }
    }
#endif

#if 1 // alternative 2015-07-24
    {
        VFloat  maxLength = 0.0, le;
        int     sI = -1, eI = -1;

        k = 0;

        for (i=0; i<[splitListUg count]; i++)
        {   VGraphic	*gr = [splitListUg objectAtIndex:i];

            p = [gr pointAt:0.4];
            if ( [self isPointInside:p] )
            {   VGraphic    *g=[splitListUg objectAtIndex:i];

                if (first)
                {   sI = i; first = NO; }

                le = SqrDistPoints([g pointWithNum:0], [g pointWithNum:MAXINT]);
                if ( le > maxLength )
                    maxLength = le;
            }
            else if (!first)
            {   eI = i;
                if (eI-1 == sI)
                {   [splitListUg removeObjectAtIndex:sI];
                    /* correct all uStartIs behind i */
                    for (k=0; k < uStartIsCnt; k++)
                        if (uStartIs[k] > sI) uStartIs[k] -= 1;
                    i--;
                    removedFromUg++;
                }
                else // more than one
                {
                    for (j=eI-1; j >= sI; j--)
                    {   VGraphic    *g=[splitListUg objectAtIndex:j];

                        le = SqrDistPoints([g pointWithNum:0], [g pointWithNum:MAXINT]);
                        if ( (j == eI-1 || j == sI) && le < maxLength )
                            continue; // do not remove first and last short graphic from 

                        [splitListUg removeObjectAtIndex:j];
                        /* correct all uStartIs behind i */
                        for (k=0; k < uStartIsCnt; k++)
                            if (uStartIs[k] > j) uStartIs[k] -= 1;
                        i--;
                        removedFromUg++;
                    }
                }
                maxLength = 0.0;
                first = YES;
            }
        }
        if (!first && eI == -1) // last removing part
        {
            eI = i-1;
            if (eI-1 == sI)
            {   [splitListUg removeObjectAtIndex:sI];
                /* correct all uStartIs behind i */
                for (k=0; k < uStartIsCnt; k++)
                    if (uStartIs[k] > sI) uStartIs[k] -= 1;
                removedFromUg++;
            }
            else // more than one
            {
                for (j=eI-1; j >= sI; j--)
                {   VGraphic    *g=[splitListUg objectAtIndex:j];

                    le = SqrDistPoints([g pointWithNum:0], [g pointWithNum:MAXINT]);
                    if ( (j == eI-1 || j == sI) && le < maxLength )
                        continue; // do not remove first and last short graphic

                    [splitListUg removeObjectAtIndex:j];
                    /* correct all uStartIs behind i */
                    for (k=0; k < uStartIsCnt; k++)
                        if (uStartIs[k] > j) uStartIs[k] -= 1;
                    removedFromUg++;
                }
            }
        }
    }
#endif // alternative

    /* check if we removed a whole subpath */
    for (i=0; i< uStartIsCnt-1; i++)
    {
        if (uStartIs[i] == uStartIs[i+1])
        {
            for (l=i; l < uStartIsCnt-1; l++)
                uStartIs[l] = uStartIs[l+1];
            uStartIsCnt--;
            i--; // perhaps we removed two or three
        }
    }
    /* searching for our startI (not inside ug) */
    startI = -1;
    for ( i=0, listCnt = [[ng list] count]; i<listCnt; i++ )
    {	id	gThis;

        gThis = [[ng list] objectAtIndex:i];	/* this object */

        /* first line normaly not possible !!! after split everything must be a path !! ! */
        p = [gThis pointAt:0.4];
        if ( ![ug isPointInside:p] )
        {
            startI = i;
            break;
        }
    }

    /* self is inside ug -> ug is it */
    if (startI == -1 && !removedFromUg)
    {
        [pool release];
        return [[ug copy] autorelease];
    }

    /* now we remove the parts of ng which are inside ug
     * and notice the start and end points ..
     */
    first = YES;
    removing = NO;
    for ( i=startI, listCnt = [[ng list] count]; startI != -1 && (first || i != startI); i++ )
    {	id	gThis;
        // NSPoint	gPrevE = NSZeroPoint;
        BOOL	currentlyRemoved = NO;

        i = (i >= listCnt) ? 0 : i;
        if (!first && i == startI)
            break;

        gThis = [[ng list] objectAtIndex:i];	/* this object */
        first = NO;

        if (removing && SqrDistPoints(gPrevE, [gThis pointWithNum:0]) > tol*tol)
            removing = NO; // last object removed but first object is not the same subpath and also removed
        gPrevE = [gThis pointWithNum:MAXINT];

        /* first line normaly not possible !!! after split everything must be a path !! ! */
        p = ( [gThis isKindOfClass:[VPath class]] ) ? [[[(VPath*)gThis list] objectAtIndex:0] pointAt:0.4]
                                                    : [gThis pointAt:0.4];
        if ( [ug isPointInside:p] )
        {
            removedFromNg++;
            currentlyRemoved = YES;
            if (!removing)
            {   int	l, prevI = -1;

                removing = YES;
                eCnt++;
                sPairsCnt++;
                ePairsCnt++;
                ePairsCnts[ePairsCnt-1] = 0; // for check of second startPts[] / removing endpts
                sPairsCnts[sPairsCnt-1] = 1;
                startIs[sCnt] = ((i-1 < 0) ? (listCnt-1) : (i-1));
                startPts[sCnt++] = [gThis pointWithNum:0];
                /* search prevG for startPts[1]  */ /* no prevG found - should be not possible ! */
                prevI = ((i-1 < 0) ? (listCnt-1) : i-1);
                for (l=prevI; l != i; l--)
                {   VGraphic	*gr = [[ng list] objectAtIndex:l];
                    NSPoint	e;

                    e = [gr pointWithNum:MAXINT];
                    if (SqrDistPoints(e, startPts[sCnt-1]) <= tol*tol) // prevG found
                    {   NSPoint	s = [gr pointWithNum:0];

                        startIs[sCnt-1] = l; // this is realy the right index !

                        startIs[sCnt] = ((l-1 < 0) ? (listCnt-1) : (l-1));
                        startPts[sCnt++] = s;
                        sPairsCnts[sPairsCnt-1] = 2;
                        break;
                    }
                    if (!l)
                        l = listCnt; // go around until i !!
                }
            }
            ePairsCnts[ePairsCnt-1] = 1;
            endIs[eCnt-1] = i;
            endPts[eCnt-1] = [gThis pointWithNum:MAXINT];
            [[ng list] removeObjectAtIndex:i];

            /* check if we remove a second startPt !!!!!!!!! */
            {   int	l, si0 = 0, spCnt = sPairsCnts[0];

                for (k=0; k < sPairsCnt; k++)
                {
                    spCnt = sPairsCnts[k];
                    if (i == startIs[si0] /*|| (spCnt > 1 && i == startIs[si0+1])*/)
                    {   int	removeI = si0;

                        if (spCnt > 1 && i == startIs[si0]) // remove both points !
                        {
                            for (l=k; l < sPairsCnt-1; l++)
                                sPairsCnts[l] = sPairsCnts[l+1];
                            sPairsCnt--;
                            removeI = sCnt; // nothing more to remove
                            for (l=si0; l < sCnt-2; l++)
                            {
                                startPts[l] = startPts[l+2];
                                startIs[l] = startIs[l+2];
                            }
                            sCnt--; // we remove two points !
//                            NSLog(@"VPath.m: -uniteWith: one startPt pair was currently removed");
                        }
                        else if (spCnt > 1 && i == startIs[si0+1])
                        {
                            break;
                            sPairsCnts[k] = 1;
                            removeI = si0+1;
                        }
                        else
                        {
                            for (l=k; l < sPairsCnt-1; l++)
                                sPairsCnts[l] = sPairsCnts[l+1];
                            sPairsCnt--;
                            removeI = si0;
                        }
                        /* remove startPts from startPts !!!!!!!!! */
                        for (l=removeI; l < sCnt-1; l++)
                        {
                            startPts[l] = startPts[l+1];
                            startIs[l] = startIs[l+1];
                        }
                        sCnt--;
                        break;
                    }
                    si0 += sPairsCnts[k];
                }
            }
            /* correct all startIs/endIs behind i !! */
            for (j=0; j < sCnt; j++)
                if (i <= startIs[j] && startIs[j]) startIs[j] -= 1;
            for (j=0; j < eCnt; j++)
                if (i < endIs[j] && endIs[j]) endIs[j] -= 1;

            if (i < startI)
                startI--;
            i = (i-1 < -1) ? (listCnt-2) : (i-1);
            listCnt--;
        }
        /* close gap with graphics from splitListUg */
        if ((!currentlyRemoved && removing == YES) // i+1
            || (removing == YES && !first && ((i+1 >= listCnt) ? (0) : (i+1)) == startI)) // last endpts to start gr
        {   NSPoint	s;

            /* search nextG for endPts[1]   no nextG found - startG == endG - only one Graphic ! */
            if (!currentlyRemoved)
            {   NSPoint	e = [gThis pointWithNum:MAXINT];

                endIs[eCnt] = i; // ++++++++++++++++1 ((i+1 >= listCnt) ? 0 : i+1);
                endPts[eCnt++] = e;
                ePairsCnts[ePairsCnt-1] = 2;
            }
            else // currentlyRemoved -> i perhaps -1
            {   int	l, nextI = ((i+1 >= listCnt) ? 0 : i+1);

                /* correct endIs[eCnt-1] !!! - we remove the last graphic in list to startI */
                if (i+1 >= listCnt) // endIs[eCnt-1]++ ! - nextI wird i+2 !
                {
                    /* we have to correct only the index !!! */
                    for (l=nextI; l != ((i < 0) ? (listCnt-1) : i); l++)
                    {   VGraphic	*gr = [[ng list] objectAtIndex:l];
                        
                    // if (k == i) break; // one time around
                        s = [gr pointWithNum:0];
                        if (SqrDistPoints(s, endPts[eCnt-1]) <= tol*tol) // nextG found
                        {   //NSPoint	e = [gr pointWithNum:MAXINT];

                            endIs[eCnt-1] = l;
                            //endPts[eCnt-1] = e;
                            break;
                        }
                        if (l == listCnt-1)
                            l = -1; // go around until i !
                    }
                   //nextI = ((nextI+1 >= listCnt) ? 0 : nextI+1);
                }

                for (l=nextI; l != ((i < 0) ? (listCnt-1) : i); l++)
                {   VGraphic	*gr = [[ng list] objectAtIndex:l];
                    
                    // if (k == i) break; // one time around
                    s = [gr pointWithNum:0];
                    if (SqrDistPoints(s, endPts[eCnt-1]) <= tol*tol) // nextG found
                    {   NSPoint	e = [gr pointWithNum:MAXINT];

                        endIs[eCnt] = l; // ++++++++++++++++++++++1
                        endPts[eCnt++] = e;
                        ePairsCnts[ePairsCnt-1] = 2;
                        break;
                    }
                    if (l == listCnt-1)
                        l = -1; // go around until i !
                }
            }
            removing = NO;
        }
    }

    if (!removedFromNg || !removedFromUg)
    {
        /* look if graphics in splitListUg are identical with graphics in [ng list] */
        for (i=0; i<[splitListUg count]; i++)
        {   VGraphic	*gi = [splitListUg objectAtIndex:i];

            for (j=0; j<listCnt; j++)
            {   VGraphic	*gj = [[ng list] objectAtIndex:j];

                if ([gi identicalWith:gj])
                {   [splitListUg removeObjectAtIndex:i];
                    /* korrect all uStartIs behind i */
                    for (k=0; k < uStartIsCnt; k++)
                        if (uStartIs[k] > i) uStartIs[k] -= 1;
                    i--;
                    removedFromUg++;
                    break;
                }
            }
        }
        /* check if we removed a whole subpath */
        for (i=0; i< uStartIsCnt-1; i++)
        {
            if (uStartIs[i] == uStartIs[i+1])
            {
                for (l=i; l < uStartIsCnt-1; l++)
                    uStartIs[l] = uStartIs[l+1];
                uStartIsCnt--;
                i--; // perhaps we remove two or three
            }
        }
        if (![splitListUg count])
        {   [pool release];
            return ng;
        }
    }

    if (!removedFromNg && !removedFromUg)
    {
        /* ug is'nt a path and not splitted now there are two possibilities
         * self is in ug or ug is in self else -> nothing to unite - NO
         */
        if ( ![ug isKindOfClass:[VPath class]] && [splitListUg count] == 1 && ![ug isKindOfClass:[VGroup class]])
        {   NSPoint	p;

            [pool release];
            /* ug is inside self -> self is ok can remove ug later */
            [ug getPoint:&p at:0.4];
            if ( [self isPointInside:p] )
                return ng;

            /* self is inside ug -> ug is it */
            [[list objectAtIndex:0] getPoint:&p at:0.4];
            if ( [(id)ug isPointInside:p] )
                return [[ug copy] autorelease];
            return nil;	// nothing to unite
        }
        [pool release];
        return nil;
    }

    /* search graphics in splitListUg which close the gaps in ng */
    /* our orientation we get through the startPts / sePairsCnt */
    for (i=0; i< sPairsCnt; i++)
    {   int	sptCnt = sPairsCnts[i], eptCnt = ePairsCnts[i], sIx = 1;
        int	sIs[2], eIs[2], sI0 = -1, eI0 = -1, endI = -1;
        NSPoint	sPts[2], ePts[2] = {NSZeroPoint, NSZeroPoint};

        /* count with i and sePairsCnts to the current startIs/startPts index */
        sI0 = 0;
        for (j=0; j < i; j++)
            sI0 += sPairsCnts[j];

        sIs[0] = startIs[sI0];
        sPts[0] = startPts[sI0];
        if (sptCnt == 2)
        {   sIs[1] = startIs[sI0+1];
            sPts[1] = startPts[sI0+1];
        }

        sIx = 1; // is the startIx of the next subPath !
        for (j=0; j<[splitListUg count]; j++)
        {   VGraphic	*gj = [splitListUg objectAtIndex:j];
            NSPoint	sj, ej;

            if (j >= uStartIs[sIx])
                sIx++;

            sj = [gj pointWithNum:0];
            ej = [gj pointWithNum:MAXINT];

            if (pointWithToleranceInArray(sj, tol, sPts, sptCnt) ||
                pointWithToleranceInArray(ej, tol, sPts, sptCnt))
            {   int	closeK = -1, si = 0;
                BOOL	ejIsNearer = NO, gjRemoved = NO, jumpOverOneEnd = NO;
                NSPoint	closePt;

                /* check if gj is a double graphic */
                for (k=0; k < sPairsCnt; k++)
                {
                    if ((startIs[si] < listCnt &&
                        [gj identicalWith:[[ng list] objectAtIndex:startIs[si]]]))
                        //(endIs[si] < listCnt &&
                        // [gj identicalWith:[[ng list] objectAtIndex:endIs[si]]])
                    {
                        [splitListUg removeObjectAtIndex:j];
                        /* korrect all uStartIs behind j */
                        for (l=0; l < uStartIsCnt; l++)
                            if (uStartIs[l] > j) uStartIs[l] -= 1;
                        j--;
                        gjRemoved = YES;
                        break;
                    }
                    si += sPairsCnts[k];
                }
                if (gjRemoved)
                    continue;

                /* ej == sPts[1] && sj != sPts[0]  and sPts[1] is also in endPts */
                if (SqrDistPoints(ej, sPts[1]) < tol*tol && SqrDistPoints(sj, sPts[0]) > tol*tol)
                {   VGraphic	*gjn;
                    NSPoint	sjn;

                    /* ej == sPts[1] && sPts[1] is also in endPts */
                    if (pointWithToleranceInArray(ej, tol, endPts, eCnt))
                        continue;
                    // ej to sPts[1] check if gjn s is to sPts[0]
                    gjn = [splitListUg objectAtIndex:((j+1 >= uStartIs[sIx]) ? uStartIs[sIx-1] : (j+1))];
                    sjn = [gjn pointWithNum:0];
                    if (SqrDistPoints(sjn, sPts[0]) < tol*tol)
                        continue; // took sj to sPts[0]
                }

                if (pointWithToleranceInArray(sj, tol, sPts, sptCnt) &&
                    pointWithToleranceInArray(ej, tol, sPts, sptCnt))
                {   float	ds, de;

                    /* check if ej is nearer to sPts -> search backward / take next start */
                    ds = SqrDistPoints(sj, sPts[0]);
                    de = SqrDistPoints(ej, sPts[0]);
                    if (sptCnt > 1)
                    {   ds = Min(ds, SqrDistPoints(sj, sPts[1]));
                        de = Min(de, SqrDistPoints(ej, sPts[1]));
                    }
                    if (de < ds)
                        ejIsNearer = YES;

               	    if (SqrDistPoints(ej, sPts[0]) < tol*tol)
                    {   VGraphic	*gjn;
                        NSPoint		sjn;

                        /* ej to sPts[0] check if gjn s is to sPts[0] */
                        gjn = [splitListUg objectAtIndex:((j+1 >= uStartIs[sIx]) ? uStartIs[sIx-1] : (j+1))];
                        sjn = [gjn pointWithNum:0];
                        if (SqrDistPoints(sjn, sPts[0]) < tol*tol)
                            continue; // took gjn with sj to sPts[0]
                    }
                }
                /* search forward in splitListUg */
                if (!ejIsNearer && pointWithToleranceInArray(sj, tol, sPts, sptCnt))
                {   BOOL	firstK = YES;
                    NSPoint	prevE = sj; // first k == j == startPt

                    closeK = -1;
                    for ( k=j; firstK || k != j; k++ )
                    {   VGraphic	*gk, *gkn;
                        NSPoint		sk, ek, skn, ekn;

                        k = (k >= uStartIs[sIx]) ? uStartIs[sIx-1] : k;
                        if (!firstK && k == j)
                            break;
                        firstK = NO;

                        gk = [splitListUg objectAtIndex:k];
                        sk = [gk pointWithNum:0];
                        ek = [gk pointWithNum:MAXINT];

                        if (SqrDistPoints(prevE, sk) >= tol*tol)
                            break; // nothing to close gap in ug splitlist

                        if (pointWithToleranceInArray(ek, tol, endPts, eCnt))
                        {
                            gkn = [splitListUg objectAtIndex:((k+1 >= uStartIs[sIx]) ? uStartIs[sIx-1] : (k+1))];
                            skn = [gkn pointWithNum:0];
                            ekn = [gkn pointWithNum:MAXINT];
                            if (SqrDistPoints(ek, skn) < tol*tol &&
                                pointWithToleranceInArray(ekn, tol, endPts, eCnt))
                            {   float	dek = MAXCOORD, dekn = MAXCOORD, d;
                                BOOL	gknIsDouble = NO, eknIs0ePt = YES;
                                int	eki = 0, ekni = 0;

                                for (l=0; l < eCnt; l++)
                                {
                                    if ((d=SqrDistPoints(ekn, endPts[l])) < dekn)
                                    {   dekn = d;
                                        ekni = l;
                                    }
                                    if ((d=SqrDistPoints(ek, endPts[l])) < dek)
                                    {   dek = d;
                                        eki = l;
                                    }
                                }
                                /* both endPts must be 0 ePts ! to use this !! */
                                if (dekn <= dek)
                                {   int	eknI = 0, epCnt; // ekI = 0

                                    for (l=0; l < ePairsCnt; l++)
                                    {
                                        epCnt = ePairsCnts[l];
                                        if (eknI == ekni || (epCnt == 2 && eknI+1 == ekni))
                                        {
                                            if (epCnt == 2 && eknI+1 == ekni)
                                                eknIs0ePt = NO;
                                            break;
                                        }
                                        eknI += ePairsCnts[l];
                                        /*if (ekI == eki || (epCnt == 2 && ekI+1 == eki))
                                        {
                                            if (epCnt == 2 && ekI+1 == eki)
                                                ekIs0ePt = NO;
                                            break;
                                        }
                                        ekI += ePairsCnts[l];*/
                                    }
                                }
                                /* check if gkn is a double graphic */
                                si = 0;
                                for (l=0; l < sPairsCnt; l++)
                                {
                                    if ((startIs[si] < listCnt &&
                                         [gkn identicalWith:[[ng list] objectAtIndex:startIs[si]]]))
                                        //(endIs[si] < listCnt &&
                                        // [gkn identicalWith:[[ng list] objectAtIndex:endIs[si]]])
                                    {
                                        gknIsDouble = YES;
                                        break;
                                    }
                                    si += sPairsCnts[l];
                                }
                                if (!gknIsDouble && eknIs0ePt && (dekn < dek || (dekn <= dek && eki != ekni)))
                                {   prevE = ek;
                                    if (eki != ekni) // this is when we jump over an [ng list] graphic !!
                                        jumpOverOneEnd = YES;
                                    continue; // next gk is our close gk
                                }
                            }
                            closePt = ek;
                            closeK = k;
                            break; // we can close the gap
                        }
                        prevE = ek;
                    }
                }
                else // backward searching
                {   BOOL	firstK = YES;
                    NSPoint	prevS = ej; // first k == j == startPt

                    closeK = -1;
                    for ( k=j; firstK || k != j; k-- )
                    {   VGraphic	*gk, *gkp;
                        NSPoint		sk, ek, skp, ekp;

                        k = (k < uStartIs[sIx-1]) ? (uStartIs[sIx]-1) : k;

                        if (!firstK && k == j)
                            break;
                        firstK = NO;

                        gk = [splitListUg objectAtIndex:k];
                        sk = [gk pointWithNum:0];
                        ek = [gk pointWithNum:MAXINT];

                        if (SqrDistPoints(prevS, ek) >= tol*tol)
                            break; // nothing to close gap in path
                        if (pointWithToleranceInArray(sk, tol, endPts, eCnt))
                        {
                            gkp = [splitListUg objectAtIndex:((k-1 < uStartIs[sIx-1]) ? (uStartIs[sIx]-1) : (k-1))];
                            skp = [gkp pointWithNum:0];
                            ekp = [gkp pointWithNum:MAXINT];
                            if (SqrDistPoints(sk, ekp) < tol*tol &&
                                pointWithToleranceInArray(skp, tol, endPts, eCnt))
                            {   float	dek = MAXCOORD, dekp = MAXCOORD, d;
                                BOOL	gkpIsDouble = NO, ekpIs0ePt = YES;
                                int	eki = 0, ekpi = 0;

                                for (l=0; l < eCnt; l++)
                                {   if ((d=SqrDistPoints(ekp, endPts[l])) < dekp)
                                    {   dekp = d;
                                        ekpi = l;
                                    }
                                    if ((d=SqrDistPoints(ek, endPts[l])) < dek)
                                    {   dek = d;
                                        eki = l;
                                    }
                                }
                                /* both endPts must be 0 ePts ! to use this !! */
                                if (dekp <= dek)
                                {   int	ekpI = 0, epCnt;

                                    for (l=0; l < ePairsCnt; l++)
                                    {
                                        epCnt = ePairsCnts[l];
                                        if (ekpI == ekpi || (epCnt == 2 && ekpI+1 == ekpi))
                                        {
                                            if (epCnt == 2 && ekpI+1 == ekpi)
                                                ekpIs0ePt = NO;
                                            break;
                                        }
                                        ekpI += ePairsCnts[l];
                                    }
                                }
                                /* check if gkp is a double graphic */
                                si = 0;
                                for (l=0; l < sPairsCnt; l++)
                                {
                                    if ((startIs[si] < listCnt &&
                                         [gkp identicalWith:[[ng list] objectAtIndex:startIs[si]]]))
                                        //(endIs[si] < listCnt &&
                                        // [gkp identicalWith:[[ng list] objectAtIndex:endIs[si]]])
                                    {
                                        gkpIsDouble = YES;
                                        break;
                                    }
                                    si += sPairsCnts[l];
                                }
                                if (!gkpIsDouble && ekpIs0ePt && (dekp < dek || (dekp <= dek && eki != ekpi)))
                                {   prevS = sk;
                                    if (eki != ekpi) // this is when we jump over an [ng list] graphic !!
                                        jumpOverOneEnd = YES;
                                    continue; // next gk is our close gk
                                }
                            }
                            closePt = sk;
                            closeK = k;
                            break; // we can close the gap
                        }
                        prevS = sk;
                    }
                }
                if (closeK != -1)
                {   int		added = 0, from = closeK, to = j, m=0;
                    float	dist = MAXCOORD;

                    /* get endI, eptCnt and eI0 */
                    if (pointWithToleranceInArray(closePt, tol, endPts, eCnt))
                    {
                        for (k=0; k < eCnt; k++)
                            if (SqrDistPoints(closePt, endPts[k]) < tol*tol)
                            {   endI = k;
                                break;
                            }
                    }
                    else
                        NSLog(@"VPath.m: -uniteWith: this should be not possible");

                    eI0 = 0;
                    for (k=0; k < ePairsCnt; k++)
                    {
                        eptCnt = ePairsCnts[k];
                        if (eI0 == endI || (eptCnt == 2 && eI0+1 == endI))
                            break;
                        eI0 += ePairsCnts[k];
                    }
                    eIs[0] = endIs[eI0];
                    ePts[0] = endPts[eI0];
                    if (eptCnt == 2)
                    {   eIs[1] = endIs[eI0+1];
                        ePts[1] = endPts[eI0+1];
                    }

					/* here we remove this endPair from endPts */
                    /* k is our ePairs index - eI0 is our endPts/endIs index - eptCnt 1 or 2 epts */
                    /* remove endPts (1 or 2) / remove endIs (1 or 2) */
                    /* remove ePairsCnts (1) */
                    /* ePairsCnt -- */
                    if ( eptCnt == 2 )
                    {   for (m=eI0+1; m < eCnt-1; m++)
                        {   endIs[m] = endIs[m+1];
                            endPts[m] = endPts[m+1];
                        }
                        eCnt--;
                    }
                    for (m=eI0; m < eCnt-1; m++)
                    {   endIs[m] = endIs[m+1];
                        endPts[m] = endPts[m+1];
                    }
                    eCnt--;
                    for (m=k; m < ePairsCnt-1; m++)
                        ePairsCnts[m] = ePairsCnts[m+1];
                    ePairsCnt--;

                    /* little gap will close from optimize list correctlier */
                    if (SqrDistPoints(sPts[0], ePts[0]) < tol*tol ||
                        (!pointWithToleranceInArray(sj, tol, sPts, sptCnt) && SqrDistPoints(closePt, ej) < tol*tol) ||
                        (pointWithToleranceInArray(sj, tol, sPts, sptCnt) && SqrDistPoints(closePt, sj) < tol*tol))
                        continue; // little gap will close from optimize list correctlier

                    /* if eCnt/sCnt > 1
                    * && ej/sj... gleich zu ..Pts[1] -> ..Is[0] aus [ng list] removen !!!!!!!!!! */
                    if (sptCnt > 1 &&
                        (((dist=SqrDistPoints(ej, sPts[1])) < tol*tol && dist < SqrDistPoints(ej, sPts[0])) ||
                         ((dist=SqrDistPoints(sj, sPts[1])) < tol*tol && dist < SqrDistPoints(sj, sPts[0]))) &&
                        !pointWithToleranceInArray(sPts[1], tol, endPts, eCnt))
                    {   /* remove object at sIs[0] from [ng list] */
                        [[ng list] removeObjectAtIndex:sIs[0]];
                        if (startI > sIs[0])
                            startI--;
                        
                        /* correct all startIs/endIs behind sIs[0] !! */
                        for (k=0; k < sCnt; k++)
                            if (startIs[k] >= sIs[0] && startIs[k]) startIs[k] -= 1;
                        for (k=0; k < eCnt; k++)
                            if (endIs[k] > sIs[0] && endIs[k]) endIs[k] -= 1;
                        if (eIs[0] > sIs[0]) eIs[0] -= 1;
                        sIs[0]--;
                        listCnt--;
                    }

                    if ((eptCnt > 1 &&
                         ((dist=SqrDistPoints(closePt, ePts[1])) < tol*tol &&
                          dist < SqrDistPoints(closePt, ePts[0]) && // tol*tol
                          !pointWithToleranceInArray(ePts[1], tol, startPts, sCnt)))
                        || (jumpOverOneEnd && eptCnt > 1 && SqrDistPoints(closePt, ePts[0]) < tol*tol))
                    {	int	ri = eIs[0];

                        if (jumpOverOneEnd && eptCnt > 1 && SqrDistPoints(closePt, ePts[0]) < tol*tol)
                        {
                            if (sIs[0]+1 == eIs[0]-1)
                                ri = sIs[0]+1;
                            else if (Diff(sIs[0], eIs[0]) == 1 || Diff(sIs[0], eIs[0]) > 3)
                                ri = -1; // nothing to remove
                            else
                            {   ri = -1;
                                NSLog(@"VPAth.m -uniteWith: not yet implemented");
                            }
                        }
                        if (ri != -1)
                        {   /* remove object at ri (eIs[0]) from [ng list] */
                            [[ng list] removeObjectAtIndex:ri];

                            /* correct all startIs/endIs befor ri !! */
                            for (k=0; k < sCnt; k++)
                                if (startIs[k] >= ri && startIs[k]) startIs[k] -= 1;
                            for (k=0; k < eCnt; k++)
                                if (endIs[k] > ri && endIs[k]) endIs[k] -= 1;
                            if (sIs[0] >= ri) sIs[0] -= 1;
                            listCnt--;
                        }
                    }

                    if (!pointWithToleranceInArray(sj, tol, sPts, sptCnt)) //  war  ej ohne !
                    {
                        //if (pointWithToleranceInArray(ej, tol, sPts, sptCnt))
                        {   to = closeK;
                            from = j;
                        }
                        /* insert graphics forward */ /* dont stop with 0 (k) <= -1 (from) */
                        for (k=to; k <= ((to > from) ? (uStartIs[sIx]-1) : (from)) && from >= uStartIs[sIx-1]; k++)
                        {   VGraphic	*gk = [splitListUg objectAtIndex:k];

                            [gk changeDirection];
                            [[ng list] insertObject:gk atIndex:((sIs[0]==[[ng list] count]) ? (sIs[0]) : (sIs[0]+1))];
                            added++;
                            if (k <= from) { from--; to--; }
                            [splitListUg removeObjectAtIndex:k];
                            /* korrect all uStartIs behind k */
                            for (l=0; l < uStartIsCnt; l++)
                                if (uStartIs[l] > k) uStartIs[l] -= 1;
                            k--;
                            if (k+1 >= uStartIs[sIx] && to > from)
                            {   k = uStartIs[sIx-1] - 1; // 0 - 1
                                to = from-1; // little hack mh - second part until list end !
                            }
                        }
                    }
                    else
                    {   //if (pointWithToleranceInArray(sj, tol, sPts, sptCnt))
                        {   to = closeK;
                            from = j;
                        }
                        /* insert graphics from backward (closeK-j) */
                        for (k=to; k >= ((!to || to < from) ? uStartIs[sIx-1] : from); k--)
                        {   VGraphic	*gk = [splitListUg objectAtIndex:k];
                            
                            [[ng list] insertObject:gk atIndex:((sIs[0]==[[ng list] count]) ? (sIs[0]) : (sIs[0]+1))];
                            [splitListUg removeObjectAtIndex:k];
                            /* korrect all uStartIs behind k */
                            for (l=0; l < uStartIsCnt; l++)
                                if (uStartIs[l] > k) uStartIs[l] -= 1;
                            added++;
                            if (k < from) { from--; to--; }

                            if (k <= uStartIs[sIx-1] && to < from) // we step over 0 - second part until from !
                            {   k = uStartIs[sIx]; // [splitListUg count]
                                to = from+1; // little hack mh - second part until from !
                            }
                        }
                    }
                    /* we must check if we remove a hole subpath */
                    for (k=0; k< uStartIsCnt-1; k++)
                    {
                        if (uStartIs[k] == uStartIs[k+1])
                        {
                            for (l=k; l < uStartIsCnt-1; l++)
                                uStartIs[l] = uStartIs[l+1];
                            uStartIsCnt--;
                            k--; // perhaps we remove two or three
                        }
                    }
                    /* correct all startIs/endIs behind sIs[0] !! */
                    for (k=0; k < sCnt; k++)
                        if (startIs[k] >= sIs[0]) startIs[k] += added;
                    for (k=0; k < eCnt; k++)
                        if (endIs[k] >= sIs[0]) endIs[k] += added;

                    listCnt += added;
                    break;
                }
            }
        }
    }

    /* add closed shapes from splitListUg to ng */
    if (uStartIsCnt > 1 && [splitListUg count])
    {
        for (i=0; i<uStartIsCnt-1; i++)
        {
            if (uStartIs[i+1]-1 == uStartIs[i] && [splitListUg count] == 1) // only one object
            {   VGraphic	*g = [splitListUg objectAtIndex:uStartIs[i]];

                if ([g isKindOfClass:[VArc class]] && Abs([(VArc*)g angle]) == 360.0)
                    [[ng list] addObject:[splitListUg objectAtIndex:uStartIs[i]]];
                continue;
            }
            else if ([splitListUg count] >= uStartIs[i+1]-1)
            {   VGraphic	*gs = [splitListUg objectAtIndex:uStartIs[i]];
                VGraphic	*ge = [splitListUg objectAtIndex:uStartIs[i+1]-1];
                NSPoint		s, e;

                s = [gs pointWithNum:0];
                e = [ge pointWithNum:MAXINT];
                if (SqrDistPoints(s, e) <= tol*tol) /*&& (sPairsCnt || (!sPairsCnt && !removedFromUg))*/
                {   BOOL	doNotAdd = NO;

                    for (j=uStartIs[i]; j < uStartIs[i+1]-1; j++)
                    {   VGraphic	*gs = [splitListUg objectAtIndex:j];
                        VGraphic	*ge = [splitListUg objectAtIndex:j+1];
                        NSPoint		s, e;

                        e = [gs pointWithNum:MAXINT];
                        s = [ge pointWithNum:0];
                        if (SqrDistPoints(e, s) <= tol*tol)
                            continue;
                        else
                        {   doNotAdd = YES;
                            break;
                        }
                    }
                    if (doNotAdd)
                        continue;

                    for (j=uStartIs[i]; j < uStartIs[i+1]; j++)
                        [[ng list] addObject:[splitListUg objectAtIndex:j]];
                }
            }
        }
    }

    if (sPairsCnt > 1) // aukommentieren fuer debugging zwecke !!!!!!!!!!!!!!!!
        [self optimizeList:[ng list]];

    [pool release];

    return ng;
}

/* return self - if self is completely inside cg
 * return ug   - if cg is completely inside self
 * return the intersection path of both
 */
- (id)clippedFrom:(VGraphic*)cg
{   int			i, j, cnt, nothingRemoved = 0;
    VPath		*ng;
    NSMutableArray	*splitListG, *splitListUg;
    NSAutoreleasePool	*pool;

    if ( ![cg isKindOfClass:[VPath class]] && ![cg isKindOfClass:[VArc class]] && ![cg isKindOfClass:[VPolyLine class]]
        && ![cg isKindOfClass:[VRectangle class]] && ![cg isKindOfClass:[VGroup class]] )
        return NO;

    ng = [VPath path];
    [ng setColor:[self color]];
    [ng setFilled:filled optimize:NO];
    [ng setWidth:0.0];
    [ng setSelected:NO];

    /* split self */
    if ( (splitListG = [self getListOfObjectsSplittedFromGraphic:cg]) )
        [ng setList:splitListG optimize:NO];

    pool = [NSAutoreleasePool new];

    if ( ![[ng list] count] )
        for (i=0; i<(int)[list count]; i++)
            [[ng list] addObject:[[[list objectAtIndex:i] copy] autorelease]];

    /* split cg */
    if ( !(splitListUg = [cg getListOfObjectsSplittedFromGraphic:self]) )
    {
        splitListUg = [NSMutableArray array];
        if ( [cg isKindOfClass:[VPath class]] )
            for (i=0; i<(int)[[(VPath*)cg list] count]; i++)
                [splitListUg addObject:[[[[(VPath*)cg list] objectAtIndex:i] copy] autorelease]];
        else
            [splitListUg addObject:[[cg copy] autorelease]];
    }

    /* cg is'nt a path and not splitted now there are two possibilities
     * self is in cg or cg is in self else -> nothing to unite - NO
     */
    if ( ![cg isKindOfClass:[VPath class]] && [splitListUg count] == 1 && ![cg isKindOfClass:[VGroup class]])
    {   NSPoint	p;
        [pool release];

        /* return self - if self is completely inside cg
         * return cg   - if cg is completely inside self
         */
        /* cg is inside self */
        [cg getPoint:&p at:0.4];
        if ( [self isPointInside:p] )
            return [[cg copy] autorelease];

        /* self is inside cg -> self is it */
        [[list objectAtIndex:0] getPoint:&p at:0.4];
        if ( [(id)cg isPointInside:p] )
            return ng;
        return NO;	/* nothing to clip */
    }

    /* now remove the graphictiles from cg wich are outside
     * if no tile is removed -> NO
     */
    {   HiddenArea	*hiddenArea = [HiddenArea new];
        
        /* return self - if self is completely inside cg
         * return cg   - if cg is completely inside self
         */
        if ( ![hiddenArea removeGraphics:splitListUg outside:self] )
            nothingRemoved++;

        /* now remove the graphic tiles from ng(self splitted) wich are outside or on cg */
        if ( ![hiddenArea removeGraphics:[ng list] outside:cg] && nothingRemoved )
        {   [hiddenArea release];
            [pool release];
            return ng; // self comletly inside cg
        }

        /* add graphics from splitListUg to ng list */
        for (i=0; i<(int)[splitListUg count]; i++)
            [[ng list] addObject:[[[splitListUg objectAtIndex:i] copy] autorelease]];

        /* we must remove identical graphics in list */
        cnt = ([[ng list] count]-[splitListUg count]);

        /* we check only added objects !!!!!!!!!! */
        for (i=[[ng list] count]-1; i >= cnt; i--)
        {   VGraphic	*g = [[ng list] objectAtIndex:i];

            for (j=0; j<(int)[[ng list] count]; j++)
            {   VGraphic	*g2 = [[ng list] objectAtIndex:j];

                if ( g2 == g )
                    continue;
                if ( [g2 identicalWith:g] )
                {
                    [[ng list] removeObject:g];
                    break;
                }
            }
        }

        [hiddenArea removeSingleGraphicsInList:[ng list] :[cg bounds]];
        [hiddenArea release];
    }

    [pool release];
    return ng;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [super encodeWithCoder:aCoder];
    [aCoder encodeObject:list]; // [aCoder encodeValuesOfObjCTypes:"@", &list];
    [aCoder encodeValuesOfObjCTypes:"c", &isDirectionCCW];
    [aCoder encodeValuesOfObjCTypes:"i", &filled]; // 2002-07-07
    [aCoder encodeObject:fillColor];
    [aCoder encodeObject:endColor];
    [aCoder encodeValuesOfObjCTypes:"ff", &graduateAngle, &stepWidth];
    //[aCoder encodeValuesOfObjCTypes:"{NSPoint=ff}", &radialCenter];
    [aCoder encodePoint:radialCenter];          // 2012-01-08
}
- (id)initWithCoder:(NSCoder *)aDecoder
{   int		version;

    [super initWithCoder:aDecoder];
    version = [aDecoder versionForClassName:@"VPath"];
    list = [[aDecoder decodeObject] retain];    // [aDecoder decodeValuesOfObjCTypes:"@", &list];
    if ( version < 1 )
        [aDecoder decodeValuesOfObjCTypes:"c", &filled];
    else if (version < 2) // 07.04.98
        [aDecoder decodeValuesOfObjCTypes:"cc", &filled, &isDirectionCCW];
    else // 2002-07-07
    {   [aDecoder decodeValuesOfObjCTypes:"c", &isDirectionCCW];
        [aDecoder decodeValuesOfObjCTypes:"i", &filled];
        fillColor = [[aDecoder decodeObject] retain];
        endColor  = [[aDecoder decodeObject] retain];
        [aDecoder decodeValuesOfObjCTypes:"ff", &graduateAngle , &stepWidth];
        //[aDecoder decodeValuesOfObjCTypes:"{NSPoint=ff}", &radialCenter];
        radialCenter = [aDecoder decodePoint];  // 2012-01-08
    }

    if ( version < 2 )
    {   UPath	fillUPath;

        [aDecoder decodeValuesOfObjCTypes:"ii", &fillUPath.num_ops, &fillUPath.num_pts];
        if ( fillUPath.num_ops )	// old
        {
            fillUPath.ops = malloc((fillUPath.num_ops+10) * sizeof(char));
            fillUPath.pts = malloc((fillUPath.num_pts+10) * sizeof(float));
            [aDecoder decodeArrayOfObjCType:"c" count:fillUPath.num_ops at:fillUPath.ops];
            [aDecoder decodeArrayOfObjCType:"f" count:fillUPath.num_pts at:fillUPath.pts];
            free(fillUPath.ops);
            free(fillUPath.pts);
        }
    }

    selectedObject = -1;
    graduateDirty = YES;
    graduateList = nil;

    return self;
}

/* archiving with property list
 */
- (id)propertyList
{   NSMutableDictionary	*plist = [super propertyList];

    [plist setObject:propertyListFromArray(list)                forKey:@"list"];
    if (filled)
        [plist setObject:propertyListFromInt(filled)            forKey:@"filled"];
    // FIXME: it is not reliable to compare with "!=", it needs "isEqual:"
    //if (fillColor != [NSColor blackColor])
        [plist setObject:propertyListFromNSColor(fillColor)     forKey:@"fillColor"];
    if (endColor  != [NSColor blackColor])
        [plist setObject:propertyListFromNSColor(endColor)      forKey:@"endColor"];
    if (graduateAngle)
        [plist setObject:propertyListFromFloat(graduateAngle)   forKey:@"graduateAngle"];
    if (stepWidth != 7)
        [plist setObject:propertyListFromFloat(stepWidth)       forKey:@"stepWidth"];
    if (!(radialCenter.x == 0.5 && radialCenter.y == 0.5))
        [plist setObject:propertyListFromNSPoint(radialCenter)  forKey:@"radialCenter"];
    return plist;
}
- (id)initFromPropertyList:(id)plist inDirectory:(NSString *)directory
{
    [super initFromPropertyList:plist inDirectory:directory];
    list = arrayFromPropertyList([plist objectForKey:@"list"], directory, [self zone]);
    filled = [plist intForKey:@"filled"];
    if (!filled && [plist objectForKey:@"filled"])
        filled = 1;
    // Note: VPath, VArc, VRectangle
    //       if fillColor == nil, we may have an old file where color == fillColor
    if (!(fillColor = colorFromPropertyList([plist objectForKey:@"fillColor"], [self zone])))
    {   [self setFillColor:[NSColor blackColor]/*[color copy]*/];
        //[self setFillColor:[color copy]]; // loads old file format with color only
    }
    if (!(endColor  = colorFromPropertyList([plist objectForKey:@"endColor"],  [self zone])))
        [self setEndColor:[NSColor blackColor]];
    graduateAngle = [plist floatForKey:@"graduateAngle"];
    if ( !(stepWidth = [plist floatForKey:@"stepWidth"]))
        stepWidth = 7.0;	// default;
    if ([plist objectForKey:@"radialCenter"])
        radialCenter = pointFromPropertyList([plist objectForKey:@"radialCenter"]);
    else
        radialCenter = NSMakePoint(0.5, 0.5);	// default

    selectedObject = -1;
    graduateDirty = YES;
    graduateList = nil;
    return self;
}


- (void)dealloc
{
    [fillColor release];
    [endColor  release];
    [list release];
    list = nil;
    if (graduateList)
    {   [graduateList release];
        graduateList = nil;
    }
    [super dealloc];
}

@end