File: gpsmap.cc

package info (click to toggle)
kismet 2008-05-R1-4
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 3,232 kB
  • ctags: 3,998
  • sloc: cpp: 33,568; sh: 5,544; ansic: 459; makefile: 457; perl: 62; sql: 41
file content (4583 lines) | stat: -rw-r--r-- 164,975 bytes parent folder | download | duplicates (2)
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
/*
    This file is part of Kismet

    Kismet is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with Kismet; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "config.h"

// Prevent make dep warnings
#if (defined(HAVE_IMAGEMAGICK) && defined(HAVE_GMP))

#include <stdio.h>
#ifdef HAVE_PTHREAD
#include <pthread.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#include <math.h>
#include <gmp.h>
#include <time.h>
#include "getopt.h"
#include <unistd.h>
#include <list>
#include <map>
#include <vector>
#include <algorithm>
#include <string>
#include <deque>
#include <algorithm>
#include <zlib.h>
#include <magick/api.h>
#include "configfile.h"

#include "timetracker.h"
#include "gpsdump.h"
#include "expat.h"
#include "manuf.h"
#include "gpsmap_cache.h"
#include "gpsmap_samples.h"

// Make gpsd happy
Timetracker timetracker;

// Kludge old IM
#if (MagickLibVersion < 0x600)
#define MagickTrue 1
#define MagickFalse 0

typedef unsigned int MagickBooleanType;
#endif

/* Mapscale / pixelfact is meter / pixel */
#define PIXELFACT 2817.947378

#define square(x) ((x)*(x))

// Global constant values
const char *config_base = "kismet.conf";

// Not all these work anymore, but left for people who kept gifs and want to still
// plot on top of them.  We won't download new ones.
#define MAPSOURCE_MIN        -1
#define MAPSOURCE_NULL       -1
#define MAPSOURCE_MAPBLAST   0
#define MAPSOURCE_MAPPOINT   1
#define MAPSOURCE_TERRA      2
#define MAPSOURCE_TIGER      3
#define MAPSOURCE_EARTHAMAPS 4
#define MAPSOURCE_TERRATOPO  5
#define MAPSOURCE_EUEX	     6
#define MAPSOURCE_OSM        7
#define MAPSOURCE_MAX        7

// Broken map sources...  Damn vendors changing.
// Mappoint
// const char url_template_mp[] = "http://msrvmaps.mappoint.net/isapi/MSMap.dll?ID=3XNsF.&C=%f,%f&L=USA&CV=1&A=%ld&S=%d,%d&O=0.000000,0.000000&MS=0&P=|5748|";

// Mapblast
const char url_template_mb[] = "http://go.vicinity.com/homedepotvd/MakeMap.d?&CT=%f:%f:%ld&IC=&W=%d&H=%d&FAM=mblast&LB=%s";

// Terraserver photo-maps and topo maps
const char url_template_ts[] = "http://terraservice.net/GetImageArea.ashx?t=1&lat=%f&lon=%f&s=%ld&w=%d&h=%d";
const char url_template_tt[] = "http://terraservice.net/GetImageArea.ashx?t=2&lat=%f&lon=%f&s=%ld&w=%d&h=%d";
// Tiger census vector maps
const char url_template_ti[] = "http://tiger.census.gov/cgi-bin/mapper/map.gif?lat=%f&lon=%f&wid=0.001&ht=%f&iwd=%d&iht=%d&on=majroads&on=places&on=shorelin&on=streets&on=interstate&on=statehwy&on=ushwy&on=water&tlevel=-&tvar=-&tmeth=i";
// Earthamaps need a perl helper script to get data because of cookies
const char url_template_em[] = "gpsmap-helper-earthamaps %s %f %f %d %d %ld";

const char url_template_euex[] = "http://www.expedia.de/pub/agent.dll?qscr=mrdt&ID=3XNsF.&CenP=%f,%f&Lang=%s&Alti=%ld&Size=%d,%d&Offs=0.000000,0.000000&BCheck=1";

const char url_template_osm[] = "http://tah.openstreetmap.org/MapOf/?lat=%f&long=%f&z=%d&w=%d&h=%d&format=png";

// Download template for sources that we fetch using wget
const char download_template[] = "wget \"%s\" -O %s";

// Image scales we try to autofetch
long int scales[] = { 1000, 2000, 5000, 10000, 20000, 30000, 50000, 60000, 
    70000, 75000, 80000, 85000, 90000, 95000, 100000, 125000, 150000, 200000, 
    300000, 500000, 750000, 1000000, 2000000, 3000000, 4000000, 5000000, 
    6000000, 7000000, 8000000, 9000000, 10000000, 15000000,
    20000000, 25000000, 30000000, 35000000, 40000000, -1 };

// Terraserver scales for conversion to mapblast scales
long int terrascales[] = { 2757, 5512, 11024, 22048, 44096, 88182, 176384, -1 };

// Earthamap scales turned into our mapblast scales
// (metersscale / 42 * PIXELFACT)
long int earthamapscales[] = {
    0, 0, 32393191, 16196595, 8098298, 4319092, 2159546, 1079773, 539887,
    215955, 107977, 53989, 26994, 14315, 7158, 3579, -1 };

// Scales for Expedia
long int euexscales[] = { 3950, 7900, 11850, 15800, 19750, 23700, 27650,
	31600, 35550, 39500, 79000, 118500, 197500, 237000, 276500, 316000,
	355500, 395000, 790000, 1580000, 237000, 3160000, 3950000, 19750000,
	39500000, 47400000};

// Zoomlevels for OSM

//taken from wiki but doesn't seem to work :(
//long int osmscales[] = {3385, 6771, 14000, 27000, 54000, 108000, 217000, 433000, 867000, 2000000, 3000000};
//int osm_zoomlevels[] = {17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7};

//got these ones by trial'n'error:
long int osmscales[] = {2100, 4320, 8600, 17200, 34000};
int osm_zoomlevels[] = {17, 16, 15, 14, 13};
int osm_zoomlevel = 13;

/* tested scales:
17 = 2100?
16 = 4320
15 = 8600
14 = 17200
13 = 34000
12 = 
11 = 
10 = 
09 = 
08 = 
07 = 
*/

// Decay from absolute blue for multiple tracks
const uint8_t track_decay = 0x1F;
// distance (in feet) before we throttle a network and discard it
const unsigned int horiz_throttle = 75000;

// Image colors
const char *netcolors[] = {
    "#000000",
    "#FF0000", "#FF0072", "#FF00E5", "#D400FF",
    "#5D00FF", "#0087FF", "#00F2FF", "#00FF94",
    "#00FF2E", "#BBFF00", "#FFB200", "#FF6E00",
    "#FF6500", "#960000", "#96005F", "#640096",
    "#001E96", "#008E96", "#00963E", "#529600",
    "#968C00", "#963700", NULL
};

// Channel colors
/*
char *channelcolors[] = {
    "#FF0000", "#FF8000", "#FFFF00",
    "#80FF00", "#00FF00", "#00FF80",
    "#00FFFF", "#0080FF", "#0000FF",
    "#8000FF", "#FF00FF", "#FF0080",
    "#808080", "#CCCCCC"
};
*/
char *channelcolors[] = { 
    "#FF0000", "#FF6000", "#A08000", 
    "#80A000", "#60FF00", "#00FF00", 
    "#00FF60", "#00A080", "#0080A0", 
    "#0060FF", "#0000FF", "#808080",
    "#CCCCCC", "#00FFFF" };
int channelcolor_max = 14;

// Origional
char *powercolors_Orig[] = {
    "#FF0000", "#FFD500", "#FFCC00",
    "#F2FF00", "#7BFF00", "#00FFB6",
    "#00FFFF", "#005DFF", "#A100FF",
    "#FA00FF"
};
const int power_steps_Orig = 10;
// Blue powercolors
char *powercolors_Blue[] = {
    "#A0A0FF",
    "#9B9BFA",
    "#9696F5",
    "#9191F0",
    "#8C8CEB",
    "#8787E6",
    "#8282E1",
    "#7D7DDC",
    "#7878D7",
    "#7373D2",
    "#6E6ECD",
    "#6969C8",
    "#6464C3",
    "#5F5FBE",
    "#5A5AB9",
    "#5555B4",
    "#5050AF",
    "#4B4BAA",
    "#4646A5",
    "#4141A0",
    "#3C3C9B",
    "#373796",
    "#323291",
    "#2D2D8C",
    "#282887",
    "#232382",
    "#1E1E7D",
    "#191978",
    "#141473",
    "#0F0F6E",
    "#0A0A69",
    "#050564",
};
const int power_steps_Blue = 32;

// Math progression
char *powercolors_Math[] = {
    "#FF0000", "#FF8000", "#FFFF00",
    "#80FF00", "#00FF00", "#00FF80",
    "#00FFFF", "#0080FF", "#0000FF",
    "#8000FF", "#FF00FF", "#FF0080"
};
const int power_steps_Math = 12;
// Weather Radar
char *powercolors_Radar[] = {
    "#50E350", "#39C339", "#208420",
    "#145A14", "#C8C832", "#DC961E",
    "#811610", "#B31A17", "#E61E1E"
};
const int power_steps_Radar = 9;
// Maximum power reported
const int power_max = 255;

int powercolor_index = 0;

// Label gravity
char *label_gravity_list[] = {
    "northwest", "north", "northeast",
    "west", "center", "east",
    "southwest", "south", "southeast"
};

int scatter_power;
int power_zoom;

// Average all the sample points or try to be smart?
int pure_center_average = 0;

// Tracker internals
int sample_points;

// Convex hull point
struct hullPoint {
	int x, y;
	double angle;
	string xy;
	bool operator< (const hullPoint&) const;
	bool operator() (const hullPoint&, const hullPoint&) const;
};

bool hullPoint::operator< (const hullPoint& op) const {
	if (y == op.y) {
		return x < op.x;
	}
	return y < op.y;
}

bool hullPoint::operator() (const hullPoint& a, const hullPoint& b) const {
	if (a.angle == b.angle) {
		if (a.x == b.x) {
			return a.y < b.y;
		}
		return a.x < b.x;
	}
	return a.angle < b.angle;
}

typedef struct gps_network {

    gps_network() {
        filtered = 0;
        wnet = NULL;
        max_lat = 90;
        max_lon = 180;
        min_lat = -90;
        min_lon = -180;
        max_alt = min_alt = 0;
        count = 0;
        avg_lat = avg_lon = avg_alt = avg_spd = 0;
        diagonal_distance = altitude_distance = 0;
    };

    // Are we filtered from displying?
    int filtered;

    // Wireless network w/ full details, loaded from the associated netfile xml
    wireless_network *wnet;

    string bssid;

    float max_lat;
    float min_lat;
    float max_lon;
    float min_lon;
    float max_alt;
    float min_alt;

    int count;

    float avg_lat, avg_lon, avg_alt, avg_spd;

    float diagonal_distance, altitude_distance;

    vector<gps_point *> points;
    vector<gps_point *> center_points;

    // Points w/in this network
    // vector<point> net_point;

    // Index to the netcolors table
    string color_index;

    struct {
	int x, y, h, w; } label;
};

// All networks we know about
map<mac_addr, wireless_network *> bssid_net_map;

// All the networks we know about for drawing
map<string, gps_network *> bssid_gpsnet_map;
// All networks we're going to draw
map<mac_addr, gps_network *> drawn_net_map;

typedef struct {
    int version;

    float lat;
    float lon;
    float alt;
    float spd;

    int power;
    int quality;
    int noise;

    unsigned int x, y;
} track_data;

// Array of network track arrays
unsigned int num_tracks = 0;
vector< vector<track_data> > track_vec;
// Global average for map scaling
gps_network global_map_avg;

// Do we have any power data?
int power_data;

// Map scape
long map_scale;
// Center lat/lon for map
double map_avg_lat, map_avg_lon;


// User options and defaults
unsigned int map_width = 1280;
unsigned int map_height = 1024;
const int legend_height = 100;

// Drawing features and opacity
int draw_track = 0, draw_bounds = 0, draw_range = 0, draw_power = 0,
    draw_hull = 0, draw_scatter = 0, draw_legend = 0, draw_center = 0, draw_label = 0;
int track_opacity = 100, /* no bounds opacity */ range_opacity = 70, power_opacity = 70,
    hull_opacity = 70, scatter_opacity = 100, center_opacity = 100, label_opacity = 100,
    bounds_opacity = 10;
int track_width = 3;
int convert_greyscale = 1, keep_gif = 0, verbose = 0, label_orientation = 7, feather_range = 0,
    feather_hull = 0, feather_scatter = 0, color_saturation = 0, map_intensity = 0;
int cache_disable = 0;
int ignore_under_count = 0, ignore_under_distance = 0;

// Offsets for drawing from what we calculated
int draw_x_offset = 0, draw_y_offset = 0;

// Map source
int mapsource = -1;

// Interpolation resolution
int power_resolution = 5;
// Interpolation colors
// strength colors
char **power_colors = NULL;
int power_steps = 0;
// Center resolution (size of circle)
int center_resolution = 2;
// Scatter resolution
int scatter_resolution = 2;

// Labels to draw
#define NETLABEL_SSID     0
#define NETLABEL_BSSID    1
#define NETLABEL_INFO     2
#define NETLABEL_MANUF    3
#define NETLABEL_LOCATION 4
vector<int> network_labels;

// Order to draw in
string draw_feature_order = "ptbrhscl";
// Color coding (1 = wep, 2 = channel)
int color_coding = 0;
#define COLORCODE_NONE    0
#define COLORCODE_WEP     1
#define COLORCODE_CHANNEL 2

// Threads, locks, and graphs to hold the power
#ifdef HAVE_PTHREAD
pthread_t *mapthread;
pthread_mutex_t power_lock;
pthread_mutex_t print_lock;
pthread_mutex_t power_pos_lock;
#endif
int numthreads = 1;
int *power_map;
unsigned int power_pos = 0;
int *power_input_map;

// AP and client maps
macmap<vector<manuf *> > ap_manuf_map;
macmap<vector<manuf *> > client_manuf_map;

// Filtered MAC's
int invert_filter = 0;
macmap<int> filter_map;

// Filtered types
map<wireless_network_type, int> type_filter_map;
int invert_type_filter;

// Exception/error catching
ExceptionInfo im_exception;

// Signal levels
int signal_lowest = 255;
int signal_highest = -255;

// Highest channel we've seen for plotting colors
int maxseen_channel = 0;

// Forward prototypes
string Mac2String(uint8_t *mac, char seperator);
string NetType2String(wireless_network_type in_type);
void UpdateGlobalCoords(float in_lat, float in_lon, float in_alt);
double rad2deg(double x);
double earth_distance(double lat1, double lon1, double lat2, double lon2);
double calcR (double lat);
void calcxy (double *posx, double *posy, double lat, double lon, double pixelfact, 
             double zero_lat, double zero_long);
int BestMapScale(long int *in_mapscale, long int *in_fetchscale, double tlat, 
        double tlon, double blat, double blon);
int ProcessGPSFile(char *in_fname);
void AssignNetColors();
void MergeNetData(vector<wireless_network *> in_netdata);
void ProcessNetData(int in_printstats);
void DrawNetTracks(vector< vector<track_data> > in_tracks, Image *in_img, 
                   DrawInfo *in_di);
void DrawNetCircles(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di);
void DrawNetBoundRects(vector<gps_network *> in_nets, Image *in_img, 
                       DrawInfo *in_di, int in_fill);
void DrawNetCenterDot(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di);
void DrawNetCenterText(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di);
int InverseWeight(int in_x, int in_y, int in_fuzz, double in_scale);
void DrawNetPower(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di);
void DrawNetHull(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di);
void DrawNetScatterPlot(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di);

int DrawLegendComposite(vector<gps_network *> in_nets, Image **in_img, DrawInfo **in_di);

int DrawFeatherCircle(int in_width, Image *in_img, int in_xpos, int in_ypos,
                      int concoffset, int in_opacity, float inner_perc, 
                      float outer_perc, PixelPacket circlecolor);
int IMStringWidth(const char *psztext, Image *in_img, DrawInfo *in_di);
int IMStringHeight(const char *psztext, Image *in_img, DrawInfo *in_di);

int IMStringWidth(const char *psztext, Image *in_img, DrawInfo *in_di) {
    ExceptionInfo ex;
    TypeMetric metrics;

    in_di->text = (char *) psztext;
    GetExceptionInfo(&ex);
    if (!GetTypeMetrics(in_img, in_di, &metrics)) {
        GetImageException(in_img, &ex);
        fprintf(stderr, "stringheight.. %s %s\n", ex.reason, ex.description);
        return 0;
    }

    in_di->text = NULL;

    return (int) fabs(metrics.width);
}

int IMStringHeight(const char *psztext, Image *in_img, DrawInfo *in_di) {
    ExceptionInfo ex;
    TypeMetric metrics;

    in_di->text = (char *) psztext;
    GetExceptionInfo(&ex);
    if (!GetTypeMetrics(in_img, in_di, &metrics)) {
        GetImageException(in_img, &ex);
        fprintf(stderr, "stringwidth... %s %s\n", ex.reason, ex.description);
        return 0;
    }

    in_di->text = NULL;

    return (int) fabs(metrics.height);
}

int DrawFeatherCircle(int in_width, Image *in_img, int in_xpos, int in_ypos,
                      int concoffset, int in_opacity, float inner_perc, float outer_perc,
                      PixelPacket circlecolor) {
    // Do special voodoo here to make a series of concentric circles
    int nconcentric = (int) rintf(((in_width * outer_perc) - 
                                   (in_width * inner_perc)) / concoffset);

    // Allocate the width of the circle + 50%, odd-sized so we get
    // a center pixel we can span out from
    int extwidth = (int) (in_width * outer_perc);
    // Give us plenty of room around the image
    int circlewidth = (int) (extwidth * 4);
    // Center pixel that we draw the network around
    int centerpoint = (circlewidth / 2);

    unsigned char *pixdata;
    unsigned char *apixdata;

    // Printable hex string and color info
    char clrstr[8];
    PixelPacket alphacolor;

    ExceptionInfo excep;
    GetExceptionInfo(&excep);

    Image *alpha_img = NULL;
    ImageInfo *alpha_info = CloneImageInfo((ImageInfo *) NULL);
    DrawInfo *alpha_di = NULL;
    
    Image *base_img = NULL;
    ImageInfo *base_info = CloneImageInfo((ImageInfo *) NULL);
    DrawInfo *base_di = NULL;

    char prim[1024];

    // Allocate space for the image and the alpha image
    pixdata = (unsigned char *) malloc(sizeof(unsigned char) * 
                                       (circlewidth * circlewidth) * 4);
    apixdata = (unsigned char *) malloc(sizeof(unsigned char) * 
                                        (circlewidth * circlewidth));
    memset(pixdata, 0, sizeof(unsigned char) * (circlewidth * circlewidth) * 4);
    memset(apixdata, 0, sizeof(unsigned char) * (circlewidth * circlewidth));

    // Allocate the RGB+Alpha channel image
    base_img = ConstituteImage(circlewidth, circlewidth, "RGBA", CharPixel,
                               pixdata, &excep);
    if (excep.severity != UndefinedException) {
        fprintf(stderr, "WARNING: ConstituteImage failed for base\n");
        CatchException(&excep);
        return -1;
    }

    // Allocate an intensity-only image to build the alpha channel into
    alpha_img = ConstituteImage(circlewidth, circlewidth, "I", CharPixel,
                                apixdata, &excep);
    if (excep.severity != UndefinedException) {
        fprintf(stderr, "WARNING: ConstituteImage failed for alpha channel\n");
        CatchException(&excep);
        return -1;
    }


    base_di = CloneDrawInfo(base_info, NULL);
    alpha_di = CloneDrawInfo(alpha_info, NULL);

    int opac = 0;
    int max_opac = (int) rintf((float) 255 * 
                               ((float) in_opacity / (float) 100));
    for (int x = (int) (in_width * outer_perc) + centerpoint;
         x >= centerpoint + (in_width * inner_perc) && nconcentric > 1; 
         x -= concoffset) {
        if ((opac = opac + (max_opac / (nconcentric - 1))) > max_opac)
            opac = max_opac;
        snprintf(clrstr, 8, "#%02X%02X%02X", opac, opac, opac);

        QueryColorDatabase(clrstr, &alphacolor, &excep);
        if (im_exception.severity != UndefinedException) {
            fprintf(stderr, "WARNING: QueryColorDatabase failed for %s\n", 
                    clrstr);
            CatchException(&excep);
            return -1;
        }
        alpha_di->fill = alphacolor;

        snprintf(prim, 1024, "fill-opacity %d%% circle %d,%d %d,%d",
                 in_opacity, centerpoint, centerpoint, x, x);
        alpha_di->primitive = prim;

        DrawImage(alpha_img, alpha_di);
        GetImageException(alpha_img, &excep);
        if (excep.severity != UndefinedException) {
            fprintf(stderr, "WARNING: DrawImage failed for %s\n", prim);
            CatchException(&excep);
            return -1;
        }

    }

    // Draw the center itself
    snprintf(clrstr, 8, "#%02X%02X%02X", max_opac, max_opac, max_opac);
    QueryColorDatabase(clrstr, &alphacolor, &excep);
    if (excep.severity != UndefinedException) {
        fprintf(stderr, "WARNING: QueryColorDatabase failed for %s\n", clrstr);
        CatchException(&excep);
        return -1;
    }
    alpha_di->fill = alphacolor;

    snprintf(prim, 1024, "fill-opacity 100%% circle %d,%d %d,%d",
             centerpoint, centerpoint, 
             centerpoint + (int) (in_width * inner_perc),
             centerpoint + (int) (in_width * inner_perc));
    alpha_di->primitive = prim;

    DrawImage(alpha_img, alpha_di);
    GetImageException(alpha_img, &excep);
    if (excep.severity != UndefinedException) {
        fprintf(stderr, "WARNING: DrawImage failed for %s\n", prim);
        CatchException(&excep);
        return -1;
    }

    alpha_img->matte = (MagickBooleanType) false;
    // Draw a simple color over the entire base and let the alpha channel
    // control where it gets drawn
    base_di->fill = circlecolor;
    snprintf(prim, 1024, "fill-opacity 100%% rectangle 0,0 %d,%d",
             circlewidth, circlewidth);
    base_di->primitive = prim;

    DrawImage(base_img, base_di);
    GetImageException(base_img, &excep);
    if (excep.severity != UndefinedException) {
        fprintf(stderr, "WARNING: DrawImage failed for %s\n", prim);
        CatchException(&excep);
        return -1;
    }

    // Now we composite the alpha channel into our base image
    CompositeImage(base_img, CopyOpacityCompositeOp, alpha_img, 0, 0);

    CompositeImage(in_img, OverCompositeOp, base_img, 
                   (int) (in_xpos - (circlewidth / 2)),
                   (int) (in_ypos - (circlewidth / 2)));

    alpha_di->text = strdup("");
    alpha_di->primitive = strdup("");

    DestroyImageInfo(alpha_info);
    DestroyDrawInfo(alpha_di);
    DestroyImage(alpha_img);

    base_di->text = strdup("");
    base_di->primitive = strdup("");

    DestroyImageInfo(base_info);
    DestroyDrawInfo(base_di);
    DestroyImage(base_img);

    free(pixdata);
    free(apixdata);

    return (circlewidth);
}

string Mac2String(uint8_t *mac, char seperator) { /*FOLD00*/
    char tempstr[MAC_STR_LEN];

    // There must be a better way to do this...
    if (seperator != '\0')
        snprintf(tempstr, MAC_STR_LEN, "%02X%c%02X%c%02X%c%02X%c%02X%c%02X",
                 mac[0], seperator, mac[1], seperator, mac[2], seperator,
                 mac[3], seperator, mac[4], seperator, mac[5]);
    else
        snprintf(tempstr, MAC_STR_LEN, "%02X%02X%02X%02X%02X%02X",
                 mac[0], mac[1], mac[2],
                 mac[3], mac[4], mac[5]);

    string temp = tempstr;
    return temp;
}

string NetType2String(wireless_network_type in_type) {
    if (in_type == network_ap)
        return "ap";
    if (in_type == network_adhoc)
        return "adhoc";
    if (in_type == network_probe)
        return "probe";
    if (in_type == network_turbocell)
        return "turbocell";
    if (in_type == network_data)
        return "data";

    return "unknown";
}

void UpdateGlobalCoords(float in_lat, float in_lon, float in_alt) {
    if (in_lat > global_map_avg.max_lat || global_map_avg.max_lat == 90)
        global_map_avg.max_lat = in_lat;
    if (in_lat < global_map_avg.min_lat || global_map_avg.min_lat == -90)
        global_map_avg.min_lat = in_lat;

    if (in_lon > global_map_avg.max_lon || global_map_avg.max_lon == 180)
        global_map_avg.max_lon = in_lon;
    if (in_lon < global_map_avg.min_lon || global_map_avg.min_lon == -180)
        global_map_avg.min_lon = in_lon;

    if (in_alt > global_map_avg.max_alt || global_map_avg.max_alt == 0)
        global_map_avg.max_alt = in_alt;
    if (in_alt < global_map_avg.min_alt || global_map_avg.min_alt == 0)
        global_map_avg.min_alt = in_alt;

}

void MergeNetData(vector<wireless_network *> in_netdata) {
    for (unsigned int x = 0; x < in_netdata.size(); x++) {
        wireless_network *inet = in_netdata[x];

        map<mac_addr, wireless_network *>::iterator bnmi = 
            bssid_net_map.find(inet->bssid);
        if (bnmi != bssid_net_map.end()) {
            wireless_network *onet = bnmi->second;

            // Update stuff if it's info we don't have, period

            if (onet->type > inet->type)
                onet->type = inet->type;

            if (onet->ssid == "")
                onet->ssid = inet->ssid;

            if (onet->channel == 0)
                onet->channel = inet->channel;

            if (onet->beacon_info == "")
                onet->beacon_info = inet->beacon_info;

            if (onet->ipdata.atype < inet->ipdata.atype)
                memcpy(&onet->ipdata, &inet->ipdata, sizeof(net_ip_data));

            if (onet->last_time < inet->last_time) {
                // Update stuff if it's better in the newer data.  This may cause a
                // double-update but this only happens once in a massively CPU intensive
                // utility so I don't care.
                onet->last_time = inet->last_time;

                if (inet->ssid != "")
                    onet->ssid = inet->ssid;

                if (inet->channel != 0)
                    onet->channel = inet->channel;

                if (inet->beacon_info != "")
                    onet->beacon_info = inet->beacon_info;

                onet->cloaked = inet->cloaked;
                onet->crypt_set = inet->crypt_set;
            }

            if (onet->first_time < inet->first_time)
                onet->first_time = inet->first_time;

            onet->llc_packets += inet->llc_packets;
            onet->data_packets += inet->data_packets;
            onet->crypt_packets += inet->crypt_packets;
            onet->interesting_packets += inet->interesting_packets;
        } else {
            bssid_net_map[inet->bssid] = inet;
        }
    }
}

int ProcessGPSFile(char *in_fname) {
    int file_samples = 0;

#ifdef HAVE_LIBZ
    gzFile gpsfz;
#else
    FILE *gpsf;
#endif

    vector<gps_point *> file_points;
    map<int, int> file_screen;
    vector<wireless_network *> file_networks;
    int cached = -1;

    // Look for a cache of the file, first
    if (cache_disable == 0 &&
        (cached = ReadGpsCacheFile(in_fname, &file_networks, &file_points)) >= 0) {
        fprintf(stderr, "NOTICE: Reading cached data for %s\n", in_fname);
    }

    if (cached < 0) {
#ifdef HAVE_LIBZ
        if ((gpsfz = gzopen(in_fname, "rb")) == NULL) {
            fprintf(stderr, "FATAL:  Could not open data file\n");
            return -1;
        }
#else
        if ((gpsf = fopen(in_fname, "r")) == NULL) {
            fprintf(stderr, "FATAL:  Could not open data file.\n");
            return -1;
        }
#endif

        fprintf(stderr, "NOTICE:  Processing gps file '%s'\n", in_fname);

#ifdef HAVE_LIBZ
        file_points = XMLFetchGpsList(gpsfz);
#else
        file_points = XMLFetchGpsList(gpsf);
#endif

        // We handle the points themselves after we handle the network component

#ifdef HAVE_LIBZ
        gzclose(gpsfz);
#else
        fclose(gpsf);
#endif

        // We have all our gps points loaded into the local struct now, so if they had a
        // network file specified, load the networks from that and mesh it with the network
        // data we already (may) have from ther files.

        int foundnetfile = 0;
        string comp;

        if ((comp = XMLFetchGpsNetfile()) != "") {
            if (verbose)
                fprintf(stderr, "NOTICE:  Reading associated network file, '%s'\n", 
                        XMLFetchGpsNetfile().c_str());
#ifdef HAVE_LIBZ
            if ((gpsfz = gzopen(XMLFetchGpsNetfile().c_str(), "r")) == NULL) {
                if (verbose)
                    fprintf(stderr, "WARNING:  Could not open associated network "
                            "xml file '%s'.\n", XMLFetchGpsNetfile().c_str());
            } else {
                foundnetfile = 1;
            }

            // Try our alternate file methods

            if (foundnetfile == 0) {
                comp = XMLFetchGpsNetfile();
                comp += ".gz";

                if ((gpsfz = gzopen(comp.c_str(), "r")) == NULL) {
                    if (verbose)
                        fprintf(stderr, "WARNING:  Could not open compressed network "
                                "xml file '%s'\n", comp.c_str());
                } else {
                    foundnetfile = 1;
                }
            }

            if (foundnetfile == 0) {
                string orignetfile = XMLFetchGpsNetfile();
                string origxmlfile = in_fname;

                // Prepend a ./ to the files if it isn't there
                if (origxmlfile[0] != '/' && origxmlfile[0] != '.')
                    origxmlfile = "./" + origxmlfile;
                if (orignetfile[0] != '/' && orignetfile[0] != '.')
                    orignetfile = "./" + orignetfile;

                // Break up the path to the gpsxml file and form a path based on that
                unsigned int lastslash = 0;
                for (string::size_type x = origxmlfile.find('/'); x != string::npos;
                     lastslash = x, x = origxmlfile.find('/', lastslash+1)) {
                    // We don't actually need to do anything...
                }

                comp = origxmlfile.substr(0, lastslash);

                lastslash = 0;
                for (string::size_type x = orignetfile.find('/'); x != string::npos;
                     lastslash = x, x = orignetfile.find('/', lastslash+1)) {
                    // We don't actually need to do anything...
                }

                comp += "/" + orignetfile.substr(lastslash, orignetfile.size() - lastslash);

                if (comp != origxmlfile) {
                    if ((gpsfz = gzopen(comp.c_str(), "r")) == NULL) {
                        if (verbose)
                            fprintf(stderr, "WARNING:  Could not open network xml file "
                                    "relocated to %s\n", comp.c_str());
                    } else {
                        foundnetfile = 1;
                    }

                    // And look again for our relocated compressed file.
                    if (foundnetfile == 0) {
                        comp += ".gz";
                        if ((gpsfz = gzopen(comp.c_str(), "r")) == NULL) {
                            if (verbose)
                                fprintf(stderr, "WARNING:  Could not open compressed "
                                        "network xml file relocated to %s\n",
                                        comp.c_str());
                        } else {
                            foundnetfile = 1;
                        }
                    }
                }
            }

#else
            if ((gpsf = fopen(XMLFetchGpsNetfile().c_str(), "r")) == NULL) {
                if (verbose)
                    fprintf(stderr, "WARNING:  Could not open associated network "
                            "xml file '%s'\n", XMLFetchGpsNetfile().c_str());
            } else {
                foundnetfile = 1;
            }

            // Try our alternate file methods

            if (foundnetfile == 0) {
                string orignetfile = XMLFetchGpsNetfile();
                string origxmlfile = in_fname;

                // Prepend a ./ to the files if it isn't there
                if (origxmlfile[0] != '/' && origxmlfile[0] != '.')
                    origxmlfile = "./" + origxmlfile;
                if (orignetfile[0] != '/' && orignetfile[0] != '.')
                    orignetfile = "./" + orignetfile;

                // Break up the path to the gpsxml file and form a path based on that
                unsigned int lastslash = 0;
                for (unsigned int x = origxmlfile.find('/'); x != string::npos;
                     lastslash = x, x = origxmlfile.find('/', lastslash+1)) {
                    // We don't actually need to do anything...
                }

                comp = origxmlfile.substr(0, lastslash);

                lastslash = 0;
                for (unsigned int x = orignetfile.find('/'); x != string::npos;
                     lastslash = x, x = orignetfile.find('/', lastslash+1)) {
                    // We don't actually need to do anything...
                }

                comp += "/" + orignetfile.substr(lastslash, orignetfile.size() - lastslash - 1);

                if (comp != origxmlfile) {
                    if ((gpsf = fopen(comp.c_str(), "r")) == NULL) {
                        if (verbose)
                            fprintf(stderr, "WARNING:  Could not open network xml file "
                                    "relocated to %s\n", comp.c_str());
                    } else {
                        foundnetfile = 1;
                    }

                }
            }

#endif

            if (foundnetfile) {
                fprintf(stderr, "NOTICE:  Opened associated network xml file '%s'\n", 
                        comp.c_str());

                if (verbose)
                    fprintf(stderr, "NOTICE:  Processing network XML file.\n");

#ifdef HAVE_LIBZ
                file_networks = XMLFetchNetworkList(gpsfz);
#else
                file_networks = XMLFetchNetworkList(gpsf);
#endif
                if (file_networks.size() == 0) {
                    fprintf(stderr, "WARNING:  No network entries found in '%s'.\n",
                            XMLFetchGpsNetfile().c_str());
                }
#ifdef HAVE_LIBZ
                gzclose(gpsfz);
#else
                fclose(gpsf);
#endif
            }
        }
    }

    file_samples = file_points.size();

    if (cache_disable == 0 && cached < 0) {
        fprintf(stderr, "NOTICE: Caching GPS file %s\n", in_fname);
        WriteGpsCacheFile(in_fname, &file_networks, &file_points);
    }

    // Do this after caching so we don't keep reparsing empty files
    if (file_samples == 0) {
        fprintf(stderr, "WARNING:  No sample points found in '%s'.\n", in_fname);
        return 0;
    }

    // We have the file correctly, so add to our gps track count
    vector<track_data> trak;
    track_vec.push_back(trak);
    num_tracks++;

    if (file_networks.size() != 0)
        MergeNetData(file_networks);

    // Now that we have the network data (hopefully) loaded, we'll load the points and
    // reference the networks for them.
    int last_power = 0;
    int power_count = 0;

    // Bail if we don't have enough samples to make it worth it.
    if (file_points.size() < 50) {
        fprintf(stderr, "WARNING:  Skipping file '%s', too few sample points to get "
                "valid data.\n", in_fname);
        return 1;
    }
    
    // Sanitize the data and build the map of points we don't look at
    if (verbose)
        fprintf(stderr, "NOTICE:  Sanitizing %zd sample points...\n", 
                file_points.size());
    SanitizeSamplePoints(file_points, &file_screen);

    int valid_filepoints = 0;

    for (unsigned int i = 0; i < file_points.size(); i++) {
        if (file_screen.find(file_points[i]->id) != file_screen.end()) {
            if (verbose)
                fprintf(stderr, "Removing invalid point %f,%f id %d from "
                        "consideration...\n", file_points[i]->lat, 
                        file_points[i]->lon, file_points[i]->id);
            continue;
        }

        // All we have to do here is push the points into the network (and make them
        // one if it doesn't exist).  We crunch all the data points in ProcessNetData
        gps_network *gnet = NULL;

        // Don't process filtered macs at all.
        //macmap<int>::iterator fitr = 
        //    filter_map.find(mac_addr(file_points[i]->bssid));
        if (((invert_filter == 0 && 
             filter_map.find(file_points[i]->bssid) != filter_map.end()) ||
            (invert_filter == 1 && 
             filter_map.find(file_points[i]->bssid) == filter_map.end())) &&
            (strncmp(file_points[i]->bssid, gps_track_bssid, 17) != 0)) {
            continue;
        }

        // Don't process unfixed points at all
        if (file_points[i]->fix < 2)
            continue;

        valid_filepoints++;

        double lat, lon, alt, spd;
        int fix;

        lat = file_points[i]->lat;
        lon = file_points[i]->lon;
        alt = file_points[i]->alt;
        spd = file_points[i]->spd;
        fix = file_points[i]->fix;

        if (file_points[i]->signal != 0)
            power_data = 1;

        // Only include tracks in the size of the map if we're going to draw them
        int trackdata = strncmp(file_points[i]->bssid, gps_track_bssid, MAC_STR_LEN);
        if ((draw_track && trackdata == 0) || trackdata != 0) {
            global_map_avg.avg_lon += lon;
            global_map_avg.avg_alt += alt;
            global_map_avg.avg_spd += spd;
            global_map_avg.count++;

            UpdateGlobalCoords(lat, lon, alt);
        }

        if (trackdata == 0) {
            track_data tdat;

            tdat.x = 0;
            tdat.y = 0;

            tdat.lat = lat;
            tdat.lon = lon;
            tdat.alt = alt;
            tdat.spd = spd;

            tdat.version = (int) XMLFetchGpsVersion();

            // Filter power ratings
            if (file_points[i]->signal == last_power) {
                if (power_count < 3) {
                    tdat.power = file_points[i]->signal;
                    tdat.quality = file_points[i]->quality;
                    tdat.noise = file_points[i]->noise;
                } else {
                    tdat.power = 0;
                    tdat.quality = 0;
                    tdat.noise = 0;
                }
                power_count++;
            } else {
                last_power = file_points[i]->signal;
                power_count = 0;
                tdat.power = file_points[i]->signal;
                tdat.quality = file_points[i]->quality;
                tdat.noise = file_points[i]->noise;
            }

            track_vec[num_tracks-1].push_back(tdat);
        } else if (bssid_gpsnet_map.find(file_points[i]->bssid) == bssid_gpsnet_map.end()) {
            //printf("making new netork: %s\n", file_points[i]->bssid);
            gnet = new gps_network;

            gnet->bssid = file_points[i]->bssid;

            if (bssid_net_map.find(file_points[i]->bssid) != bssid_net_map.end()) {
                gnet->wnet = bssid_net_map[file_points[i]->bssid];

                // Set filter bit as we create it
                /*
                if (type_filter.length() != 0)
                    if (((invert_type_filter == 0 && type_filter.find(NetType2String(gnet->wnet->type)) != string::npos) ||
                         (invert_type_filter == 1 && type_filter.find(NetType2String(gnet->wnet->type)) == string::npos))) {
                        gnet->filtered = 1;;
                    }
                    */
                if ((invert_type_filter == 0 && 
                     type_filter_map.find(gnet->wnet->type) != type_filter_map.end()) ||
                    (invert_type_filter == 1 &&
                     type_filter_map.find(gnet->wnet->type) == type_filter_map.end())) {
                    gnet->filtered = 1;
                }

            } else {
                gnet->wnet = NULL;
            }

            gnet->points.push_back(file_points[i]);

            bssid_gpsnet_map[file_points[i]->bssid] = gnet;

            UpdateGlobalCoords(lat, lon, alt);

        } else {
            gnet = bssid_gpsnet_map[file_points[i]->bssid];

            gnet->points.push_back(file_points[i]);

            UpdateGlobalCoords(lat, lon, alt);

        }
    }

    if (verbose)
        fprintf(stderr, "%s contains %d valid samples.\n", in_fname, valid_filepoints);

    sample_points += valid_filepoints;

    return 1;
}

// Do all the math
void ProcessNetData(int in_printstats) {
    // Convert the tracks to x,y
    if (draw_track != 0 || draw_power != 0) {
        for (unsigned int vec = 0; vec < track_vec.size(); vec++) {
            for (unsigned int x = 0; x < track_vec[vec].size(); x++) {
                double track_tx, track_ty;
                calcxy(&track_tx, &track_ty, track_vec[vec][x].lat, track_vec[vec][x].lon,
                       (double) map_scale/PIXELFACT, map_avg_lat, map_avg_lon);

                track_vec[vec][x].x = (int) track_tx;
                track_vec[vec][x].y = (int) track_ty;
            }

            if (in_printstats)
                printf("Track %d: %d samples.\n", vec, (int) track_vec[vec].size());
        }
    }

    printf("Processing %d raw networks.\n", (int) bssid_gpsnet_map.size());

    for (map<string, gps_network *>::const_iterator x = bssid_gpsnet_map.begin();
         x != bssid_gpsnet_map.end(); ++x) {

        gps_network *map_iter = x->second;


        if (map_iter->points.size() <= 1) {
           // printf("net %s only had <= 1 point.\n", map_iter->bssid.c_str());
            continue;
        }

        // Intelligent center guessing
        mpf_t alat;
        mpf_t alon;

        mpf_init(alat);
        mpf_init(alon);

        vector<gps_point *> relvec;

        // We need this for interpolation as well as center averaging... 
        // calculate it and assign it
        if (pure_center_average == 0 || draw_power) 
            map_iter->center_points = RelevantCenterPoints(map_iter->points);
      
        // Do we average all the points or use the new smarter relevance
        if (pure_center_average == 0)
            relvec = map_iter->center_points;
        else
            relvec = map_iter->points;

        for (unsigned int y = 0; y < relvec.size(); y++) {
            mpf_t lat, lon;
            mpf_init_set_d(lat, relvec[y]->lat);
            mpf_init_set_d(lon, relvec[y]->lon);

            mpf_add(alat, alat, lat);
            mpf_add(alon, alon, lon);
            
            map_iter->avg_alt += relvec[y]->alt;
            map_iter->avg_spd += relvec[y]->spd;
        }

        mpf_div_ui(alat, alat, relvec.size());
        mpf_div_ui(alon, alon, relvec.size());

        double avg_lat = mpf_get_d(alat);
        double avg_lon = mpf_get_d(alon);
        
        float avg_alt = (float) (map_iter->avg_alt / relvec.size());
        float avg_spd = (float) (map_iter->avg_spd / relvec.size());

        map_iter->avg_lat = avg_lat;
        map_iter->avg_lon = avg_lon;
        map_iter->avg_alt = avg_alt;
        map_iter->avg_spd = avg_spd;

        // Calculate the min/max and average sizes of this network
        for (unsigned int y = 0; y < map_iter->points.size(); y++) {
            float lat = map_iter->points[y]->lat;
            float lon = map_iter->points[y]->lon;
            float alt = map_iter->points[y]->alt;

            //printf("Got %f %f %f %f\n", lat, lon, alt, spd);
            map_iter->count++;

            // Enter the max/min values
            if (lat > map_iter->max_lat || map_iter->max_lat == 90)
                map_iter->max_lat = lat;

            if (lat < map_iter->min_lat || map_iter->min_lat == -90)
                map_iter->min_lat = lat;

            if (lon > map_iter->max_lon || map_iter->max_lon == 180)
                map_iter->max_lon = lon;

            if (lon < map_iter->min_lon || map_iter->min_lon == -180)
                map_iter->min_lon = lon;

            if (alt > map_iter->max_alt || map_iter->max_alt == 0)
                map_iter->max_alt = alt;

            if (alt < map_iter->min_alt || map_iter->min_alt == 0)
                map_iter->min_alt = alt;
        }

        map_iter->diagonal_distance = earth_distance(map_iter->max_lat, 
                map_iter->max_lon, map_iter->min_lat, map_iter->min_lon);

        map_iter->altitude_distance = map_iter->max_alt - map_iter->min_alt;

        if ((map_iter->diagonal_distance * 3.3) > (20 * 5280))
            printf("WARNING:  Network %s [%s] has range greater than 20 miles, this "
                   "may be a glitch you want to filter.\n", 
                   map_iter->wnet == NULL ? "Unknown" : map_iter->wnet->ssid.c_str(),
                   map_iter->bssid.c_str());
        
        if (in_printstats)
            printf("Net:     %s [%s]\n"
                   "  Samples : %d\n"
                   "  Min lat : %f\n"
                   "  Min lon : %f\n"
                   "  Max lat : %f\n"
                   "  Max lon : %f\n"
                   "  Min alt : %f\n"
                   "  Max Alt : %f\n"
                   "  Avg Lat : %f\n"
                   "  Avg Lon : %f\n"
                   "  Avg Alt : %f\n"
                   "  Avg Spd : %f\n"
                   "  H. Range: %f ft\n"
                   "  V. Range: %f ft\n",
                   map_iter->wnet == NULL ? "Unknown" : map_iter->wnet->ssid.c_str(),
                   map_iter->bssid.c_str(),
                   map_iter->count,
                   map_iter->min_lat, map_iter->min_lon,
                   map_iter->max_lat, map_iter->max_lon,
                   map_iter->min_alt, map_iter->max_alt,
                   map_iter->avg_lat, map_iter->avg_lon,
                   map_iter->avg_alt, map_iter->avg_spd,
                   map_iter->diagonal_distance * 3.3, map_iter->altitude_distance);
    }
}

void AssignNetColors() {
    int base_color = 1;

    for (map<string, gps_network *>::const_iterator x = bssid_gpsnet_map.begin();
         x != bssid_gpsnet_map.end(); ++x) {

        gps_network *map_iter = x->second;

        if (map_iter->filtered)
            continue;

        if (color_coding == COLORCODE_WEP) {
            if (map_iter->wnet != NULL) {
                if (map_iter->wnet->type == network_adhoc || map_iter->wnet->type == network_probe)
                    map_iter->wnet->manuf_ref = MatchBestManuf(&client_manuf_map, map_iter->wnet->bssid,
                                                               map_iter->wnet->ssid, map_iter->wnet->channel,
                                                               map_iter->wnet->crypt_set, map_iter->wnet->cloaked,
                                                               &map_iter->wnet->manuf_score);
                else
                    map_iter->wnet->manuf_ref = MatchBestManuf(&ap_manuf_map, map_iter->wnet->bssid,
                                                               map_iter->wnet->ssid, map_iter->wnet->channel,
                                                               map_iter->wnet->crypt_set, map_iter->wnet->cloaked,
                                                               &map_iter->wnet->manuf_score);

                if (map_iter->wnet->manuf_score == manuf_max_score) {
                    map_iter->color_index = "#0000FF";
                } else if (map_iter->wnet->crypt_set) {
                    map_iter->color_index = "#FF0000";
                } else {
                    map_iter->color_index = "#00FF00";
                }
            } else {
                map_iter->color_index = "#00FF00";
            }
        } else if (color_coding == COLORCODE_CHANNEL) {
            if (map_iter->wnet != NULL) {
                if (map_iter->wnet->channel < 1 || map_iter->wnet->channel > 14) {
                    map_iter->color_index = channelcolors[0];
                } else {
                    // Track the highest network channel we've seen
                    if (map_iter->wnet->channel > maxseen_channel)
                        maxseen_channel = map_iter->wnet->channel;

                    map_iter->color_index = channelcolors[map_iter->wnet->channel - 1];
                }
            } else {
                map_iter->color_index = channelcolors[0];
            }
        } else {
            if (netcolors[base_color] == NULL)
                base_color = 1;

            map_iter->color_index = netcolors[base_color];

            base_color++;
        }
    }
}


// Faust Code to convert rad to deg and find the distance between two points
// on the globe.  Thanks, Faust.
//const float M_PI = 3.14159;

//double rad2deg(double x) { /*FOLD00*/
//     return x*M_PI/180.0;
//}
#define rad2deg(x) ((double)((x)*M_PI/180.0))

double earth_distance(double lat1, double lon1, double lat2, double lon2) { /*FOLD00*/

    /*
    double calcedR1 = calcR(lat1);
    double calcedR2 = calcR(lat2);

    double sinradi1 = sin(rad2deg(90-lat1));
    double sinradi2 = sin(rad2deg(90-lat2));
    
    double x1 = calcedR1 * cos(rad2deg(lon1)) * sinradi1;
    double x2 = calcedR2 * cos(rad2deg(lon2)) * sinradi2;
    double y1 = calcedR1 * sin(rad2deg(lon1)) * sinradi1;
    double y2 = calcedR2 * sin(rad2deg(lon2)) * sinradi2;
    double z1 = calcedR1 * cos(rad2deg(90-lat1));
    double z2 = calcedR2 * cos(rad2deg(90-lat2));
    
    double calcedR = calcR((double)(lat1+lat2)) / 2;
    double a = acos((x1*x2 + y1*y2 + z1*z2)/square(calcedR));
    */

     double x1 = calcR(lat1) * cos(rad2deg(lon1)) * sin(rad2deg(90-lat1));
     double x2 = calcR(lat2) * cos(rad2deg(lon2)) * sin(rad2deg(90-lat2));
     double y1 = calcR(lat1) * sin(rad2deg(lon1)) * sin(rad2deg(90-lat1));     
     double y2 = calcR(lat2) * sin(rad2deg(lon2)) * sin(rad2deg(90-lat2));
     double z1 = calcR(lat1) * cos(rad2deg(90-lat1));
     double z2 = calcR(lat2) * cos(rad2deg(90-lat2));   
     double a = acos((x1*x2 + y1*y2 + z1*z2)/pow(calcR((double) (lat1+lat2)/2),2));
    
    return calcR((double) (lat1+lat2) / 2) * a;
}

// Lifted from gpsdrive 1.7
// CalcR gets the radius of the earth at a particular latitude
// calcxy finds the x and y positions on a 1280x1024 image of a certian scale
//  centered on a given lat/lon.

// This pulls the "real radius" of a lat, instead of a global guesstimate
double calcR (double lat) /*FOLD00*/
{
    double a = 6378.137, r, sc, x, y, z;
    double e2 = 0.081082 * 0.081082;
    /*
     the radius of curvature of an ellipsoidal Earth in the plane of the
     meridian is given by

     R' = a * (1 - e^2) / (1 - e^2 * (sin(lat))^2)^(3/2)

     where a is the equatorial radius,
     b is the polar radius, and
     e is the eccentricity of the ellipsoid = sqrt(1 - b^2/a^2)

     a = 6378 km (3963 mi) Equatorial radius (surface to center distance)
     b = 6356.752 km (3950 mi) Polar radius (surface to center distance)
     e = 0.081082 Eccentricity
     */

    lat = lat * M_PI / 180.0;
    sc = sin (lat);
    x = a * (1.0 - e2);
    z = 1.0 - e2 * sc * sc;
    y = pow (z, 1.5);
    r = x / y;

    r = r * 1000.0;
    return r;
}

void calcxy (double *posx, double *posy, double lat, double lon, double pixelfact, /*FOLD00*/
        double zero_lat, double zero_long) {
    double dif;

    *posx = (calcR(lat) * M_PI / 180.0) * cos (M_PI * lat / 180.0) * (lon - zero_long);

    *posx = (map_width/2) + *posx / pixelfact;
    //*posx = *posx - xoff;

    *posy = (calcR(lat) * M_PI / 180.0) * (lat - zero_lat);

    dif = calcR(lat) * (1 - (cos ((M_PI * (lon - zero_long)) / 180.0)));

    *posy = *posy + dif / 1.85;
    *posy = (map_height/2) - *posy / pixelfact;

    *posx += draw_x_offset;
    *posy += draw_y_offset;

    //*posy = *posy - yoff;
}

// Find the best map scale for the 'rectangle' tlat,tlon
// This is a bit klugey and should be done better in the future.
int BestMapScale(long int *in_mapscale, long int *in_fetchscale, 
        double tlat, double tlon, double blat, double blon) { 
    double mapx, mapy;
    double map2x, map2y;

    if ((mapsource == MAPSOURCE_TERRA) || (mapsource == MAPSOURCE_TERRATOPO)) {
        for (int x = 0; terrascales[x] != -1; x++) {
            calcxy(&mapx, &mapy, tlat, tlon, 
                    (double) terrascales[x]/PIXELFACT, 
                    map_avg_lat, map_avg_lon);
            calcxy(&map2x, &map2y, blat, blon, 
                    (double) terrascales[x]/PIXELFACT, 
                    map_avg_lat, map_avg_lon);

            if ((mapx < 0 || mapx > map_width || mapy < 0 || 
                        mapy > map_height) ||
                    (map2x < 0 || map2x > map_width || 
                     map2y < 0 || map2y > map_height)) {
                continue;
            } else {
                (*in_mapscale) = terrascales[x];
                (*in_fetchscale) = x + 10;
                return 1;
            }
        }
        return -1;
    }

    if (mapsource == MAPSOURCE_EUEX) {
        for (int x = 0; euexscales[x] != -1; x++) {
            calcxy(&mapx, &mapy, tlat, tlon, 
                    (double) euexscales[x]/PIXELFACT, 
                    map_avg_lat, map_avg_lon);
            calcxy(&map2x, &map2y, blat, blon, 
                    (double) euexscales[x]/PIXELFACT, 
                    map_avg_lat, map_avg_lon);

            if ((mapx < 0 || mapx > map_width || mapy < 0 || 
                        mapy > map_height) ||
                    (map2x < 0 || map2x > map_width || 
                     map2y < 0 || map2y > map_height)) {
                continue;
            } else {
                (*in_mapscale) = euexscales[x];
                (*in_fetchscale) = x;
                return 1;
            }
        }
        return -1;
    }

    if (mapsource == MAPSOURCE_OSM) {
        for (int x = 0; osmscales[x] != -1; x++) {
            calcxy(&mapx, &mapy, tlat, tlon, 
                    (double) osmscales[x]/PIXELFACT, 
                    map_avg_lat, map_avg_lon);
            calcxy(&map2x, &map2y, blat, blon, 
                    (double) osmscales[x]/PIXELFACT, 
                    map_avg_lat, map_avg_lon);

            if ((mapx < 0 || mapx > map_width || mapy < 0 || 
                        mapy > map_height) ||
                    (map2x < 0 || map2x > map_width || 
                     map2y < 0 || map2y > map_height)) {
                continue;
            } else {
                (*in_mapscale) = osmscales[x];
                (*in_fetchscale) = x;
                return 1;
            }
        }
        return -1;
    }

    if (mapsource == MAPSOURCE_EARTHAMAPS) {
        // Find how many scales we have
        int nscales;
        for (nscales = 0; earthamapscales[nscales] != -1; nscales++) 
            ; // Nothing

        for (int x = (nscales - 1); x > 1; x--) {
            calcxy(&mapx, &mapy, tlat, tlon, 
                    (double) earthamapscales[x]/PIXELFACT, 
                    map_avg_lat, map_avg_lon);
            calcxy(&map2x, &map2y, blat, blon, 
                    (double) earthamapscales[x]/PIXELFACT, 
                    map_avg_lat, map_avg_lon);

            if ((mapx < 0 || mapx > map_width || mapy < 0 || 
                        mapy > map_height) ||
                    (map2x < 0 || map2x > map_width || 
                     map2y < 0 || map2y > map_height)) {
                continue;
            } else {
                (*in_mapscale) = earthamapscales[x];
                (*in_fetchscale) = x;
                return 1;
            }
        }

        return -1;
    }

    // Mapblast style scale finding
    for (int x = 0; scales[x] != -1; x++) {
        calcxy(&mapx, &mapy, tlat, tlon, (double) scales[x]/PIXELFACT, 
               map_avg_lat, map_avg_lon);
        calcxy(&map2x, &map2y, blat, blon, (double) scales[x]/PIXELFACT, 
               map_avg_lat, map_avg_lon);

        if ((mapx < 0 || mapx > map_width || mapy < 0 || mapy > map_height) ||
                (map2x < 0 || map2x > map_width || map2y < 0 || 
                 map2y > map_height)) {
            continue;
        } else {
            // Fudge the scale by 10% for extreme ranges
            if (scales[x] >= 1000000 && scales[x] < 20000000) {
                (*in_mapscale) = (long) (scales[x] + (scales[x] * 0.10)); 
            } else if (scales[x] >= 20000000) {
                (*in_mapscale) = (long) (scales[x] + (scales[x] * 0.15));
            } else {
                (*in_mapscale) = scales[x];
            }

            (*in_fetchscale) = (*in_mapscale);

            return 1;
        }

        return -1;
    }

    return -1;
}

// This new distance macro does not use the pow function, for 2 we can simply multiply
// which aves us ~800mio ops !!!!
#define geom_distance(a, b, x, y) sqrt(square((double) (a) - (double) (x)) + square((double) (b) - (double) (y)))

// Inverse weight calculations -- Shepard's with Frank and Nielson's improved 
// weight algorithm

// Keep track of stuff to save on math
typedef struct {
    int signal;
    double ldist;
} weight_point_rec;

int InverseWeight(int in_x, int in_y, int in_fuzz, double in_scale) { /*FOLD00*/
    int min_x = 0, min_y = 0;
    int max_x = map_width, max_y = map_height;

    int offset = (int)(200 * (double) (1 / in_scale));

    // Moved the abort to here, so we don't need to do the downward things
    if (offset == 0)
        return 0;

    if (in_x - offset > min_x)
        min_x = in_x - offset;
    if (in_y - offset > min_y)
        min_y = in_y - offset;
    if (in_x + offset < max_x)
        max_x = in_x + offset;
    if (in_y + offset < max_y)
        max_y = in_y + offset;

    /*
    fprintf(stderr, "influenced by %d range, %d %d from %d %d to %d %d\n",
            offset, in_x, in_y, min_x, min_y, max_x, max_y);
            */


    double power_sum = 0;

    vector<weight_point_rec> wpvec;

    // Find the farthest distance from the point we're at now thats within 
    // our range

    double maxdist = 0;
    weight_point_rec wprec;
    for (int cury = min_y; cury < max_y; cury++) {
        for (int curx = min_x; curx < max_x; curx++) {
            if (power_input_map[(map_width * cury) + curx] <= 0)
                continue;

            double ldist = sqrt(((in_x - curx)*(in_x - curx)) +
                    ((in_y - cury)*(in_y - cury)));

            if ((int) ldist > offset)
                continue;
            
            if (maxdist < ldist)
                maxdist = ldist;

            // Save our point data since we've calculated it already
            wprec.signal = power_input_map[(map_width * cury) + curx];
            wprec.ldist = ldist;
            wpvec.push_back(wprec);

        }
    }

    if (wpvec.size() == 0)
        return 0;

    // Find the sum of all distances for the bottom half of the eq
#if 0
    double bottom_sum = 0;
    for (unsigned int x = 0; x < wpvec.size(); x++) 
        bottom_sum += square((maxdist - wpvec[x].ldist)/
                (maxdist * wpvec[x].ldist));
#endif

    // Now get the weighting and add all the points
    for (unsigned int x = 0; x < wpvec.size(); x++)
        power_sum += square((maxdist - wpvec[x].ldist)/
                (maxdist * wpvec[x].ldist)) * wpvec[x].signal;

    return (int) power_sum;

}

void DrawNetTracks(Image *in_img, DrawInfo *in_di) { /*FOLD00*/
    // Our track color
    uint8_t track_r = 0x00, track_g = 0x00, track_b = 0xFF;
    char color_str[8];
    PixelPacket track_clr;

    // Draw each track
    for (unsigned int vec = 0; vec < track_vec.size(); vec++) {
        if (track_vec[vec].size() == 0)
            continue;

        // Generate the color we're drawing with
        snprintf(color_str, 8, "#%02X%02X%02X", track_r, track_g, track_b);

        ExceptionInfo excep;
        GetExceptionInfo(&excep);

        QueryColorDatabase(color_str, &track_clr, &excep);
        if (excep.severity != UndefinedException) {
            CatchException(&excep);
            break;
        }

        in_di->stroke = track_clr;

        // Dim the color
        track_b -= track_decay;

        // Reset it if we're "too dark"
        if (track_b < 0x50)
            track_b = 0xFF;

        // Initialize the previous track location vars

        int prev_tx, prev_ty;
        prev_tx = track_vec[vec][0].x;
        prev_ty = track_vec[vec][0].y;

        for (unsigned int x = 1; x < track_vec[vec].size(); x++) {
            char prim[1024];

            // If we don't have a previous vector (ie, the map data failed), set it
            // and continue
            if (prev_tx == -1 || prev_ty == -1) {
                prev_tx = track_vec[vec][x].x;
                prev_ty = track_vec[vec][x].y;
                continue;
            }

            // Scrap dupes
            if (track_vec[vec][x].x == (unsigned int) prev_tx &&
                track_vec[vec][x].y == (unsigned int) prev_ty)
                continue;

            // Scrap stuff entirely off-screen to save on speed
            if (((unsigned int) prev_tx > map_width && (unsigned int) prev_ty > map_height &&
                 track_vec[vec][x].x > map_width && track_vec[vec][x].y > map_height) ||
                (prev_tx < 0 && prev_ty < 0 &&
                 track_vec[vec][x].x < 0 && track_vec[vec][x].y < 0)) {

                continue;
            }

            // If the track jumps more than 50 meters in 1 second, assume we had a
            // problem and restart the track at the next position
            double distance;
            if ((distance = geom_distance(track_vec[vec][x].x, track_vec[vec][x].y,
                                          prev_tx, prev_ty)) > 50) {
                prev_tx = -1;
                prev_ty = -1;
                continue;
            }

            /* Don't whine about track jumps (for now)
            if (sqrt(pow(track_vec[vec][x].x - prev_tx, 2) + pow(track_vec[vec][x].y - prev_ty, 2)) > 20) {
                printf("Suspicious track record: %dx%d (%fx%f)\n"
                       "Prev: %dx%d (%fx%f)\n",
                       track_vec[vec][x].x, track_vec[vec][x].y,
                       track_vec[vec][x].lat, track_vec[vec][x].lon,
                       prev_tx, prev_ty,
                       track_vec[vec][x-1].lat, track_vec[vec][x-1].lon);
                       }
                       */

            // fill-opacity %d%% stroke-opacity %d%%
            snprintf(prim, 1024, "stroke-width %d line %d,%d %d,%d",
                     track_width,
                     prev_tx, prev_ty, track_vec[vec][x].x, track_vec[vec][x].y);

            //in_di->primitive = strdup(prim);
            in_di->primitive = prim;
            DrawImage(in_img, in_di);
            GetImageException(in_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                break;
            }

            prev_tx = track_vec[vec][x].x;
            prev_ty = track_vec[vec][x].y;
        }
    }
}

void DrawNetCircles(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di) { /*FOLD00*/
    for (unsigned int x = 0; x < in_nets.size(); x++) {
        gps_network *map_iter = in_nets[x];

        // Skip networks w/ no determined coordinates
        if (map_iter->max_lat == 90)
            continue;

        if (map_iter->diagonal_distance > horiz_throttle)
            continue;

        // Find the average distance to all the points in the network and use it as
        // the radius
        if (map_iter->points.size() == 0)
            continue;

        double mapx, mapy, endx, endy;
        calcxy (&mapx, &mapy, map_iter->avg_lat, map_iter->avg_lon,
                (double) map_scale/PIXELFACT, map_avg_lat, map_avg_lon);

        double distavg = 0;
        for (unsigned int y = 0; y < map_iter->points.size(); y++) {
            gps_point *pt = map_iter->points[y];

            double ptx, pty;
            calcxy(&ptx, &pty, pt->lat, pt->lon, (double) map_scale/PIXELFACT,
                   map_avg_lat, map_avg_lon);

            distavg += labs((long) geom_distance(mapx, mapy, ptx, pty));
        }
        distavg = distavg / map_iter->points.size();

        if (!finite(distavg))
            continue;

        endx = mapx + distavg;
        endy = mapy + distavg;

        if (!(((mapx - distavg > 0 && mapx - distavg < map_width) &&
               (mapy - distavg > 0 && mapy - distavg < map_width)) &&
              ((endx > 0 && endx < map_height) &&
               (endy > 0 && endy < map_height)))) {
            continue;
        } 
        
        drawn_net_map[map_iter->bssid.c_str()] = map_iter;
        
        PixelPacket netclr;

        ExceptionInfo excep;
        GetExceptionInfo(&excep);
        QueryColorDatabase(map_iter->color_index.c_str(), &netclr, &excep);
        if (excep.severity != UndefinedException) {
            fprintf(stderr, "WARNING: QueryColorDatabase failed for %s\n", 
                    map_iter->color_index.c_str());
            CatchException(&excep);
            break;
        }

        char prim[1024];
        int network_width = (int) distavg;

        // We want circles from 3/4 to 6/4 of the network range
        // in decreasing opacity, that are 8 pixels wide...  Do the concentric
        // calcs here to use them in testing if we draw feathers for this net
        int nconcentric = (int) (((network_width * 1.5) - 
                                  (network_width * 0.75)) / 8);

        if (feather_range && network_width > 16 && nconcentric > 1) {
            DrawFeatherCircle(network_width, in_img, (int) mapx, (int) mapy,
                              8, range_opacity, 0.75, 1.5, netclr);
        } else if (network_width > 0) {
            // Plot a transparent circle directly over our map
            in_di->fill = netclr;
            in_di->stroke = netclr;

            snprintf(prim, 1024, "fill-opacity %d%% stroke-opacity %d%% circle %d,%d %d,%d",
                     range_opacity, range_opacity, (int) mapx, (int) mapy, 
                     (int) endx, (int) endy);

            in_di->primitive = prim;
            DrawImage(in_img, in_di);
            GetImageException(in_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                fprintf(stderr, "WARNING: DrawImage failed for %s\n", prim);
                CatchException(&im_exception);
                break;
            }
        }
    }
}

double clockwize( int x0, int y0, int x1, int y1, int x2, int y2) { /*FOLD00*/
	return ( x2 - x0 ) * ( y1 - y0 ) - ( x1 - x0 ) * ( y2 - y0 );
}

void DrawNetHull(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di) { /*FOLD00*/
    for (unsigned int x = 0; x < in_nets.size(); x++) {
        gps_network *map_iter = in_nets[x];

        // Skip networks w/ no determined coordinates
        if (map_iter->max_lat == 90)
            continue;

        if (map_iter->diagonal_distance > horiz_throttle)
            continue;

        map<string, hullPoint> dim;
        for (unsigned int x = 0; x < map_iter->points.size(); x++) {
            gps_point *pt = map_iter->points[x];
            double mapx, mapy;

            calcxy (&mapx, &mapy, pt->lat, pt->lon,
                    (double) map_scale/PIXELFACT, map_avg_lat, map_avg_lon);

            // This is faily inefficient but what the hell.
            if ((mapx > 0 && mapx < map_width) || (mapy > 0 && mapy < map_height))
                drawn_net_map[map_iter->bssid.c_str()] = map_iter;

            char mm1[64];
            snprintf(mm1, 64, "%d,%d", (int) mapx, (int) mapy);
            string a = mm1;
            hullPoint b;
            b.x = (int) mapx;
            b.y = (int) mapy;
            b.angle = 0.0;
            b.xy = a;
            dim[a] = b;
	}

	// need at least 3 points for a hull

	//printf("\nPts: %d\n", dim.size());
	if (dim.size() < 3)
		continue;

	// got the unique points, now we need to sort em
        deque<hullPoint> pts;
	for (map<string, hullPoint>::const_iterator i = dim.begin(); i != dim.end(); ++i) {
		pts.push_back(i->second);
	}
	stable_sort(pts.begin(), pts.end());

	//start point for the hull
	hullPoint start = pts[0];
	pts.pop_front();

	//compute angles for pts
	for (deque<hullPoint>::iterator j = pts.begin(); j != pts.end(); ++j) {
		j->angle = atan2( j->y - start.y, j->x - start.x );
	}

	//sort against angle
	stable_sort(pts.begin(), pts.end(), hullPoint() );

	//build the hull
	vector<hullPoint> hull;
	hull.push_back(start);
	hullPoint tmp = pts[0];
	hull.push_back(tmp);
	pts.push_front(start);

        for (unsigned int k = 2; k < pts.size() ; k++) {
            while (clockwize(hull[hull.size()-2].x,
                             hull[hull.size()-2].y,
                             hull[hull.size()-1].x,
                             hull[hull.size()-1].y,
                             pts[k].x,
                             pts[k].y) >= 0
                   && hull.size() >= 2) {
                hull.pop_back();
            }
            hull.push_back(pts[k]);
        }

        if (hull.size() < 3)
            continue;
			
	//wheh
        /*
         printf("Hull:\n");
         for(vector<hullPoint>::const_iterator l = hull.begin(); l != hull.end(); ++l) {
         printf("x: %d y: %d a: %f\n", l->x, l->y, l->angle);
         }
         printf("orig:\n");
         for(deque<hullPoint>::const_iterator l = pts.begin(); l != pts.end(); ++l) {
         printf("x: %d y: %d a: %f\n", l->x, l->y, l->angle);
         }
         */

        PixelPacket netclr;

        ExceptionInfo excep;
        GetExceptionInfo(&excep);
        QueryColorDatabase(map_iter->color_index.c_str(), &netclr, &excep);
        if (excep.severity != UndefinedException) {
            CatchException(&excep);
            break;
        }

        in_di->fill = netclr;

        string sep = ", ";
        string pstr = "";
        for(vector<hullPoint>::const_iterator l = hull.begin(); l != hull.end(); ++l) {
            pstr = pstr + l->xy + sep;
	}
        pstr = pstr + start.xy;

        char pstr2[2048];
        memset(pstr2, 0, sizeof(char)*2048);
	pstr.copy(pstr2, string::npos);

	char prim[2048];
        snprintf(prim, 1024, "fill-opacity %d%% stroke-opacity %d%% polygon %s",
                 hull_opacity, hull_opacity, pstr2);

	//printf("%s\n", prim);
	
        in_di->primitive = prim;
        DrawImage(in_img, in_di);
        GetImageException(in_img, &im_exception);
        if (im_exception.severity != UndefinedException) {
            CatchException(&im_exception);
            break;
        }

    }

}

void DrawNetBoundRects(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di, /*FOLD00*/
                       int in_fill) {
    for (unsigned int x = 0; x < in_nets.size(); x++) {
        gps_network *map_iter = in_nets[x];

        // Skip networks w/ no determined coordinates
        if (map_iter->max_lat == 90)
            continue;

        if (isnan(map_iter->diagonal_distance) || map_iter->diagonal_distance == 0 || 
            map_iter->diagonal_distance > horiz_throttle)
            continue;

        // Figure x, y of min on our hypothetical map
        double mapx, mapy;
        calcxy (&mapx, &mapy, map_iter->max_lat, map_iter->max_lon,
                (double) map_scale/PIXELFACT, map_avg_lat, map_avg_lon);

        double endx, endy;
        calcxy(&endx, &endy, map_iter->min_lat, map_iter->min_lon,
               (double) map_scale/PIXELFACT, map_avg_lat, map_avg_lon);

        double tlx, tly, brx, bry;

        if (mapx < endx) {
            tlx = mapx;
            brx = endx;
        } else {
            tlx = endx;
            brx = mapx;
        }

        if (mapy < endy) {
            tly = mapy;
            bry = endy;
        } else {
            tly = endy;
            bry = mapy;
        }

        if (!(((tlx > 0 && tlx < map_width) &&
               (tly > 0 && tly < map_width)) &&
              ((brx > 0 && brx < map_height) &&
               (bry > 0 && bry < map_height)))) {
            continue;
        } 
        drawn_net_map[map_iter->bssid.c_str()] = map_iter;

        char prim[1024];

        if (in_fill) {
            PixelPacket netclr;

            ExceptionInfo excep;
            GetExceptionInfo(&excep);
            QueryColorDatabase(map_iter->color_index.c_str(), &netclr, &excep);
            if (excep.severity != UndefinedException) {
                CatchException(&excep);
                break;
            }

            in_di->fill = netclr;
            snprintf(prim, 1024, "fill-opacity %d%% rectangle %d,%d %d,%d",
                 in_fill, (int) mapx, (int) mapy, (int) endx, (int) endy);
        } else {
        snprintf(prim, 1024, "stroke black fill black fill-opacity %d%% "
                 "rectangle %d,%d %d,%d",
                 in_fill, (int) mapx, (int) mapy, (int) endx, (int) endy);
	}

        in_di->primitive = prim;
        DrawImage(in_img, in_di);
        GetImageException(in_img, &im_exception);
        if (im_exception.severity != UndefinedException) {
            CatchException(&im_exception);
            break;
        }

        /*
        //d = sqrt[(x1-x2)^2 + (y1-y2)^2]
        printf("  Px RLen : %d\n", (int) sqrt(pow((int) mapx - endx, 2) + pow((int) mapy - endy, 2)));
        */

    }
}

// Thread function to compute a line of interpolated data

typedef struct powerline_arg {
//    unsigned int y;
//    unsigned int y_max;
    unsigned int in_res;
    unsigned int threadno;
};

void *PowerLine(void *arg) {
    powerline_arg *parg = (powerline_arg *) arg;
    time_t startline;

//    unsigned int y_offset = parg->y;
//    unsigned int y_max = parg->y_max;
    unsigned int in_res = parg->in_res;
    unsigned int y = 0;

    while (y < map_height) {
#ifdef HAVE_PTHREAD
        pthread_mutex_lock(&power_pos_lock);
#endif
        y = power_pos * in_res;
        power_pos++;
#ifdef HAVE_PTHREAD
        pthread_mutex_unlock(&power_pos_lock);
#endif
        if (y >= map_height)
            break;

        //    for (unsigned int y = y_offset; y < map_height; y+= (in_res * numthreads)) 
        startline = time(0);

#ifdef HAVE_PTHREAD
        pthread_mutex_lock(&print_lock);
        fprintf(stderr, "Thread %d: crunching interpolation image line %d\n", parg->threadno, y);
        pthread_mutex_unlock(&print_lock);
#else
        fprintf(stderr, "Crunching interpolation image line %d\n", y);
#endif

        for (unsigned int x = 0; x < map_width; x+= in_res) {
            unsigned int powr = InverseWeight(x, y, 0,
                                              (double) map_scale/PIXELFACT);
            if (powr > 255)
                powr = 255;
#ifdef HAVE_PTHREAD
            pthread_mutex_lock(&power_lock);
#endif
            power_map[(map_width * y) + x] = powr;
#ifdef HAVE_PTHREAD
            pthread_mutex_unlock(&power_lock);
#endif
        }

        if (verbose) {
#ifdef HAVE_PTHREAD
            pthread_mutex_lock(&print_lock);
#endif
            int elapsed = time(0) - startline;
            int complet = elapsed * ((map_height - y) / in_res);

            fprintf(stderr, "Completed in %d seconds.  (Estimated: %dh %dm %ds to completion)\n",
                    elapsed, (complet/60)/60, (complet/60) % 60, complet % 60);
#ifdef HAVE_PTHREAD
            pthread_mutex_unlock(&print_lock);
#endif
        }

    }

#ifdef HAVE_PTHREAD
    pthread_exit((void *) 0);
    return NULL;
#else
    return NULL;
#endif
}

void DrawNetPower(vector<gps_network *> in_nets, Image *in_img, 
                  DrawInfo *in_di) {
//    PixelPacket point_clr;
#ifdef HAVE_PTHREAD
    pthread_attr_t attr;
#endif

    power_map = new int [map_width * map_height];
    memset(power_map, 0, sizeof(int) * (map_width * map_height));
    power_input_map = new int [map_width * map_height];
    memset(power_input_map, -1, sizeof(int) * (map_width * map_height));

    for (unsigned int x = 0; x < in_nets.size(); x++) {
        gps_network *map_iter = in_nets[x];
        int visible = 0;

        for (unsigned int y = 0; y < map_iter->center_points.size(); y++) {
            double dcurx, dcury;

            calcxy(&dcurx, &dcury, map_iter->center_points[y]->lat, 
                    map_iter->center_points[y]->lon,
                   (double) map_scale/PIXELFACT, map_avg_lat, map_avg_lon);

            unsigned int curx = (unsigned int) dcurx;
            unsigned int cury = (unsigned int) dcury;

            if (curx >= map_width || cury >= map_height || curx < 0 || cury < 0)
                continue;

            // Do SNR for power if we look like dB
            int snr = map_iter->center_points[y]->signal;
            if (snr < 0 && map_iter->center_points[y]->noise < 0) {
                snr = map_iter->center_points[y]->signal - 
                    map_iter->center_points[y]->noise;
            } 

            if (snr == 0 || abs(power_input_map[(map_width * cury) + curx]) < abs(snr)) {
                power_input_map[(map_width * cury) + curx] = snr;
            }

            visible = 1;
        }

        if (visible)
            drawn_net_map[map_iter->bssid.c_str()] = map_iter;
    }

    fprintf(stderr, "Interpolating power into graph points.\n");

    powerline_arg *pargs;
#ifdef HAVE_PTHREAD
    // Slice the map into pieces and assign it to the threads, averaging high - if it's
    // not evenly divisible the last thread may get less work to do than the others.
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    pargs = new powerline_arg[numthreads];
    for (int t = 0; t < numthreads; t++) {
        pargs[t].in_res = power_resolution;
        pargs[t].threadno = t;

        pthread_create(&mapthread[t], &attr, PowerLine, (void *) &pargs[t]);
    }

    pthread_attr_destroy(&attr);

    // Now wait for the threads to complete and come back
    intptr_t thread_status;
    for (int t = 0; t < numthreads; t++) {
        void *tmp;
        pthread_join(mapthread[t], &tmp);
	thread_status = reinterpret_cast<intptr_t>(tmp);
    }
#else
    // Run one instance of our "thread".  thread number 0, it should just crunch it all
    pargs = new powerline_arg;
    pargs->in_res = power_resolution;
    pargs->threadno = 0;

    PowerLine((void *) pargs);
#endif

    // calc min and max signals for color scaling
    for (unsigned int v = 0; v < map_height; v++) {
        for (unsigned int h = 0; h < map_width; h++) {
            int pw = power_map[(map_width * v) + h];

            if (pw > 0) {
                if (signal_highest < pw)
                    signal_highest = pw;
                if (signal_lowest > pw)
                    signal_lowest = pw;
            }
        }
    }

    fprintf(stderr, "Preparing colormap.\n");
    // Doing this here saves us another ~ 1mio operations
    PixelPacket *colormap = new PixelPacket[power_steps];
    ExceptionInfo ex;
    GetExceptionInfo(&ex);
    for ( int i = 0; i < power_steps; i++) {
        QueryColorDatabase(power_colors[i], &colormap[i], &ex);
        if ( ex.severity != UndefinedException ) {
            CatchException(&ex);
            break;
        }
    }

    ExceptionInfo excep;
    GetExceptionInfo(&excep);

    // Since the opacity value is always the same, we can 
    // generate the template before the loop, which saves
    // us another 1.5mio ops

    char * point_template = new char[1024];
    char * rect_template = new char[1024];

    snprintf(point_template , 1024, "fill-opacity %d%%%% stroke-opacity %d%%%% stroke-width 0 point %%d,%%d", power_opacity, power_opacity);
    snprintf(rect_template  , 1024, "fill-opacity %d%%%% stroke-opacity %d%%%% stroke-width 0 rectangle %%d,%%d %%d,%%d", power_opacity, power_opacity);
    
    fprintf(stderr, "Drawing interpolated power levels to map.\n");

    int power_stepsize = (signal_highest - signal_lowest) / power_steps;
    
    for (unsigned int y = 0; y < map_height; y += power_resolution) {
        for (unsigned int x = 0; x < map_width; x += power_resolution) {
            int powr = power_map[(map_width * y) + x];

            if (powr > 0) {

                int power_index = powr / power_stepsize;

                if (power_index >= power_steps)
                    power_index = power_steps - 1;

                in_di->stroke = colormap[power_index];
                in_di->fill = colormap[power_index];

                char prim[1024];

                int b, r;

                if (power_resolution == 1) {
                    snprintf(prim, 1024, point_template, x, y);
                } else {
                    r = x + power_resolution - 1;
                    b = y + power_resolution - 1;
                    snprintf(prim, 1024, rect_template, x, y, r, b);
                }

                in_di->primitive = prim;
                DrawImage(in_img, in_di);
                GetImageException(in_img, &im_exception);
                if (im_exception.severity != UndefinedException) {
                    CatchException(&im_exception);
                    break;
                }
            }
        }

    }

    delete[] power_map;
    delete[] power_input_map;
    delete[] colormap;
    delete point_template;
    delete rect_template;
}

void DrawNetCenterDot(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di) {
    for (unsigned int x = 0; x < in_nets.size(); x++) {
        gps_network *map_iter = in_nets[x];

        // Skip networks w/ no determined coordinates
        if (map_iter->max_lat == 90)
            continue;

        if (map_iter->diagonal_distance > horiz_throttle)
            continue;


        // Figure x, y of min on our hypothetical map
        double mapx, mapy;

        calcxy (&mapx, &mapy, map_iter->avg_lat, map_iter->avg_lon,
                (double) map_scale/PIXELFACT, map_avg_lat, map_avg_lon);

        if (!((mapx > 0 && mapx < map_width) || (mapy > 0 && mapy < map_height)))
            continue;

        drawn_net_map[map_iter->bssid.c_str()] = map_iter;

        double endx, endy;
        endx = mapx + center_resolution;
        endy = mapy + center_resolution;

        // printf("  Endpt   : %dx%d\n", (int) endx, (int) endy);

        PixelPacket netclr;

        ExceptionInfo excep;
        GetExceptionInfo(&excep);
        QueryColorDatabase(map_iter->color_index.c_str(), &netclr, &excep);
        if (excep.severity != UndefinedException) {
            CatchException(&excep);
            break;
        }

        in_di->fill = netclr;
        in_di->stroke = netclr;

        char prim[1024];

        snprintf(prim, 1024, "fill-opacity 100%% stroke-opacity 100%% circle %d,%d %d,%d",
                 (int) mapx, (int) mapy, (int) endx, (int) endy);
        in_di->primitive = prim;
        DrawImage(in_img, in_di);
        GetImageException(in_img, &im_exception);
        if (im_exception.severity != UndefinedException) {
            CatchException(&im_exception);
            break;
        }

    }
}

void DrawNetCenterText(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di) {
    for (unsigned int x = 0; x < in_nets.size(); x++) {
        gps_network *map_iter = in_nets[x];

        map_iter->label.x = 0;
        map_iter->label.y = 0;
        map_iter->label.w = 0;
        map_iter->label.h = 0;
    }
    for (unsigned int x = 0; x < in_nets.size(); x++) {
        gps_network *map_iter = in_nets[x];

        // Skip networks w/ no determined coordinates
        if (map_iter->max_lat == 90)
            continue;

        if (map_iter->diagonal_distance > horiz_throttle)
            continue;

        // Figure x, y of min on our hypothetical map
        double mapx, mapy;

        calcxy (&mapx, &mapy, map_iter->avg_lat, map_iter->avg_lon,
                (double) map_scale/PIXELFACT, map_avg_lat, map_avg_lon);

        PixelPacket netclr;

        char prim[1024];

        ExceptionInfo excep;
        GetExceptionInfo(&excep);
        QueryColorDatabase("#000000", &netclr, &excep);
        if (excep.severity != UndefinedException) {
            CatchException(&excep);
            break;
        }

        in_di->fill = netclr;
        in_di->stroke = netclr;

        char text[1024];
        char text2[1024];
        text[0] = '\0';
        text2[0] = '\0';

        // Do we not have a draw condition at all, so we stop doing this
        int draw = 0;
        // Do we just not have a draw condition for this network
        int thisdraw = 0;

        for (unsigned int nl = 0; nl < network_labels.size(); nl++) {
            // Do something more efficient some day, but this only happens
            // a few times and this is the easy way of doing it.
            strncpy(text2, text, 1024);
            switch (network_labels[nl]) {
                case NETLABEL_BSSID:
                    thisdraw = 1;
                    snprintf(text2, 1024, "%s%s ", text, map_iter->bssid.c_str());
                    break;
                case NETLABEL_SSID:
                    if (map_iter->wnet != NULL) {
                        thisdraw = 1;
                        snprintf(text2, 1024, "%s'%s' ", text, map_iter->wnet->ssid.c_str());
                    }
                    break;
                case NETLABEL_INFO:
                    if (map_iter->wnet != NULL && map_iter->wnet->beacon_info.length() > 0) {
                        thisdraw = 1;
                        snprintf(text2, 1024, "%s'%s' ", text, map_iter->wnet->beacon_info.c_str());
                    }
                    break;
                case NETLABEL_MANUF:
                    if (map_iter->wnet != NULL) {
                        thisdraw = 1;
                        map_iter->wnet->manuf_ref = MatchBestManuf(&ap_manuf_map, 
                                                                   map_iter->wnet->bssid,
                                                                   map_iter->wnet->ssid, 
                                                                   map_iter->wnet->channel,
                                                                   map_iter->wnet->crypt_set, 
                                                                   map_iter->wnet->cloaked,
                                                                   &map_iter->wnet->manuf_score);
                        if (map_iter->wnet->manuf_ref) {
                            snprintf(text2, 1024, "%s%s ", text, 
                                     map_iter->wnet->manuf_ref->name.c_str());
                        }
                    }
                    break;
                case NETLABEL_LOCATION:
                    thisdraw = 1;
                    snprintf(text2, 1024, "%s%f,%f ", text, map_iter->avg_lat, map_iter->avg_lon);
                    break;
                default:
                    break;
            }

            draw = 1;
            strncpy(text, text2, 1024);
        }

        if (thisdraw == 0)
            continue;

        if (draw == 0)
            break;

        // Catch this just in case since
        if (strlen(text) == 0)
            continue;

        in_di->text = text;
        TypeMetric metrics;
        if (!GetTypeMetrics(in_img, in_di, &metrics)) {
            GetImageException(in_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                break;
            }
            continue;
        }

        // Find the offset we're using
        int xoff, yoff;
        switch (label_orientation) {
        case 0:
            xoff = -4 + (int) metrics.height / 3;
            yoff = -4 - (int) metrics.width;
            break;
        case 1:
            xoff = -4 + (int) metrics.height / 3;
            yoff = 0 - (int) metrics.width / 2;
            break;
        case 2:
            xoff = -4 + (int) metrics.height / 3;
            yoff = 4;
            break;
        case 3:
            xoff = 0 + (int) metrics.height / 3;
            yoff = -4 - (int) metrics.width;
            break;
        case 4:
            xoff = 0 + (int) metrics.height / 3;
            yoff = 0 - (int) metrics.width / 2;
            break;
        case 5:
            xoff = 0 + (int) metrics.height / 3;
            yoff = 4;
            break;
        case 6:
            xoff = 4 - (int) metrics.height / 3;
            yoff = -4 - (int) metrics.width / 2;
            break;
        case 7:
            xoff = 4 - (int) metrics.height / 3;
            yoff = 0 - (int) metrics.width / 2;
            break;
        case 8:
            xoff = 4 - (int) metrics.height / 3;
            yoff = 4;
            break;
        default:
            xoff = 0 + (int) metrics.height / 3;
            yoff = 0 - (int) metrics.width / 2;
            break;
        }

        map_iter->label.x = (int) mapx + yoff;
        map_iter->label.y = (int) mapy + xoff;
        map_iter->label.h = (int) metrics.height;
        map_iter->label.w = (int) metrics.width;

        while (1) {
            unsigned int y;
            for (y = 0; y < x; y++) {
                gps_network *map_iter1 = in_nets[y];
                if ((map_iter1->label.x + map_iter1->label.w > map_iter->label.x)
                 && (map_iter1->label.x < map_iter->label.x + map_iter->label.w)
                 && (map_iter1->label.y + map_iter1->label.h > map_iter->label.y)
                 && (map_iter1->label.y < map_iter->label.y + map_iter->label.h)) {
                    map_iter->label.y = map_iter1->label.y + map_iter1->label.h;
                    break;
                }
            }
            if (x == y) break;
        }

        snprintf(prim, 1024, "fill-opacity 100%% stroke-opacity 0%% text %d,%d \"%s\"",
                 map_iter->label.x, map_iter->label.y, text);

        in_di->primitive = prim;
        DrawImage(in_img, in_di);
        GetImageException(in_img, &im_exception);
        if (im_exception.severity != UndefinedException) {
            CatchException(&im_exception);
            break;
        }
    }
}

typedef struct {
    string strxy;
    int mapx, mapy, endx, endy;
} dim_rec;

void DrawNetScatterPlot(vector<gps_network *> in_nets, Image *in_img, DrawInfo *in_di) { /*FOLD00*/
    int power_level=0;
    int power_level_total=0;
    int coord_count=0;
    int power_index=0;
    float threshold=0;
    int max_power_level=0;

    for (unsigned int x = 0; x < in_nets.size(); x++) {
        gps_network *map_iter = in_nets[x];

        if (map_iter->diagonal_distance > horiz_throttle)
            continue;

        // hehe, cheating with a hash
        map<string, dim_rec> dim;
        map<string, int> dim_signal_total; // For power plotting
        map<string, int> dim_count; // For power plotting
        for (unsigned int y = 0; y < map_iter->points.size(); y++) {
            gps_point *pt = map_iter->points[y];

            double mapx, mapy;
            calcxy (&mapx, &mapy, pt->lat, pt->lon, (double) map_scale/PIXELFACT,
                    map_avg_lat, map_avg_lon);

            double endx, endy;
            endx = mapx + scatter_resolution;
            endy = mapy + scatter_resolution;

            if ((mapx < 0 && mapy < 0) || 
                (mapx > map_width && mapy > map_height))
                continue;

            drawn_net_map[map_iter->bssid.c_str()] = map_iter;

            char mm1[64];
            snprintf(mm1, 64, "%d,%d", (int) mapx, (int) mapy);
            char mm2[64];
            snprintf(mm2, 64, "%d,%d", (int) endx, (int) endy);
            string a = mm1;
            string b = mm2;

            dim_rec dr;
            dr.strxy = b;
            dr.mapx = (int) mapx;
            dr.mapy = (int) mapy;
            dr.endx = (int) endx;
            dr.endy = (int) endy;
            
            dim[a] = dr;
            if (dim_signal_total.find(a) == dim_signal_total.end()) {
                dim_signal_total[a] = (int) pt->signal;
                dim_count[a] = 1;
            } else {
                dim_signal_total[a] = dim_signal_total[a] + (int) pt->signal; //ATR associative array for commulative signal values seen at this coordinate
                dim_count[a]++; //ATR associative array for number of entries seen at this coordinate
            }

            // ATR Find highest power reading for dynamic scaling
            if ((int) pt->signal > max_power_level) {
                max_power_level = (int) pt->signal;
            }
        }

        if ( scatter_power == 0) {
            // If regular network based coloring, go ahead and set network color
            PixelPacket netclr;

            ExceptionInfo excep;
            GetExceptionInfo(&excep);
            QueryColorDatabase(map_iter->color_index.c_str(), &netclr, &excep);
            if (excep.severity != UndefinedException) {
                CatchException(&excep);
                break;
            }

            in_di->fill = netclr;
            in_di->stroke = netclr;
        } else {
            // ATR Determine range value for assigning colors
            if (power_zoom > 0) {
                max_power_level = power_zoom;
            }
            if(max_power_level < power_steps) {  // ATR don't break down further than number of colors
                threshold = 1;
            } else {
                threshold = (float) max_power_level/(float) (power_steps);

            }
            // printf("Power Zoom=%d : Power Steps=%d : Range for Color Index=%.2f\n", max_power_level, power_steps, threshold);
        }

        for (map<string, dim_rec>::const_iterator y = dim.begin(); 
             y != dim.end(); ++y) {
            if (scatter_power == 1) { 
                // ATR If power based coloring, determine and set color 
                // for each scatter point
                // ATR calc average power from multiple values
                power_level_total = dim_signal_total[y->first];
                coord_count = dim_count[y->first];
                if (power_level_total == 0) { 
                    // ATR sig is really something above zero or we 
                    // wouldn't get a packet ;)
                    power_level_total++;
                }
                power_level = power_level_total/coord_count;
                if (power_level == 0) { 
                    // ATR sig is really something above zero or we wouldn't 
                    // get a packet ;)
                    power_level++;
                }

                // ATR Determine color index
                power_index = (int) (power_level / threshold);
                if (power_index == 0) { 
                    // ATR value of zero means we got a bogus integer 
                    // rounding number
                    power_index++;
                }
                if (power_index > power_steps) { 
                    // ATR if user specifies zoom that's less than 
                    // max_power, then set index to highest color
                    power_index = power_steps;
                }

                PixelPacket netclr;
                ExceptionInfo excep;
                GetExceptionInfo(&excep);
                QueryColorDatabase(power_colors[power_index-1], &netclr, 
                                   &excep); 
                // ATR - Get color based on signal power
                if (excep.severity != UndefinedException) {
                    CatchException(&excep);
                    break;
                }
                in_di->fill = netclr;
                in_di->stroke = netclr;
                // printf("Plot=%s : Commulative Power=%d : Number Readings=%d : Ave Power=%d : Color Index=%d \n", y->first.c_str(), power_level_total, coord_count, power_level, power_index);
            }

            char prim[1024];

            if (feather_scatter == 0 || scatter_resolution < 3) {
                snprintf(prim, 1024, "fill-opacity %d%% stroke-opacity "
                         "%d%% circle %s %s",
                         scatter_opacity, scatter_opacity, y->first.c_str(), 
                         y->second.strxy.c_str());

                in_di->primitive = prim;
                DrawImage(in_img, in_di);
                GetImageException(in_img, &im_exception);
                if (im_exception.severity != UndefinedException) {
                    CatchException(&im_exception);
                    break;
                }
            } else {
                DrawFeatherCircle(scatter_resolution, in_img, 
                                  y->second.mapx, y->second.mapy,
                                  2, scatter_opacity, 1, 3, in_di->fill);
            }

        }

    }

}

// Draw the legend and composite into the main map
//
// Make sure to call this as the LAST DRAWING OPTION or else it won't get
// the count right and various other things will go wrong.
//
// Text alignment SUCKS.  I don't like writing graphics code.
// This might screw up in some font situations, i'll deal with it whenever it
// comes to that.
int DrawLegendComposite(vector<gps_network *> in_nets, Image **in_img, 
                        DrawInfo **in_di) {
   // char pixdata[map_width][map_height + legend_height];
    unsigned int *pixdata;
    char prim[1024];
    ExceptionInfo im_exception;
    GetExceptionInfo(&im_exception);
    PixelPacket textclr;
    int tx_height;
    int cur_colpos = 5, cur_rowpos = map_height + 5;
    time_t curtime = time(0);
    int cur_column = 0;
    PixelPacket sqcol;
    // Width of the text column thats mandatory
    int text_colwidth = 0;
    // max val of each column
    map<int, int> max_col_map;
    int wepped_nets = 0, unwepped_nets = 0, default_nets = 0;

    for (map<mac_addr, gps_network *>::iterator dni = drawn_net_map.begin();
         dni != drawn_net_map.end(); ++dni) {
        gps_network *map_iter = dni->second;

        if (map_iter->wnet == NULL) {
            unwepped_nets++;
            continue;
        }

        if (map_iter->wnet->manuf_score == manuf_max_score) {
            default_nets++;
        } else if (map_iter->wnet->crypt_set) {
			// Handle WPA only and no wep
			if (map_iter->wnet->crypt_set != crypt_wpa)
				wepped_nets++;
        } else {
            unwepped_nets++;
        }
    }

    Image *leg_img = NULL;
    DrawInfo *leg_di = NULL;
    ImageInfo *leg_img_info = NULL;

    leg_img_info = CloneImageInfo((ImageInfo *) NULL);

    pixdata = (unsigned int *) malloc(sizeof(unsigned int) * 
                                      (map_width * (map_height + legend_height)) * 3);

    leg_img = ConstituteImage(map_width, map_height + legend_height, "RGB", CharPixel, 
                              pixdata, &im_exception);

    if (leg_img == (Image *) NULL) {
        fprintf(stderr, "FATAL: ImageMagick error:\n");
        MagickError(im_exception.severity, im_exception.reason,
                    im_exception.description);
        exit(1);
    }

    free(pixdata);

    leg_di = CloneDrawInfo(leg_img_info, NULL);

    snprintf(prim, 1024, "stroke black fill black fill-opacity 100%% "
             "rectangle 0,%d %d,%d", map_height, map_width, legend_height);
    leg_di->primitive = prim;
    DrawImage(leg_img, leg_di);
    GetImageException(leg_img, &im_exception);
    if (im_exception.severity != UndefinedException) {
        CatchException(&im_exception);
        return -1;
    }

    // Set the max channel to 11 if we don't have extended channels
    // this makes the graph nicer
    if (maxseen_channel <= 11)
        channelcolor_max = 11;
    
    char text[1024];

    QueryColorDatabase("#FFFFFF", &textclr, &im_exception);
    if (im_exception.severity != UndefinedException) {
        CatchException(&im_exception);
        return -1;
    }
   
    leg_di->fill = textclr;
    leg_di->stroke = textclr;
    leg_di->font = strdup("courier");
    leg_di->pointsize = 14;
    leg_di->text_antialias = MagickTrue;
    // leg_di->text_antialias = 1;

    // Figure out how many columns we're going to have...
    int ncolumns = 0;

    // Find the width of the everpresent text and then take the remaining area
    // and make it the right number of columns, based off their max width of 
    // contents

    // Test the standard text in col1
    snprintf(text, 1024, "Visible networks: %zd\n", drawn_net_map.size());
    text_colwidth = kismax(text_colwidth, IMStringWidth(text, leg_img, leg_di));

    snprintf(text, 1024, "Map Created     : %.24s", ctime((const time_t *) &curtime));
    text_colwidth = kismax(text_colwidth, IMStringWidth(text, leg_img, leg_di));

    snprintf(text, 1024, "Map Coordinates : %f,%f @ scale %ld",
             map_avg_lat, map_avg_lon, map_scale);
    text_colwidth = kismax(text_colwidth, IMStringWidth(text, leg_img, leg_di));

    // Account for the margain
    text_colwidth += 5;

    // Now compare the sizes of the channel or color alloc
    int squaredim = IMStringHeight("0", leg_img, leg_di);

    if (draw_bounds || draw_range || draw_hull || draw_scatter || draw_center) {
        int curmax_colwidth = 0;
        if (color_coding == COLORCODE_WEP) {
            snprintf(text, 1024, "WEP Encrypted - %d (%2.2f%%)", wepped_nets,
                     ((double) wepped_nets / drawn_net_map.size()) * 100);
            curmax_colwidth = kismax(curmax_colwidth, 
                                     IMStringWidth(text, leg_img, leg_di) + 
                                     5 + squaredim);
            snprintf(text, 1024, "Unencrypted - %d (%2.2f%%)", unwepped_nets,
                     ((double) unwepped_nets / drawn_net_map.size()) * 100);
            curmax_colwidth = kismax(curmax_colwidth, 
                                     IMStringWidth(text, leg_img, leg_di) + 
                                     5 + squaredim);
            snprintf(text, 1024, "Factory Default - %d (%2.2f%%)", default_nets,
                     ((double) default_nets / drawn_net_map.size()) * 100);
            curmax_colwidth = kismax(curmax_colwidth, 
                                     IMStringWidth(text, leg_img, leg_di) + 5 + 
                                     squaredim);
            max_col_map[ncolumns] = curmax_colwidth;
            ncolumns++;
        } else if (color_coding == COLORCODE_CHANNEL) {
            curmax_colwidth = kismax(curmax_colwidth, squaredim * channelcolor_max);
            max_col_map[ncolumns] = curmax_colwidth;
            ncolumns++;
        } 

    }

    int power_step_skip = 1;
    if (draw_power && power_data != 0) {
        if (power_steps > 16)
            power_step_skip = power_steps / 16;

        int curmax_colwidth = squaredim * (power_steps / power_step_skip);
        max_col_map[ncolumns] = curmax_colwidth;
        ncolumns++;

    }

    // Now we know how wide we have to be...

    // Draw the first column of text, always have this
    snprintf(text, 1024, "Map Coordinates : %f,%f @ scale %ld",
             map_avg_lat, map_avg_lon, map_scale);
    tx_height = IMStringHeight(text, leg_img, leg_di);

    snprintf(prim, 1024, "text %d,%d \"%s\"",
             cur_colpos, cur_rowpos + (tx_height / 2), text);
    leg_di->text = text;
    leg_di->primitive = prim;
    DrawImage(leg_img, leg_di);
    GetImageException(leg_img, &im_exception);
    if (im_exception.severity != UndefinedException) {
        CatchException(&im_exception);
        return -1;
    }
    cur_rowpos += tx_height + 2;

    /*
    snprintf(text, 1024, "Total networks  : %d\n", in_nets.size());
    tx_height = IMStringHeight(text, leg_img, leg_di);

    snprintf(prim, 1024, "text %d,%d \"%s\"",
             cur_colpos, cur_rowpos + (tx_height / 2), text);
    leg_di->text = text;
    leg_di->primitive = prim;
    DrawImage(leg_img, leg_di);
    GetImageException(leg_img, &im_exception);
    if (im_exception.severity != UndefinedException) {
        CatchException(&im_exception);
        return -1;
    }
    cur_rowpos += tx_height + 2;
    */ 

    snprintf(text, 1024, "Visible networks: %zd\n", drawn_net_map.size());
    tx_height = IMStringHeight(text, leg_img, leg_di);

    snprintf(prim, 1024, "text %d,%d \"%s\"",
             cur_colpos, cur_rowpos + (tx_height / 2), text);
    leg_di->primitive = prim;
    DrawImage(leg_img, leg_di);
    GetImageException(leg_img, &im_exception);
    if (im_exception.severity != UndefinedException) {
        CatchException(&im_exception);
        return -1;
    }
    cur_rowpos += tx_height + 2;

    snprintf(text, 1024, "Map Created     : %.24s", ctime((const time_t *) &curtime));
    tx_height = IMStringHeight(text, leg_img, leg_di);

    snprintf(prim, 1024, "text %d,%d \"%s\"",
             cur_colpos, cur_rowpos + (tx_height / 2), text);
    leg_di->primitive = prim;
    DrawImage(leg_img, leg_di);
    GetImageException(leg_img, &im_exception);
    if (im_exception.severity != UndefinedException) {
        CatchException(&im_exception);
        return -1;
    }
    cur_rowpos += tx_height + 2;
  
    int avail_width = map_width - text_colwidth;
    
    // Draw the second column
    if ((draw_bounds || draw_range || draw_hull || draw_scatter || draw_center) &&
        (color_coding == COLORCODE_WEP || color_coding == COLORCODE_CHANNEL)) {
        cur_rowpos = map_height + 5;

        cur_colpos = text_colwidth + ((avail_width / ncolumns) * cur_column) +
            (((avail_width / ncolumns) / 2) - (max_col_map[cur_column] / 2));

        if (color_coding == COLORCODE_WEP) {
            // Draw the pretty colored squares
            QueryColorDatabase("#FF0000", &sqcol, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                return -1;
            }
            snprintf(prim, 1024, "fill-opacity 100%% stroke-opacity 100%% "
                     "rectangle %d,%d %d,%d",
                     cur_colpos , cur_rowpos,
                     cur_colpos + squaredim, cur_rowpos + squaredim);
            leg_di->fill = sqcol;
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                fprintf(stderr, "FATAL: ImageMagick error:\n");
                MagickError(im_exception.severity, im_exception.reason,
                            im_exception.description);
                return -1;
            }
            cur_rowpos += squaredim + 2;

            QueryColorDatabase("#00FF00", &sqcol, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                return -1;
            }
            snprintf(prim, 1024, "fill-opacity 100%% stroke-opacity 100%% "
                     "rectangle %d,%d %d,%d",
                     cur_colpos , cur_rowpos,
                     cur_colpos + squaredim, cur_rowpos + squaredim);
            leg_di->fill = sqcol;
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                fprintf(stderr, "FATAL: ImageMagick error:\n");
                MagickError(im_exception.severity, im_exception.reason,
                            im_exception.description);
                return -1;
            }
            cur_rowpos += squaredim + 2;

            QueryColorDatabase("#0000FF", &sqcol, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                return -1;
            }
            snprintf(prim, 1024, "fill-opacity 100%% stroke-opacity 100%% "
                     "rectangle %d,%d %d,%d",
                     cur_colpos , cur_rowpos,
                     cur_colpos + squaredim, cur_rowpos + squaredim);
            leg_di->fill = sqcol;
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                fprintf(stderr, "FATAL: ImageMagick error:\n");
                MagickError(im_exception.severity, im_exception.reason,
                            im_exception.description);
                return -1;
            }

            // Go back and draw the text
            cur_rowpos = map_height + 5;
            cur_colpos += squaredim + 5;
            int tx_offset = (squaredim / 2) + (squaredim / 3);

            leg_di->fill = textclr;
            leg_di->stroke = textclr;

            snprintf(text, 1024, "WEP Encrypted - %d (%2.2f%%)", wepped_nets,
                     ((double) wepped_nets / drawn_net_map.size()) * 100);
            tx_height = IMStringHeight(text, leg_img, leg_di);

            snprintf(prim, 1024, "text %d,%d \"%s\"",
                     cur_colpos, cur_rowpos + tx_offset, text);
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                return -1;
            }
            cur_rowpos += squaredim + 2;

            snprintf(text, 1024, "Unencrypted - %d (%2.2f%%)", unwepped_nets,
                     ((double) unwepped_nets / drawn_net_map.size()) * 100);
            tx_height = IMStringHeight(text, leg_img, leg_di);

            snprintf(prim, 1024, "text %d,%d \"%s\"",
                     cur_colpos, cur_rowpos + tx_offset, text);
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                return -1;
            }
            cur_rowpos += squaredim + 2;

            snprintf(text, 1024, "Factory Default - %d (%2.2f%%)", default_nets,
                     ((double) default_nets / drawn_net_map.size()) * 100);
            tx_height = IMStringHeight(text, leg_img, leg_di);

            snprintf(prim, 1024, "text %d,%d \"%s\"",
                     cur_colpos, cur_rowpos + tx_offset, text);
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                return -1;
            }
            cur_rowpos += squaredim + 2;
            
        } else if (color_coding == COLORCODE_CHANNEL) {
            // Draw the header
            leg_di->fill = textclr;
            leg_di->stroke = textclr;
            snprintf(text, 1024, "Channel Number");
            tx_height = IMStringHeight(text, leg_img, leg_di);
            snprintf(prim, 1024, "text %d,%d \"%s\"",
                     cur_colpos + (((channelcolor_max - 1) * squaredim) / 2) -
                     (IMStringWidth(text, leg_img, leg_di) / 2) + 4,
                     cur_rowpos + (IMStringHeight(text, leg_img, leg_di) / 2) + 3,
                     text);
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                fprintf(stderr, "FATAL: ImageMagick error:\n");
                MagickError(im_exception.severity, im_exception.reason,
                            im_exception.description);
                return -1;
            }
            cur_rowpos += tx_height + 2;

            // Draw each square in the channel graph sized to text
            for (int x = 0; x < channelcolor_max; x++) {
                QueryColorDatabase(channelcolors[x], &sqcol, &im_exception);
                if (im_exception.severity != UndefinedException) {
                    CatchException(&im_exception);
                    break;
                }

                snprintf(prim, 1024, "fill-opacity 100%% stroke-opacity 100%% "
                         "rectangle %d,%d %d,%d", 
                         cur_colpos + (x * squaredim), cur_rowpos,
                         cur_colpos + ((x+1) * squaredim), cur_rowpos + squaredim);
                //leg_di->stroke = sqcol;
                leg_di->fill = sqcol;
                leg_di->primitive = prim;
                DrawImage(leg_img, leg_di);
                GetImageException(leg_img, &im_exception);
                if (im_exception.severity != UndefinedException) {
                    fprintf(stderr, "FATAL: ImageMagick error:\n");
                    MagickError(im_exception.severity, im_exception.reason,
                                im_exception.description);
                    return -1;
                }
            }


            leg_di->fill = textclr;
            leg_di->stroke = textclr;
            snprintf(text, 1024, "1");
            snprintf(prim, 1024, "text %d,%d \"%s\"",
                     cur_colpos + (IMStringWidth(text, leg_img, leg_di) / 2),
                     cur_rowpos + squaredim + (IMStringHeight(text, leg_img, 
                                                              leg_di) / 2) + 3, 
                     text);
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                fprintf(stderr, "FATAL: ImageMagick error:\n");
                MagickError(im_exception.severity, im_exception.reason,
                            im_exception.description);
                return -1;
            }

            leg_di->fill = textclr;
            leg_di->stroke = textclr;
            snprintf(text, 1024, "%d", channelcolor_max);
            snprintf(prim, 1024, "text %d,%d \"%s\"",
                     cur_colpos +  
                     ((channelcolor_max - 1) * squaredim), 
                     cur_rowpos + squaredim + (IMStringHeight(text, leg_img, 
                                                              leg_di) / 2) + 3, 
                     text);
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                fprintf(stderr, "FATAL: ImageMagick error:\n");
                MagickError(im_exception.severity, im_exception.reason,
                            im_exception.description);
                return -1;
            }

        }

        cur_column++;
    }

    if (draw_power && power_data != 0) {
        cur_rowpos = map_height + 5;

        cur_colpos = text_colwidth + ((avail_width / ncolumns) * cur_column) +
            (((avail_width / ncolumns) / 2) - (max_col_map[cur_column] / 2));

        snprintf(text, 1024, "Signal Level");
        tx_height = IMStringHeight(text, leg_img, leg_di);
        
        int powerbarlen = ((power_steps / power_step_skip) * squaredim) + squaredim;
        leg_di->fill = textclr;
        leg_di->stroke = textclr;
        snprintf(prim, 1024, "text %d,%d \"%s\"",
                 cur_colpos + (powerbarlen / 2) - 
                 (IMStringWidth(text, leg_img, leg_di) / 2) + 4,
                 cur_rowpos + (tx_height / 2) + 3,
                 text);
        leg_di->primitive = prim;
        DrawImage(leg_img, leg_di);
        GetImageException(leg_img, &im_exception);
        if (im_exception.severity != UndefinedException) {
            fprintf(stderr, "FATAL: ImageMagick error:\n");
            MagickError(im_exception.severity, im_exception.reason,
                        im_exception.description);
            return -1;
        }
        cur_rowpos += tx_height + 2;

        int actual_pos = 0;
        for (int x = 0; x < power_steps; x += power_step_skip) {
            actual_pos++;

            QueryColorDatabase(power_colors[x], &sqcol, &im_exception);
            if (im_exception.severity != UndefinedException) {
                CatchException(&im_exception);
                break;
            }

            snprintf(prim, 1024, "fill-opacity 100%% stroke-opacity 100%% "
                     "rectangle %d,%d %d,%d", 
                     cur_colpos + (actual_pos * squaredim), cur_rowpos,
                     cur_colpos + ((actual_pos+1) * squaredim), cur_rowpos + squaredim);
            //leg_di->stroke = sqcol;
            leg_di->fill = sqcol;
            leg_di->primitive = prim;
            DrawImage(leg_img, leg_di);
            GetImageException(leg_img, &im_exception);
            if (im_exception.severity != UndefinedException) {
                fprintf(stderr, "FATAL: ImageMagick error:\n");
                MagickError(im_exception.severity, im_exception.reason,
                            im_exception.description);
                return -1;
            }

        }

        // Print the channel numbers and alloc name
        leg_di->fill = textclr;
        leg_di->stroke = textclr;
        snprintf(text, 1024, "<- Weaker");
        snprintf(prim, 1024, "text %d,%d \"%s\"",
                 cur_colpos + (IMStringWidth(text, leg_img, leg_di) / 3) - 3, 
                 cur_rowpos + squaredim + (IMStringHeight(text, 
                                                          leg_img, leg_di) / 2) + 3, 
                 text);
        leg_di->primitive = prim;
        DrawImage(leg_img, leg_di);
        GetImageException(leg_img, &im_exception);
        if (im_exception.severity != UndefinedException) {
            fprintf(stderr, "FATAL: ImageMagick error:\n");
            MagickError(im_exception.severity, im_exception.reason,
                        im_exception.description);
            return -1;
        }

        snprintf(text, 1024, "Stronger ->");
        snprintf(prim, 1024, "text %d,%d \"%s\"",
                 cur_colpos + ((actual_pos + 1) * squaredim) - 
                 IMStringWidth(text, leg_img, leg_di),  
                 cur_rowpos + squaredim + (IMStringHeight(text, 
                                                          leg_img, leg_di) / 2) + 3, 
                 text);
        leg_di->primitive = prim;
        DrawImage(leg_img, leg_di);
        GetImageException(leg_img, &im_exception);
        if (im_exception.severity != UndefinedException) {
            fprintf(stderr, "FATAL: ImageMagick error:\n");
            MagickError(im_exception.severity, im_exception.reason,
                        im_exception.description);
            return -1;
        }

    }

    snprintf(text, 1024, "Map generated by Kismet/GPSMap %s.%s.%s - "
             "http://www.kismetwireless.net", VERSION_MAJOR, 
             VERSION_MINOR, VERSION_TINY);
    QueryColorDatabase("#999999", &textclr, &im_exception);
    if (im_exception.severity != UndefinedException) {
        CatchException(&im_exception);
        return -1;
    }
    leg_di->fill = textclr;
    leg_di->stroke = textclr;
    leg_di->pointsize = 12;

    snprintf(prim, 1024, "text %d,%d \"%s\"",
             (map_width / 2) - (IMStringWidth(text, leg_img, leg_di) / 2),
             map_height + legend_height - (IMStringHeight(text, leg_img, leg_di) / 2),
             text);
    leg_di->primitive = prim;
    DrawImage(leg_img, leg_di);
    GetImageException(leg_img, &im_exception);
    if (im_exception.severity != UndefinedException) {
        fprintf(stderr, "FATAL: ImageMagick error:\n");
        MagickError(im_exception.severity, im_exception.reason,
                    im_exception.description);
        return -1;
    }

    // Now stick them together...  This doesn't take an exception and the return
    // type isn't documented, so lets just hope it does something.  Go IM!
    CompositeImage(leg_img, OverCompositeOp, *in_img, 0, 0);

    (*in_di)->text = strdup("");
    (*in_di)->primitive = strdup("");

    DestroyImage(*in_img);
    DestroyDrawInfo(*in_di);

    *in_img = leg_img;
    *in_di = leg_di;

    return 0;
}

int ShortUsage(char *argv) {
    printf("Usage: %s [OPTION] <GPS Files>\n", argv);
    printf("Try `%s --help' for more information.\n", argv);
    exit(1);
}

int Usage(char* argv, int ec = 1) { 
    printf("Usage: %s [OPTION] <GPS files>\n", argv);
    printf(
    //      12345678901234567890123456789012345678901234567890123456789012345678901234567890
           "  -h, --help                     What do you think you're reading?\n"
           "  -v, --verbose                  Verbose output while running\n"
           "  -g, --config-file <file>       Alternate config file\n"
           "  -o, --output <filename>        Image output file\n"
           "  -f, --filter <MAC list>        Comma-separated list of MACs to filter\n"
           "  -i, --invert-filter            Invert filtering (ONLY draw filtered MACs)\n"
           "  -F, --typefilter <Type list>   Comma-separated list of net types to filter\n"
           "  -I, --invert-typefilter        Invert type filtering\n"
           "  -z, --threads <num>            Number of simultaneous threads used for\n"
           "                                  complex operations [Default: 1]\n"
           "  -N, --pure-avg-center          Use old pure-average network center finding\n"
           "  -S, --map-source <#>           Source to download maps from [Default: -1]\n"
           "                                 -1 Null map (blank background image)\n"
           "                                  0 MapBlast (UNAVAILABLE)\n"
           "                                  1 MapPoint (UNAVAILABLE)\n"
           "                                  2 TerraServer (photo)\n"
           "                                  3 Tiger US Census (vector)\n"
           "                                  4 EarthaMaps (vector, UNAVAILABLE)\n"
           "                                  5 TerraServer (topo)\n"
	   "                                  6 Expedia EU (vector)\n"
	   "                                  7 OpenStreetMap TilesAtHome-Layer\n"
           "  -D, --keep-gif                 Keep the downloaded map\n"
           "  -V, --version                  GPSMap version\n"
           "\nImage options\n"
           "  -c, --coords <lat,lon>         Force map center at lat,lon\n"
           "  -s, --scale <s>                Force map scale at s.  Different sources use\n"
           "                                  different scales.\n"
           "                                  MAPBLAST - 1000 to 40000000\n"
           "                                  TERRASERVER - 10 to 16\n"
           "                                  TIGER - 1000+\n"
           "                                  EARTHAMAPS: 2 to 15\n"
           "  -m, --user-map <map>           Use custom map instead of downloading\n"
           "  -d, --map-size <x,y>           Download map at size x,y\n"
           "  -n, --network-colors <c>       Network drawing colors [Default: 0]\n"
           "                                  0 is random colors\n"
           "                                  1 is color based on WEP status\n"
           "                                  2 is color based on network channel\n"
           "  -G, --no-greyscale             Don't convert map to greyscale\n"
           "      --color-saturation <n>     Desaturate colors to n%%\n"
           "      --map-intensity <[-]n>     Modify map intensity by n%%.\n"
           "                                  Positive values overlay the map on white\n"
           "                                  Negative values overlay the map on black.\n"
           "  -M, --metric                   Fetch metric-titled map\n"
           "  -O, --offset <x,y>             Offset drawn features by x,y pixels\n"
           "\nDraw options\n"
           "  -t, --draw-track               Draw travel track\n"
           "  -Y, --draw-track-width <w>     travel track width [Default: 3] \n"
           "  -b, --draw-bounds              Draw network bounding box\n"
           "  -K, --draw-bounds-opacity <o>  Bounding box opacity [Default: 10]\n"
           "  -r, --draw-range               Draw estimaged range circles\n"
           "  -R, --draw-range-opacity <o>   Range circle opacity [Default: 70]\n"
           "      --feather-range            Draw range circles with staged opacity\n"
           "  -u, --draw-hull                Draw convex hull of data points\n"
           "  -U, --draw-hull-opacity <o>    Convex hull opacity [Default: 70]\n"
           "  -a, --draw-scatter             Draw scatter plot of data points\n"
           "  -A, --draw-scatter-opacity <o> Scatter plot opacity [Default: 100]\n"
           "  -B, --draw-scatter-size <s>    Draw scatter at radius size <s> [Default: 2]\n"
           "      --feather-scatter          Draw scatter dots with staged opacity (SLOW)\n"
           "  -Z, --draw-power-zoom          Power based scatter plot range for scaling colors [Default: 0]\n"
           "                                 0 determines upper limit based on max observed for network\n"
           "                                 1-255 is user defined upper limit\n"
           "  -p, --draw-power               Draw interpolated network power\n"
           "  -P, --draw-power-opacity <o>   Interpolated power opacity [Default: 70]\n"
           "  -Q, --draw-power-res <res>     Interpolated power resolution [Default: 5]\n"
           "  -q, --draw-power-colors <c>    Interpolated power color set [Default: 0]\n"
           "                                  0 is a ramp though RGB colorspace (12 colors)\n"
           "                                  1 is the origional color set (10 colors)\n"
           "                                  2 is weathermap radar style (9 colors)\n"
           "  -e, --draw-center              Draw dot at center of network range\n"
           "  -E, --draw-center-opacity <o>  Center dot opacity [Default: 100]\n"
           "  -H, --draw-center-size <s>     Center dot at radius size <s> [Default: 2]\n"
           "  -l, --draw-labels <list>       Draw network labels, comma-seperated list\n"
           "                                  that will be drawn in the order given.\n"
           "                                  (bssid, ssid, manuf, info, location)\n"
           "  -L, --draw-label-orient <o>    Label orientation [Default: 7]\n"
           "                                  0       1       2\n"
           "                                  3       4       5\n"
           "                                  6       7       8\n"
           "  -k, --draw-legend              Draw map legend\n"
           "  -T, --feature-order <order>    String representing the order map features\n"
           "                                  are drawn [Default: 'ptbrhscl']\n"
           "                                  p: interpolated power\n"
           "                                  t: tracks\n"
           "                                  b: bounds\n"
           "                                  r: range circles\n"
           "                                  h: convex hulls\n"
           "                                  s: scatter plot\n"
           "                                  c: center dot\n"
           "                                  l: labels\n"
           "  --ignore-under-count <x>        Ignore networks unless it has been seen more then <x> times\n"
           "  --ignore-under-distance <x>     Ignore networks unless they are larger then x ft\n"
          );
    exit(ec);
}

char *exec_name;

int main(int argc, char *argv[]) {
    char* exec_name = argv[0];

    char mapname[1024];
    char mapoutname[1024];

    bool metric = false;

    char *ap_manuf_name = NULL, *client_manuf_name = NULL;
    FILE *manuf_data;

    static struct option long_options[] = {   /* options table */
           {"help", no_argument, 0, 'h'},
           {"verbose", no_argument, 0, 'v'},
           {"config-file", required_argument, 0, 'g'},
           {"map-source", required_argument, 0, 'S'},
           {"output", required_argument, 0, 'o'},
           {"filter", required_argument, 0, 'f'},
           {"invert-filter", no_argument, 0, 'i'},
           {"typefilter", required_argument, 0, 'F'},
           {"invert-typefilter", required_argument, 0, 'I'},
           {"threads", required_argument, 0, 'z'},
           {"keep-gif", no_argument, 0, 'D'},
           {"version", no_argument, 0, 'V'},
           {"coords", required_argument, 0, 'c'},
           {"scale", required_argument, 0, 's'},
           {"user-map", required_argument, 0, 'm'},
           {"map-size", required_argument, 0, 'd'},
           {"network-colors", required_argument, 0, 'n'},
           {"no-greyscale", no_argument, 0, 'G'},
           {"metric", no_argument, 0, 'M'},
           {"offset", required_argument, 0, 'O'},
           {"draw-track", no_argument, 0, 't'},
           /*
           {"draw-track-opacity", required_argument, 0, 'T'},
           */
           {"draw-track-width", required_argument, 0, 'Y'},
           {"draw-bounds", no_argument, 0, 'b'},
           {"draw-bounds-opacity", required_argument, 0, 'K'},
           {"draw-range", no_argument, 0, 'r'},
           {"draw-range-opacity", required_argument, 0, 'R'},
           {"draw-hull", no_argument, 0, 'u'},
           {"draw-hull-opacity", required_argument, 0, 'U'},
           {"draw-scatter", no_argument, 0, 'a'},
           {"draw-scatter-opacity", required_argument, 0, 'A'},
           {"draw-scatter-size", required_argument, 0, 'B'},
           {"draw-power-zoom", required_argument, 0, 'Z'}, // ATR - option for scaling with power based scatter plots
           {"draw-power", no_argument, 0, 'p'},
           {"draw-power-opacity", required_argument, 0, 'P'},
           {"draw-power-res", required_argument, 0, 'Q'},
           {"draw-power-colors", required_argument, 0, 'q'},
           {"draw-center", no_argument, 0, 'e'},
           {"draw-center-opacity", required_argument, 0, 'E'},
           {"draw-center-size", required_argument, 0, 'H'},
           {"draw-labels", required_argument, 0, 'l'},
           {"draw-label-orient", required_argument, 0, 'L'},
           {"draw-legend", no_argument, 0, 'k'},
           {"feature-order", required_argument, 0, 'T'},
           {"pure-avg-center", no_argument, 0, 'N'},
           // From here on down we only have long args
           {"feather-range", no_argument, 0, 2},
           {"feather-scatter", no_argument, 0, 3},
           {"color-saturation", required_argument, 0, 4},
           {"map-intensity", required_argument, 0, 5},
           {"ignore-under-count",required_argument, 0, 6},
           {"ignore-under-distance",required_argument, 0, 7},
           { 0, 0, 0, 0 }
    };
    int option_index;

    bool usermap = false, useroutmap = false, filemap = false;

    power_steps = power_steps_Math;
    power_colors = powercolors_Math;

    float user_lat = 0, user_lon = 0;
    bool user_latlon = false;
    long user_scale = 0;

    int usersize = 0;

    long fetch_scale = 0;

    sample_points = 0;

    char *configfile = NULL;

    vector<string> opttok;
    mac_addr fm;
    string toklow;
    wireless_network_type wt;

    mpf_set_default_prec(256);

    int scantmp1, scantmp2;

    while(1) {
        int r = getopt_long(argc, argv,
                            "hvg:S:o:f:iF:Iz:DVc:s:m:d:n:GMO:tY:brR:uU:aA:B:pP:Z:q:Q:eE:H:l:L:kT:NK:",
                            long_options, &option_index);

        if (r < 0) break;

        switch(r) {
        case 'h':
            Usage(exec_name, 0);
            break;
        case 'v':
            verbose = true;
            break;
        case 'g':
            configfile = optarg;
            break;
        case 'o':
            snprintf(mapoutname, 1024, "%s", optarg);
            useroutmap = true;
            break;
        case 'f':
            opttok = StrTokenize(optarg, ",");
            for (unsigned int tv = 0; tv < opttok.size(); tv++) {
                fm = opttok[tv].c_str();
                if (fm.error) {
                    ShortUsage(exec_name);
                }

                filter_map.insert(fm, 1);
            }
            break;
        case 'F':
            opttok = StrTokenize(optarg, ",");
            for (unsigned int tv = 0; tv < opttok.size(); tv++) {
                toklow = StrLower(opttok[tv]);

                if (toklow == "ap" || toklow == "accesspoint")
                    wt = network_ap;
                else if (toklow == "adhoc" || toklow == "ad-hoc")
                    wt = network_adhoc;
                else if (toklow == "probe")
                    wt = network_probe;
                else if (toklow == "turbocell" || toklow == "turbo-cell")
                    wt = network_turbocell;
                else if (toklow == "data")
                    wt = network_data;
                else {
                    fprintf(stderr, "Invalid network type in filter, '%s'\n",
                            opttok[tv].c_str());
                    ShortUsage(exec_name);
                }

                type_filter_map[wt] = 1;
            }
            break;
        case 'S':
            if (sscanf(optarg, "%d", &mapsource) != 1 || mapsource < MAPSOURCE_MIN || mapsource > MAPSOURCE_MAX) {
                fprintf(stderr, "Invalid map source.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'i':
            invert_filter = 1;
            break;
        case 'I':
            invert_type_filter = 1;
             break;
        case 'z':
#ifdef HAVE_PTHREAD
            if (sscanf(optarg, "%d", &numthreads) != 1 || numthreads < 1) {
                fprintf(stderr, "Invalid number of threads.\n");
                ShortUsage(exec_name);
            }
#else
            fprintf(stderr, "PThread support was not compiled.\n");
            ShortUsage(exec_name);
#endif
            break;
        case 'D':
            keep_gif = true;
            break;
        case 'N':
            pure_center_average = 1;
            fprintf(stderr, "Using old-style pure averaging to find network "
                    "center instead of new smarter centering code.");
            break;
        case 'V':
            printf("GPSMap v%s.%s.%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_TINY);
            exit(0);
            break;
        case 'c':
            if (sscanf(optarg, "%f,%f", &user_lat, &user_lon) != 2) {
                fprintf(stderr, "Invalid custom map coordinates.\n");
                ShortUsage(exec_name);
            }
            user_latlon = true;
            break;
        case 's':
            if (sscanf(optarg, "%ld", &user_scale) != 1) {
                fprintf(stderr, "Invalid custom map scale.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'm':
            snprintf(mapname, 1024, "%s", optarg);
            usermap = true;
            break;
       	case 'd':
            if (sscanf(optarg, "%d,%d", &scantmp1, &scantmp2) != 2 || scantmp1 < 0 || scantmp2 < 0) {
                fprintf(stderr, "Invalid custom map size.\n");
                ShortUsage(exec_name);
            }
            map_width = scantmp1;
            map_height = scantmp2;
            usersize = 1;
            break;
        case 'n':
            if (sscanf(optarg, "%d", &color_coding) !=1 || color_coding < 0 || color_coding > 2) {
                fprintf(stderr, "Invalid network color set\n");
                ShortUsage(exec_name);
            }
            break;
        case 'G':
            convert_greyscale = false;
            break;
        case 'M':
            metric = true;
            break;
        case 'O':
            if (sscanf(optarg, "%d,%d", &draw_x_offset, &draw_y_offset) != 2) {
                fprintf(stderr, "Invalid drawing offset.\n");
                ShortUsage(exec_name);
            }
            break;
        case 't':
            draw_track = true;
            break;
            /*
        case 'T':
            if (sscanf(optarg, "%d", &track_opacity) != 1 || track_opacity < 0 || track_opacity > 100) {
                fprintf(stderr, "Invalid track opacity.\n");
                Usage(exec_name);
            }
            break;
            */            
        case 'Y':             /* Ge0 was here - this could very well break crap */
            if (sscanf(optarg, "%d", &track_width) != 1 || track_width <= 0) {
                fprintf(stderr, "Invalid track width.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'b':
            draw_bounds = true;
            break;
        case 'K':
            if (sscanf(optarg, "%d", &bounds_opacity) != 1 || bounds_opacity < 0 || bounds_opacity > 100) {
                fprintf(stderr, "Invalid bounds opacity.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'r':
            draw_range = true;
            break;
        case 'R':
            if (sscanf(optarg, "%d", &range_opacity) != 1 || range_opacity < 0 || range_opacity > 100) {
                fprintf(stderr, "Invalid range opacity.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'u':
            draw_hull = true;
            break;
        case 'U':
            if (sscanf(optarg, "%d", &hull_opacity) != 1 || hull_opacity < 0 || hull_opacity > 100) {
                fprintf(stderr, "Invalid convex hull opacity.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'a':
            draw_scatter = true;
            break;
        case 'A':
            if (sscanf(optarg, "%d", &scatter_opacity) != 1 || scatter_opacity < 0 || scatter_opacity > 100) {
                fprintf(stderr, "Invalid scatter plot opacity.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'B':
            if (sscanf(optarg, "%d", &scatter_resolution) != 1 || scatter_resolution < 1) {
                fprintf(stderr, "Invalid scatter plot size.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'p':
            draw_power = true;
            break;
        case 'P':
            if (sscanf(optarg, "%d", &power_opacity) != 1 || power_opacity < 0 || power_opacity > 100) {
                fprintf(stderr, "Invalid interpolated power opacity.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'Q':
            if (sscanf(optarg, "%d", &power_resolution) != 1 || power_resolution < 1) {
                fprintf(stderr, "Invalid interpolated power resolution.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'Z':
            if (sscanf(optarg, "%d", &power_zoom) != 1 || power_zoom > 255 || power_zoom < 0) {
                fprintf(stderr, "Invalid scatter power zoom.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'q':
            {
                int icolor;
                if (sscanf(optarg, "%d", &icolor) !=1 || icolor < 0 || icolor > 3) {
                    fprintf(stderr, "Invalid interpolated power color set\n");
                    ShortUsage(exec_name);
                }

                // ATR - set vars for scatter plot
                scatter_power = 1;

                powercolor_index = icolor;

                if (icolor == 0) {
                    power_steps = power_steps_Orig;
                    power_colors = powercolors_Orig;
                } else if (icolor == 2) {
                    power_steps = power_steps_Radar;
                    power_colors = powercolors_Radar;
                } else if (icolor == 3) {
                    power_steps = power_steps_Blue;
                    power_colors = powercolors_Blue;
                }
            }
            break;
        case 'e':
            draw_center = true;
            break;
        case 'E':
            if (sscanf(optarg, "%d", &center_opacity) != 1 || center_opacity < 0 || center_opacity > 100) {
                fprintf(stderr, "Invalid center dot opacity.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'H':
            if (sscanf(optarg, "%d", &center_resolution) != 1 || center_resolution < 1) {
                fprintf(stderr, "Invalid center dot size.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'l':
            opttok = StrTokenize(optarg, ",");
            for (unsigned int t = 0; t < opttok.size(); t++) {
                string tok = StrLower(opttok[t]);
                if (tok == "ssid" || tok == "name")
                    network_labels.push_back(NETLABEL_SSID);
                else if (tok == "bssid")
                    network_labels.push_back(NETLABEL_BSSID);
                else if (tok == "info")
                    network_labels.push_back(NETLABEL_INFO);
                else if (tok == "manuf")
                    network_labels.push_back(NETLABEL_MANUF);
                else if (tok == "location")
                    network_labels.push_back(NETLABEL_LOCATION);
                else {
                    fprintf(stderr, "Invalid label '%s'\n", tok.c_str());
                    exit(1);
                }
            }
            draw_label = 1;
            break;
        case 'L':
            if (sscanf(optarg, "%d", &label_orientation) != 1 || label_orientation < 0 ||
                label_orientation > 8) {
                fprintf(stderr, "Invalid label orientation.\n");
                ShortUsage(exec_name);
            }
            break;
        case 'k':
            draw_legend = true;
            break;
        case 'T':
            draw_feature_order = optarg;
            break;
        case 2:
            feather_range = 1;
            draw_range = 1;
            break;
        case 3:
            feather_scatter = 1;
            break;
        case 4:
            if (sscanf(optarg, "%d", &color_saturation) != 1 || 
                color_saturation < 0 || color_saturation > 100) {
                fprintf(stderr, "Invalid color saturation.\n");
                ShortUsage(exec_name);
            }
            convert_greyscale = 0;
            break;
        case 5:
            if (sscanf(optarg, "%d", &map_intensity) != 1 || 
                map_intensity < -100 || map_intensity > 100) {
                fprintf(stderr, "Invalid map intensity.\n");
                ShortUsage(exec_name);
            }
            break;
        case 6:
            if (sscanf(optarg, "%d", &ignore_under_count) != 1 || ignore_under_count < 0) {
                fprintf(stderr, "You must specify a positive number.\n");
                ShortUsage(exec_name);
            }
            break;
        case 7:
            if (sscanf(optarg, "%d", &ignore_under_distance) != 1 || ignore_under_distance < 0) {
                fprintf(stderr, "You must specify a positive number.\n");
                ShortUsage(exec_name);
            }
            break;
        default:
            ShortUsage(exec_name);
            break;
        }
    }

    // sanity checks
    if (draw_power == 0 && draw_track == 0 && draw_bounds == 0 && draw_range == 0 &&
        draw_hull == 0 && draw_scatter == 0 && draw_center == 0 && draw_label == 0) {
        fprintf(stderr, "FATAL:  No drawing methods requested.\n");
        ShortUsage(exec_name);
    }

    /*
    if ((map_width > 1280 || map_height > 1024) && 
        mapsource == MAPSOURCE_MAPBLAST) {
        fprintf(stderr, "WARNING:  Maximum Mapblast image size is 1024x1280.  "
                "Adjusting.\n");
        map_width = 1024;
        map_height = 1280;
    }
    */

    if (feather_scatter == 1 && scatter_resolution < 3) {
        fprintf(stderr, "WARNING: Scatter resolution must be at least 3 "
                "for scatter feathering.  Scatter feathering will be "
                "disabled.\n");
    }

    // Fail on nullsource + usermap
    if (mapsource == MAPSOURCE_NULL && usermap) {
        fprintf(stderr, "FATAL: Cannot provide a user map to the nullmap source.\n");
        exit(1);
    }
    
    // no dump files
    if (optind == argc) {
        fprintf(stderr, "FATAL:  Must provide at least one gps file.\n");
        ShortUsage(exec_name);
    }

    ConfigFile conf;

    // If we haven't gotten a command line config option...
    if (configfile == NULL) {
        configfile = (char *) malloc(1024*sizeof(char));
        snprintf(configfile, 1024, "%s/%s", SYSCONF_LOC, config_base);
    }

    // Parse the config and load all the values from it and/or our command
    // line options.  This is a little soupy but it does the trick.
    if (conf.ParseConfig(configfile) < 0) {
        fprintf(stderr, "WARNING:  Couldn't open config file '%s'.  Will continue anyway, but MAC filtering and manufacturer detection will be disabled\n",
                configfile);
        configfile = NULL;
    }

    if (configfile != NULL) {
        if (conf.FetchOpt("ap_manuf") != "") {
            ap_manuf_name = strdup(conf.FetchOpt("ap_manuf").c_str());
        } else {
            fprintf(stderr, "WARNING:  No ap_manuf file specified, AP manufacturers and defaults will not be detected.\n");
        }

        if (conf.FetchOpt("client_manuf") != "") {
            client_manuf_name = strdup(conf.FetchOpt("client_manuf").c_str());
        } else {
            fprintf(stderr, "WARNING:  No client_manuf file specified.  Client manufacturers will not be detected.\n");
        }

    }

    // Catch a null-draw condition
    if (invert_filter == 1 && filter_map.size() == 0) {
        fprintf(stderr, "FATAL:  Inverse filtering requested but no MAC's given to draw.\n");
        exit(1);
    }

    // Mangle user scales for other sources into our internal map-blasty scales.
    // Some day this needs to get rewritten to not be using a source that doesn't
    // work anymore as the internal reference point.
    
    if (((mapsource == MAPSOURCE_TERRA) || 
         (mapsource == MAPSOURCE_TERRATOPO)) && user_scale != 0) {
        // It's way too much of a kludge to muck with munging the scale around
        if ((user_scale < 10) || (user_scale > 16)) {
            fprintf(stderr, "FATAL: You must provide a scale with the -s "
                    "option that is from 10 to 16\n");
            exit(0);
        }
        fetch_scale = user_scale;
        map_scale = user_scale = terrascales[(user_scale - 10)];
    }

    // Require the user to specify a scale between 2 and 15, then set
    // {map,user}_scale to the cooresponding element in earthamapscales[].
    if (mapsource == MAPSOURCE_EARTHAMAPS && user_scale != 0) {
        if ((user_scale < 2) || (user_scale > 15)) {
            fprintf(stderr, "FATAL: You must provide a scale with the -s "
                    "option that is from 2 to 15\n");
            exit(0);
        }
        fetch_scale = user_scale;
        map_scale   = user_scale = earthamapscales[user_scale];
    }

    if (ap_manuf_name != NULL) {
        char pathname[1024];

        if (strchr(ap_manuf_name, '/') == NULL)
            snprintf(pathname, 1024, "%s/%s", SYSCONF_LOC, ap_manuf_name);
        else
            snprintf(pathname, 1024, "%s", ap_manuf_name);

        if ((manuf_data = fopen(pathname, "r")) == NULL) {
            fprintf(stderr, "WARNING:  Unable to open '%s' for reading (%s), AP manufacturers "
                    "and defaults will not be detected.\n",
                    pathname, strerror(errno));
        } else {
            fprintf(stderr, "Reading AP manufacturer data and defaults from %s\n", pathname);
            ReadManufMap(manuf_data, 1, &ap_manuf_map);
            fclose(manuf_data);
        }

        free(ap_manuf_name);
    }

    if (client_manuf_name != NULL) {
        char pathname[1024];

        if (strchr(client_manuf_name, '/') == NULL)
            snprintf(pathname, 1024, "%s/%s", SYSCONF_LOC, client_manuf_name);
        else
            snprintf(pathname, 1024, "%s", client_manuf_name);

        if ((manuf_data = fopen(pathname, "r")) == NULL) {
            fprintf(stderr, "WARNING:  Unable to open '%s' for reading (%s), client "
                    "manufacturers and defaults will not be detected.\n",
                    pathname, strerror(errno));
        } else {
            fprintf(stderr, "Reading client manufacturer data and defaults "
                    "from %s\n", pathname);
            ReadManufMap(manuf_data, 0, &client_manuf_map);
            fclose(manuf_data);
        }

        free(client_manuf_name);
    }

    // Initialize stuff
    num_tracks = 0;
//    memset(&global_map_avg, 0, sizeof(gps_network));

#ifdef HAVE_PTHREAD
    // Build the threads
    mapthread = new pthread_t[numthreads];
    pthread_mutex_init(&power_lock, NULL);
    pthread_mutex_init(&print_lock, NULL);
    pthread_mutex_init(&power_pos_lock, NULL);
#endif

    // Imagemagick stuff
    Image *img = NULL;
    ImageInfo *img_info;
    DrawInfo *di;
    char prim[1024];

    InitializeMagick(*argv);
    GetExceptionInfo(&im_exception);
    img_info = CloneImageInfo((ImageInfo *) NULL);
    di = CloneDrawInfo(img_info, NULL);

    for (int x = optind; x < argc; x++) {
        if (ProcessGPSFile(argv[x]) < 0) {
            fprintf(stderr, "WARNING:  Unrecoverable error processing GPS data file "
                    "\"%s\", skipping.\n", argv[x]);
        }
    }

    if (sample_points == 0) {
        fprintf(stderr, "FATAL:  No samples from any of the files given.\n");
        exit(1);
    }
        
    fprintf(stderr, "Processing %d sample points.\n",
            sample_points);

    map_avg_lat = (double) (global_map_avg.min_lat + 
                            global_map_avg.max_lat) / 2;
    map_avg_lon = (double) (global_map_avg.min_lon + 
                            global_map_avg.max_lon) / 2;
    
    // Fit the whole map if we can
    if (user_scale == 0) {
        if (BestMapScale(&map_scale, &fetch_scale, global_map_avg.min_lat, 
                         global_map_avg.min_lon, global_map_avg.max_lat, 
                         global_map_avg.max_lon) < 0) {
            fprintf(stderr, "Could not find a suitable scale for the sample "
                    "points. Please manually provide a scale with the -s "
                    "option.\n");
            exit(1);
        }
    }

    fprintf(stderr, "Map image scale: %ld\n", map_scale);
    fprintf(stderr, "Minimum Corner (lat/lon): %f x %f\n", 
            global_map_avg.min_lat, global_map_avg.min_lon);
    fprintf(stderr, "Maximum Corner (lat/lon): %f x %f\n", 
            global_map_avg.max_lat, global_map_avg.max_lon);
    fprintf(stderr, "Map center (lat/lon): %f x %f\n", 
            map_avg_lat, map_avg_lon);

    if (usermap && user_scale == 0 && user_latlon == 0 && usersize == 0) {
        float filelat, filelon;
        long filescale;
        int filewidth, fileheight;

        if (sscanf(mapname, "map_%f_%f_%ld_%d_%d.gif",
                   &filelat, &filelon, &filescale, &filewidth, 
                   &fileheight) == 5) {
            user_lat = filelat;
            user_lon = filelon;
            user_scale = filescale;
            map_width = filewidth;
            map_height = fileheight;
        }
    }

    if (user_scale != 0) {
        fprintf(stderr, "Overriding with user scale: %ld\n", user_scale);
        map_scale = user_scale;
    }

    if (user_lat != 0) {
        fprintf(stderr, "Overriding with user map center (lat/lon): %f x %f\n",
                user_lat, user_lon);

        map_avg_lat = user_lat;
        map_avg_lon = user_lon;
    }

    if (map_scale == 0) {
        fprintf(stderr, "Unable to find a map at any scale to fit the data.\n");
        exit(0);
    }

    if (!usermap) {
        snprintf(mapname, 1024, "map_%f_%f_%ld_%d_%d.gif", map_avg_lat, 
                 map_avg_lon, map_scale, map_width, map_height);
    }

    if (useroutmap == false)
        snprintf(mapoutname, 1024, "map_%f_%f_%ld_%d_%d.png", map_avg_lat, 
                 map_avg_lon, map_scale, map_width, map_height);

    strcpy(img_info->filename, mapname);

    // Load the map or create the blank
    unsigned char *pixdata = NULL;
    if (mapsource != MAPSOURCE_NULL) {
        printf("Loading map into Imagemagick structures.\n");
        img = ReadImage(img_info, &im_exception);
    } else {
        printf("Creating blank map image.\n");
        pixdata = (unsigned char *) malloc(sizeof(unsigned char) *
                                           map_width * map_height * 3);
        img = ConstituteImage(map_width, map_height, "RGB", CharPixel,
                              pixdata, &im_exception);
        if (im_exception.severity != UndefinedException) {
            fprintf(stderr, "FATAL: ConstituteImage failed for null mapsource\n");
            CatchException(&im_exception);
            exit(1);
        }

        snprintf(prim, 1024, "stroke white fill white fill-opacity 100%% "
                 "rectangle 0,0 %d,%d", map_width, map_height);
        di->primitive = prim;
        DrawImage(img, di);
        GetImageException(img, &im_exception);
        if (im_exception.severity != UndefinedException) {
            fprintf(stderr, "FATAL: Couldn't blank image.\n");
            CatchException(&im_exception);
            exit(1);
        }
        di->primitive = strdup("");
    }

    if (img == (Image *) NULL) {
        if (usermap) {
            fprintf(stderr, "Unable to load '%s'\n", mapname);
            exit(1);
        }

        if (mapsource == MAPSOURCE_MAPPOINT) {
            fprintf(stderr, "The source you selected is known to be broken.  "
                    "Support remains for this source only if previously "
                    "downloaded maps are available, because the map vendor has "
                    "changed their interface in a way that prevents gpsmap "
                    "from getting the images.\n");
            exit(1);
        }
        
        char url[1024];

        if (mapsource == MAPSOURCE_MAPBLAST) {
            snprintf(url, 1024, url_template_mb, map_avg_lat, map_avg_lon, 
                     map_scale, map_width, map_height, 
                     metric ? "&DU=KM" : "");
        } else if (mapsource == MAPSOURCE_TERRA) {
            snprintf(url, 1024, url_template_ts, map_avg_lat, map_avg_lon, 
                     fetch_scale, map_width, map_height);
        } else if (mapsource == MAPSOURCE_TERRATOPO) {
            snprintf(url, 1024, url_template_tt, map_avg_lat, map_avg_lon, 
                     fetch_scale, map_width, map_height);
        } else if (mapsource == MAPSOURCE_TIGER) {
            snprintf(url, 1024, url_template_ti, map_avg_lat, map_avg_lon, 
                     (map_scale / 300000.0), map_width, map_height);
        } else if (mapsource == MAPSOURCE_EARTHAMAPS) {
            snprintf(url, 1024, url_template_em, mapname, map_avg_lat, 
                     map_avg_lon, map_width, map_height, fetch_scale);
        } else if (mapsource == MAPSOURCE_EUEX) {
	    fetch_scale = (long) (map_scale / 3950);
	    char loc[8] = "USA0409";
	    if (map_avg_lat > (-30.0))
		strcpy(loc,"EUR0809");
	    snprintf(url, 1024, url_template_euex, map_avg_lat, map_avg_lon,
		 loc, fetch_scale, map_width, map_height);
		} else if (mapsource == MAPSOURCE_OSM) {
			switch (map_scale) {
				case 2100: 
					osm_zoomlevel = 17;
					break;
				case 4320: 
					osm_zoomlevel = 16;
					break;
				case 8600: 
					osm_zoomlevel = 15;
					break;
				case 17200: 
					osm_zoomlevel = 14;
					break;
				case 34000: 
					osm_zoomlevel = 13;
					break;
				default:
					fprintf(stderr, "Scale %ld not supported by mapsource OSM. Valid "
							"scales for OSM are:\n", map_scale);
					fprintf(stderr, "\t2100\n\t4320\n\t8600\n\t17200\n\t34000\n");
					exit(1);
					break;
			}
			printf("OSM Debug: Scale %ld maps to zoomlevel %d\n", 
				   map_scale, osm_zoomlevel);
			snprintf(url, 1024, url_template_osm, map_avg_lat, 
					 map_avg_lon, osm_zoomlevel, map_width, map_height);
		}

		printf("Map url: %s\n", url);
        printf("Fetching map...\n");

        if (mapsource == MAPSOURCE_EARTHAMAPS) {
            int retval	= system(url);

            if (retval != 0) {
                fprintf(stderr, "Could not run %s: %s\n", url, strerror(retval));
                exit(1);
            }
        } else {
            char geturl[1024];
            snprintf(geturl, 1024, download_template, url, mapname);
            if (system(geturl)!=0) {
	      fprintf(stderr, "WARNING: failed to execute '%s'\n", geturl);
	      exit(1);
	    }
        }

        printf("Loading map into Imagemagick structures.\n");
        strcpy(img_info->filename, mapname);
        img = ReadImage(img_info, &im_exception);

        if (img == (Image *) NULL) {
            fprintf(stderr, "FATAL:  ImageMagick error:\n");
            MagickError(im_exception.severity, im_exception.reason, im_exception.description);
            exit(0);
        }
    } else {
        filemap = true;
    }

    strcpy(img_info->filename, mapoutname);
    strcpy(img->filename, mapoutname);

    // Convert it to greyscale and then back to color
    if (convert_greyscale) {
        fprintf(stderr, "Converting map to greyscale.\n");
        SetImageType(img, GrayscaleType);
        SetImageType(img, TrueColorType);
    } else if (color_saturation) {
        fprintf(stderr, "Desaturating color to %d%%\n", color_saturation);
        snprintf(prim, 1024, "100,%d,100", color_saturation);
        ModulateImage(img, prim);
    }

    // Overlay it if needed
    if (map_intensity != 0) {
        fprintf(stderr, "Adjusting map intensity to %d%%\n", map_intensity);
        // This means making a whole new image and overlaying things
        unsigned char *pixdata;
        unsigned char *apixdata;
        ExceptionInfo excep;
        GetExceptionInfo(&excep);

        Image *alpha_img = NULL;
        ImageInfo *alpha_info = CloneImageInfo((ImageInfo *) NULL);
        DrawInfo *alpha_di = NULL;
    
        Image *base_img = NULL;
        ImageInfo *base_info = CloneImageInfo((ImageInfo *) NULL);
        DrawInfo *base_di = NULL;

        // Allocate space for both alpha and normal 
        pixdata = (unsigned char *) malloc(sizeof(unsigned char) *
                                           map_width * map_height * 4);
        apixdata = (unsigned char *) malloc(sizeof(unsigned char) *
                                           map_width * map_height);
        memset(pixdata, 0, sizeof(unsigned char) * map_width * map_height * 4);
        memset(apixdata, 0, sizeof(unsigned char) * map_width * map_height);

        // Allocate the RGB+Alpha channel image
        base_img = ConstituteImage(map_width, map_height, "RGBA", CharPixel,
                                   pixdata, &excep);
        if (excep.severity != UndefinedException) {
            fprintf(stderr, "WARNING: ConstituteImage failed for base\n");
            CatchException(&excep);
            return -1;
        }

        // Allocate an intensity-only image to build the alpha channel into
        alpha_img = ConstituteImage(map_width, map_height, "I", CharPixel,
                                    apixdata, &excep);
        if (excep.severity != UndefinedException) {
            fprintf(stderr, "WARNING: ConstituteImage failed for alpha channel\n");
            CatchException(&excep);
            return -1;
        }

        base_di = CloneDrawInfo(base_info, NULL);
        alpha_di = CloneDrawInfo(alpha_info, NULL);

        // Draw the alpha channel
        char alcolor[8];
        PixelPacket alphaclr;
        int alperc = (int) rintf((float) 255 * 
                                 ((float) abs(map_intensity) / (float) 100));

        snprintf(alcolor, 8, "#%02X%02X%02X", alperc, alperc, alperc);

        QueryColorDatabase(alcolor, &alphaclr, &excep);
        if (excep.severity != UndefinedException) {
            fprintf(stderr, "FATAL: QueryColorDatabase failed for %s\n", 
                    alcolor);
            CatchException(&excep);
            exit(1);
        }
        alpha_di->fill = alphaclr;
        alpha_di->stroke = alphaclr;

        snprintf(prim, 1024, "fill-opacity 100%% stroke-opacity 100%% "
                 "rectangle 0,0 %d,%d", map_width, map_height);

        alpha_di->primitive = prim;

        DrawImage(alpha_img, alpha_di);
        GetImageException(alpha_img, &excep);
        if (excep.severity != UndefinedException) {
            fprintf(stderr, "WARNING: DrawImage failed for %s\n", prim);
            CatchException(&excep);
            return -1;
        }

        // Copy the map over the base image
        CompositeImage(base_img, OverCompositeOp, img, 0, 0);

        // Blank the map image
        snprintf(prim, 1024, "stroke %s fill %s fill-opacity 100%% "
                 "stroke-opacity 100%% rectangle 0,0 %d,%d", 
                 map_intensity < 0 ? "black" : "white",
                 map_intensity < 0 ? "black" : "white",
                 map_width, map_height);
        di->primitive = prim;
        DrawImage(img, di);
        GetImageException(img, &excep);
        if (excep.severity != UndefinedException) {
            fprintf(stderr, "WARNING: DrawImage failed for %s\n", prim);
            CatchException(&excep);
            return -1;
        }
        alpha_img->matte = (MagickBooleanType) false;

        // Composite the alpha and new map images
        // base is now the map with the new alpha channel
        CompositeImage(base_img, CopyOpacityCompositeOp, alpha_img, 0, 0);

        // Now we merge that over the filled in original map image
        CompositeImage(img, OverCompositeOp, base_img, 0, 0);

        // Clean up our garbage
        alpha_di->text = strdup("");
        alpha_di->primitive = strdup("");

        DestroyImageInfo(alpha_info);
        DestroyDrawInfo(alpha_di);
        DestroyImage(alpha_img);

        base_di->text = strdup("");
        base_di->primitive = strdup("");

        DestroyImageInfo(base_info);
        DestroyDrawInfo(base_di);
        DestroyImage(base_img);

        free(pixdata);
        free(apixdata);
    }

    fprintf(stderr, "Calculating network coordinates and statistics...\n");
    ProcessNetData(verbose);

    fprintf(stderr, "Assigning network colors...\n");
    AssignNetColors();    
    
    // Build a vector.  This can become a selected list in the future.
    vector<gps_network *> gpsnetvec;
    for (map<string, gps_network *>::iterator x = bssid_gpsnet_map.begin();
         x != bssid_gpsnet_map.end(); ++x) {

        // Skip filtered
        if (x->second->filtered || x->second->count < ignore_under_count || x->second->diagonal_distance < ignore_under_distance)
            continue;

        gpsnetvec.push_back(x->second);
    }

    fprintf(stderr, "Plotting %zd networks...\n", gpsnetvec.size());

    for (unsigned int x = 0; x < draw_feature_order.length(); x++) {
        switch (draw_feature_order[x]) {
        case 'p':
            if (draw_power && power_data == 0) {
                fprintf(stderr, "ERROR:  Interpolated power drawing requested, but none of the GPS datafiles being\n"
                        "processed have power data.  Not doing interpolated graphing.\n");
            } else if (draw_power) {
                fprintf(stderr, "Drawing network power interpolations...\n");
                DrawNetPower(gpsnetvec, img, di);
            }
            break;
        case 't':
            if (draw_track) {
                fprintf(stderr, "Drawing track coordinates, width: %d...\n", track_width);
                DrawNetTracks(img, di);
            }
            break;
        case 'b':
            if (draw_bounds) {
                fprintf(stderr, "Calculating and drawing bounding rectangles...\n");
                DrawNetBoundRects(gpsnetvec, img, di, bounds_opacity);
            }
            break;
        case 'r':
            if (draw_range) {
                fprintf(stderr, "Calculating and drawing network circles...\n");
                DrawNetCircles(gpsnetvec, img, di);
            }
            break;
        case 'h':
            if (draw_hull) {
                fprintf(stderr, "Calculating and drawing network hulls...\n");
                DrawNetHull(gpsnetvec, img, di);
            }
            break;
        case 's':
            if (draw_scatter) {
                fprintf(stderr, "Drawing scatter plot, dot size %d...\n", scatter_resolution);
                DrawNetScatterPlot(gpsnetvec, img, di);
            }
            break;
        case 'c':
            if (draw_center) {
                fprintf(stderr, "Drawing center dot, size %d...\n", center_resolution);
                DrawNetCenterDot(gpsnetvec, img, di);
            }
            break;
        case 'l':
            if (draw_label) {
                fprintf(stderr, "Labeling networks...\n");
                DrawNetCenterText(gpsnetvec, img, di);
            }
            break;
        default:
            fprintf(stderr, "WARNING:  Unknown feature '%c' in requested order.  Skipping.\n",
                    draw_feature_order[x]);
            break;
        };
    }

    // Make sure our DI has a clean primitive, since all of the other assignments were
    // local variables
    di->text = strdup("");
    di->primitive = strdup("");

    // Draw the legend if we're going to...  And of course since it has to be
    // annoying, it needs to be able to modify img itself so it's a pointer to
    // a pointer.
    if (draw_legend) {
        fprintf(stderr, "Drawing legend...\n");
        DrawLegendComposite(gpsnetvec, &img, &di);

        // Clean up and set our new image out values
        di->text = strdup("");
        di->primitive = strdup("");
        img_info = CloneImageInfo((ImageInfo *) NULL);
        strcpy(img_info->filename, mapoutname);
        strcpy(img->filename, mapoutname);
    }

    WriteImage(img_info, img);

    DestroyDrawInfo(di);
    DestroyImage(img);
    if (pixdata != NULL)
        free(pixdata);

    DestroyMagick();

#ifdef HAVE_PTHREAD
    delete[] mapthread;
#endif

    if (!keep_gif && !usermap && !filemap && mapsource != MAPSOURCE_NULL) {
        fprintf(stderr, "Unlinking downloaded map.\n");
        unlink(mapname);
    }

}

#endif