~ctibrazil/fabathome-model1/ApplicationV0.23

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
/*License Notification
Fab@Home operates under the BSD Open Source License

Copyright (c) 2006, Hod Lipson and Evan Malone (evan.malone@cornell.edu) All rights reserved. 

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met: 

Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer. 
Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation and/or 
other materials provided with the distribution. 
Neither the name of the Fab@Home Project nor the names of its contributors may be 
used to endorse or promote products derived from this software without specific 
prior written permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//Printer.cpp
//implementation of the CPrinter class

#include "stdafx.h"
#include ".\printer.h"
#include "FabAtHomeParameters.h"
#include "ToolChangeDlg.h"
#include <vector>

using namespace std;

//--------------------------------------------------------------------
CPrinter::CPrinter(void)
//--------------------------------------------------------------------
{
	Clear();
	pApp = (CFabAtHomeApp *) AfxGetApp();
	pModel = NULL; //will be filled in once valid
	bEmulateHardware = true;
	bHardwareInitialized = false;
	m_bSafeSet = false;
	m_bSafeSetMan = false;
	m_bLastSet = false;
	m_bOriginSet = false;
	m_bHomed = false;
	m_bIsSafe = false;
	bNewStatus = true;
	m_nQSpace = 0;	//memory space remaining in the path queue on the machine
	for(int i = 0; i<AXES_CNT; i++)
	{
		m_arlGlobalPos[i] = 0;	//distance of axes from home position in steps
		m_arBLimitSwitch[2*i] = FALSE;	//which limit switches are connected
		m_arBLimitSwitch[(2*i)+1] = FALSE; //twice as many limits as axes
		m_arbLimitState[2*i] = false;	//states of limit switches
		m_arbLimitState[(2*i)+1] = false; //twice as many limits as axes
		//m_arlEncoder[i] = 0; //raw encoder readings
	}
	m_BFirmwareVersion = -1;		//the firmware version number
	m_stateFlags.STARTED = false;		//has the machine been told to start processing the queue
	m_stateFlags.PAUSED = false;		//is the machine paused
	m_stateFlags.ABORTED = false;		//is the machine aborted (stopped, and queue flushed)
	m_stateFlags.HOMED = false;		//is the HW machine homed
	m_stateFlags.MALF = false;		//is there an error of some sort
	m_stateFlags.MOVING = false;	//is the hardware currently moving
	m_stateFlags.CONFIGURED = false;	//has the microcontroller been successfully configured?
	m_stateFlags.QEMPTY = TRUE;		//the queue should be empty when starting
	m_bCollectStatus = false; //to track whether status is being collected by worker or not
	m_pStatusThread = NULL; //to hold the status thread pointer
	m_dwMachineElapsedTime_ms = 0; //track the elapsed time on the micrcontroller since micro rebo
	m_dwMachineStartTime_ms = 0;	//tick count from microcontroller in first status packet since reset
	m_bFirstPacket = true;	//to identify the first status packet received
	m_dwUSRStatusPeriod = STATUS_UPDATE_PERIOD; //the user's requested status update period
	m_dwCMDStatusPeriod = STATUS_UPDATE_PERIOD; //the commanded period at which the status is collected from the machine
	m_dwTGTStatusPeriod = STATUS_UPDATE_PERIOD; //the target period at which the status should be collected from the machine
	m_nPeriodCalcStep = 0; //counter for steps in status period average calculation
	m_dwACTStatusPeriod = 0; //the achieved status update period
	m_nStatusSamples = 10;	//number of samples to average for status update rate calc
	for(int i = 0; i < m_nStatusSamples; i++)
		m_arStatusPeriod.Add(0); //buffer for averaging status update rate
	m_dwLastCmdExecuted = 0;
	m_dwQueuePathIndex = 0;
	m_sCurTool = "Undefined";
	m_sCurMaterial = "Undefined";
	//for the worker thread sending segments to the microcontroller queue
	m_pathArray.RemoveAll();
	m_nPathIndex = 0;
	m_bQPathDone = true;
	//initialize the range of motion of the positioning axes
	for(int i = 0; i < POSITION_AXES; i++)
		m_ardMaxTravel[i] = 0.0;
	m_nMaxTools = 1; //set the maximum number of tools that can be mounted simultaneously
	m_bPauseAtToolChange = true; //have system pause building during a tool change, unless multitool and user specifies
	m_vPOD = CVec(99,-318,-60); //init to standard 1-syringe tool in tool graphics coords- used to calculate offsets
	m_vPODOffset = CVec(0,0,0); //offset for adjusting point of deposition after tool change
	m_bDefined = false;
	m_dJogSpeed = 5; //speed of all non-build motions, mm/s
	m_ctsTCAuto = AUTO_TC_TIME; //estimated time in seconds for auto (multi-tool system) tool change
	m_ctsTCMan = MAN_TC_TIME; //estimated time in seconds for manual tool change
	m_ctsIdleTime = 0; //idle time with amps on but no motion - for auto disabling of amps
	m_ctIdleStart = 0; //start of idle period
	m_dCommsErrorRate = 0.0; //error rate for status comms with micro
	m_bEnableRequested = false;
	m_bEStop = false;
	m_nPushoutState = 0; //initially should be no net pressure in syringe
	m_bLogging = false; //initially not logging information
	m_dEmulatorSlowdown = EMULATOR_SLOWDOWN; //init speed for emulator

	m_dSubsegLen = -1.0;
	m_dMaxAccel = 10000;
	m_bNetworkConnect = false;
	m_bToolMoving = false;
}

//--------------------------------------------------------------------
CPrinter::~CPrinter(void)
//--------------------------------------------------------------------
{
}

//--------------------------------------------------------------------
bool CPrinter::Shutdown()
//--------------------------------------------------------------------
{
	//if using the hardware, shut it down
	if(bHardwareInitialized) return( ShutdownHardware() );
	//otherwise, make sure all threads are dead
	return( CollectStatus(false) );
}

//--------------------------------------------------------------------
bool CPrinter::CalcAccelParams(double pathWidth, double* pSpeed, double* pRmin)
//--------------------------------------------------------------------
{
	//calculate the parameters to use for acceleration limited path planning
	//max acceleration and pathWidth are considered fixed
	//if radius of curvature = pathspeed^2/Amax > pathwidth/2 then
	//pathspeed will be reduced

	*pRmin = (*pSpeed)*(*pSpeed)/(m_dMaxAccel);
	if(*pRmin >= pathWidth*0.5)
	{
		*pRmin = pathWidth*0.49;
		double newspeed = sqrt((*pRmin)*m_dMaxAccel);
		CString msg;
		if( (newspeed > 0.0) && (newspeed < *pSpeed) )
		{
			*pSpeed = newspeed;
			
			msg.Format("Path speed too high for pathwidth and acceleration.\nReducing pathspeed to %0.3f.",
				newspeed);
			((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		}
		else
		{
			msg.Format("CalcAccelParams(pathwidth %0.3f, pathspeed %0.3f, amax %0.3f): new speed calculation error",
				pathWidth, *pSpeed, m_dMaxAccel);
			return false;
		}
	}
	return true;
}

//--------------------------------------------------------------------
void CPrinter::Log(CString& callingFn, CString& comment)
//--------------------------------------------------------------------
{
	//if not logging, the user open new file, write strings to log
	if(m_bLogging)
	{
		CString msg;
		CVec cmdPos = GetCurrentPos(true);
		CVec rtPos = GetCurrentPos(false);
		CVec podPos = rtPos + m_vPOD;
		double toolCMDPos = GetCurrentToolPos(true);
		double toolRTPos = GetCurrentToolPos(false);

		msg.Format("%d\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%s\t%s\n",
			GetPCElapsedTime(), m_vOrigin.x, m_vOrigin.y, m_vOrigin.z, cmdPos.x, cmdPos.y, cmdPos.z, rtPos.x, rtPos.y, rtPos.z, 
			podPos.x, podPos.y, podPos.z, toolCMDPos, toolRTPos, callingFn, comment);
		m_fLog.Write((LPCTSTR)msg, msg.GetLength());
	}
}

//--------------------------------------------------------------------
void CPrinter::StartLog(CString& startFile)
//--------------------------------------------------------------------
{
	//if already logging, do nothing
	//else open a new logfile, and update logging flag
	if(!m_bLogging)
	{
		CFileDialog dlg(TRUE, "log", (LPCTSTR)startFile, NULL,
					"Log File (*.dat)|*.dat|All Files (*.*)|*.*||", 0);
		if(IDOK != dlg.DoModal()) return;
		startFile = dlg.GetPathName();
		CFileException e;
		if( m_fLog.Open((LPCTSTR)startFile, CFile::modeCreate | CFile::modeWrite, &e))
		{
			m_bLogging = true;
			CString msg;
			msg.Format("Time\tOrigin.x\tOrigin.y\tOrigin.z\tCMDPos.x\tCMDPos.y\tCMDPos.z\tRTPos.x\tRTPos.y\tRTPos.z\tPOD.x\tPOD.y\tPOD.z\tToolCMD\tToolRT\tFunction\tComment\n");
			m_fLog.Write((LPCTSTR)msg,msg.GetLength());
		}
		else
			((CFabAtHomeApp *)AfxGetApp())->Log("Cannot create log file");
	}
}

//--------------------------------------------------------------------
void CPrinter::StopLog()
//--------------------------------------------------------------------
{
	//stop logging and close the log file
	m_bLogging = false;
	m_fLog.Close();
}

//--------------------------------------------------------------------
bool CPrinter::SetPauseAtToolChange(bool bPause)
//--------------------------------------------------------------------
{
	//if this is a multi-tool configuration,
	//then set system to pause build at tool changes according to bPause
	//return true if success
	if(GetMaxTools()>1)
	{
		m_bPauseAtToolChange = bPause;
		return true;
	}
	return false;
}

//--------------------------------------------------------------------
bool CPrinter::SetAutoresume(bool bResume)
//--------------------------------------------------------------------
{
	//if system is autopausing because of tool PAUSEPATHS parameter
	//then automatically resume (without waiting for user action) if bResume
	//return true if success
	m_bAutoresume = bResume;
	return true;
}

//--------------------------------------------------------------------
CTimeSpan &CPrinter::GetManTCTime()
//--------------------------------------------------------------------
{
	//return the estimated time for a manual tool change
	return m_ctsTCMan;
}

//--------------------------------------------------------------------
CTimeSpan &CPrinter::GetAutoTCTime()
//--------------------------------------------------------------------
{
	//return the estimated time for an automatic tool change
	return m_ctsTCAuto;
}

//--------------------------------------------------------------------
bool CPrinter::EnsureLoadedTool(CString &toolname)
//--------------------------------------------------------------------
{
	//ensure that the named tool is loaded by asking user to
	//reload tools if necessary, 
	int idx = -1;

	if(CTool::LoadedToolCount() < 1)
		return false;
	if((idx = CTool::SearchByName(toolname)) < 0)
		return false;

	return true;
}

//--------------------------------------------------------------------
bool CPrinter::EnsureMountedTool(CString& toolname)
//--------------------------------------------------------------------
{
	//ensure that the named tool is loaded and mounted
	//ask user to reload and mount, exit if fail

	if(!EnsureLoadedTool(toolname))
		return false;
	
	if(!CTool::GetByName(toolname)->IsMounted())
		return false;

	return true;
}

//--------------------------------------------------------------------
bool CPrinter::EnsureCurrentTool(bool bForceDlg)
//--------------------------------------------------------------------
{
	// if bForceDlg == true, then show the tool configuration dialog
	//make sure that a current tool is defined, loaded and mounted
	if( (CTool::SearchByName(GetCurToolName()) < 0) )
	{
		if(bForceDlg)
			pApp->UserToolChange();
		return false;
	}
	if(!EnsureMountedTool(GetCurToolName()))
	{
		if(bForceDlg)
			pApp->UserToolChange();
		return false;
	}

	return true;
}

//--------------------------------------------------------------------
CTool* CPrinter::GetCurTool()
//--------------------------------------------------------------------
{
	//return pointer to the current tool
	//prompt user if unable to find
	return(CTool::GetByName(m_sCurTool));
}

//--------------------------------------------------------------------
CMaterial* CPrinter::GetCurMaterial()
//--------------------------------------------------------------------
{
	//return reference to the current material
	return(&(pApp->material[CMaterial::SearchByName(m_sCurMaterial)]));
}


//--------------------------------------------------------------------
bool CPrinter::LoadConfiguration(CString configfilename, CString& errorstr)
//--------------------------------------------------------------------
{// read configuration

	Clear();

	CStdioFile file;
	if (file.Open(configfilename, CFile::modeRead) == 0)
		return false;

	CString line;
	BOOL readok;
	CString error;
	int idx = -1;

	do {
		readok = file.ReadString(line);
		line.Trim();
		if (readok && !line.IsEmpty() && !(line[0]=='#')  && !(line[0]=='/') && !(line[0]=='%') && !(line[0]==';')) {
			CString str1 = line.SpanExcluding(" \t,:");
			CString str1a = line.Mid(str1.GetLength());
			CString str1b = str1a.SpanIncluding(" \t,:");
			CString str2 = str1a.Mid(str1b.GetLength());
			str1.Trim();
			str2.Trim();
			if (!str1.IsEmpty()) {
				if (str1.CompareNoCase("NAME")==0) {
					name = str2;
				} else if (str1.CompareNoCase("DESCRIPTION")==0) {
					description = str2;
				} else if (str1.CompareNoCase("COMPONENT")==0) {
					if (component.GetSize() >= 4) {
						error = "5th component encountered. Printer cannot have more than 4 components";
						errorstr += error;
						return false;
					}
					CString geomfile = CUtils::RemoveComment(str2);
					CString geompath = CUtils::GetPath(configfilename)+"\\"+geomfile;
					CPrinterComponent comp;
					if (_access(geompath,4) != 0 || !comp.geom.LoadSTL(geompath, 10000)) {
						error.Format("%s: Cannot load printer geometry '%s'\n", configfilename, geompath);
						errorstr += error;
						return false;}
					comp.geom.ComputeBoundingBox(comp.pmin, comp.pmax);
					component.Add(comp);
					idx = component.GetSize()-1;
					component[idx].component_geom = geomfile;
				} else if (str1.CompareNoCase("APPENDGEOM")==0) {
					CString geomfile = CUtils::RemoveComment(str2);
					component[idx].component_appendgeom = geomfile;
					CString geompath = CUtils::GetPath(configfilename)+"\\"+geomfile;
					CGeometry tmpgeom;
					bool ok = tmpgeom.LoadSTL(geompath, 10000);
					if (ok) {
						component[idx].geom.AppendGeometry(tmpgeom);
						component[idx].geom.ComputeBoundingBox(component[idx].pmin, component[idx].pmax);
					} else {
						error.Format("%s: Cannot access geometry file '%s'\n", configfilename, geomfile);
						errorstr += error;
					}
				} else if (str1.CompareNoCase("COLOR")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%lf %lf %lf %lf", 
						&component[idx].color.x, 
						&component[idx].color.y, 
						&component[idx].color.z, 
						&component[idx].alpha);
					if (j != 4) {
						error.Format("%s: Cannot read color '%s'\n", configfilename, line);
						errorstr += error;
						component[idx].color = CVec(200,200,200);
						component[idx].alpha = 255;
						return false;
					}
				} else if (str1.CompareNoCase("RANGE")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%lf %lf %lf", 
						&component[idx].rangemin,
						&component[idx].rangemax, 
						&component[idx].home);
					if (j != 3) {
						error.Format("%s: Cannot read range parameters '%s'\n", configfilename, line);
						errorstr += error;
						component[idx].rangemin = 0;
						component[idx].rangemax = 240;
						component[idx].home = 0;
						return false;
					}
				} else if (str1.CompareNoCase("DIRECTION")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%ld %lf %lf %lf", 
						&component[idx].refidx,
						&component[idx].dir.x, 
						&component[idx].dir.y, 
						&component[idx].dir.z);
					component[idx].dir.Normalize();
					if (j != 4) {
						error.Format("%s: Cannot read motion parameters '%s'\n", configfilename, line);
						errorstr += error;
						return false;
					}
					if (component[idx].refidx >= idx) {
						error.Format("%s: Component %d cannot reference future component %d in '%s'\n", configfilename, idx, component[idx].refidx, line);
						errorstr += error;
						component[idx].refidx = -1;
						return false;
					}
				} else if (str1.CompareNoCase("MOTOR")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%ld %ld %lf", 
						&component[idx].axis, &component[idx].axisDir, 
						&component[idx].mmps);
					if (j != 3) {
						error.Format("%s: Cannot read motor parameters '%s'\n", configfilename, line);
						errorstr += error;
						return false;
					}
				} else if (str1.CompareNoCase("LIMITSWITCH")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%d %d", &component[idx].posLimitSwitch, &component[idx].negLimitSwitch);
					if (j != 2) {
						error.Format("%s: Cannot read limit switch config '%s'\n", configfilename, line);
						errorstr += error;
						component[idx].posLimitSwitch = FALSE;
						component[idx].negLimitSwitch = FALSE;
					}
				} else if (str1.CompareNoCase("INCREMENT")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%lf", &component[idx].jogIncrement);
					if (j != 1) {
						error.Format("%s: Cannot read jog increment'%s'\n", configfilename, line);
						errorstr += error;
						component[idx].jogIncrement = JOG_STEP_AXIS;
					}
				} else if (str1.CompareNoCase("OFFSET")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%lf %lf %lf", &component[idx].offset.x, &component[idx].offset.y, &component[idx].offset.z);
					if (j != 3) {
						error.Format("%s: Cannot read offset coordinates '%s'\n", configfilename, line);
						errorstr += error;
						component[idx].offset = CVec(0,0,0);
						return false;
					}
				} else if (str1.CompareNoCase("STATUS_UPDATE_PERIOD")==0) {
					str2.Replace(","," ");
					double period;
					int j=sscanf_s(str2,"%lf", &period);
					SetUserStatusPeriod((DWORD)period);
					if (j != 1) {
						error.Format("%s: Cannot read status update rate '%s'\nPlease add entry STATUS_UPDATE_PERIOD and value to .printer file",
							configfilename, line);
						errorstr += error;
						return false;
					}
				} else if (str1.CompareNoCase("MAXTOOLS")==0) {
					str2.Replace(","," ");
					int n;
					int j=sscanf_s(str2,"%d", &n);
					SetMaxTools(n);
					if (j != 1) {
						error.Format("%s: Cannot read maximum number of tools: '%s'",
							configfilename, line);
						errorstr += error;
						return false;
					}
				} else if (str1.CompareNoCase("JOGSPEED")==0) {
					str2.Replace(","," ");
					double spd;
					int j=sscanf_s(str2,"%lf", &spd);
					SetJogSpeed(spd);
					if (j != 1) {
						error.Format("%s: Cannot read jog speed: '%s'",
							configfilename, line);
						errorstr += error;
						return false;
					}
				} else if (str1.CompareNoCase("TOOLLIMITSWITCH")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%d %d", 
						&m_arBLimitSwitch[2*AXIS_U+1], 
						&m_arBLimitSwitch[2*AXIS_V+1]);
					if (j != 2) {
						error.Format("%s: Cannot read limit switch config '%s'\n", configfilename, line);
						errorstr += error;
						m_arBLimitSwitch[2*AXIS_U+1] = FALSE;
						m_arBLimitSwitch[2*AXIS_V+1] = FALSE;
					}
				} else if (str1.CompareNoCase("DEFAULT_POD")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%lf %lf %lf", &m_vPOD.x, &m_vPOD.y, &m_vPOD.z);
					if (j != 3) {
						error.Format("%s: Cannot read default point of deposition: '%s'",
							configfilename, line);
						errorstr += error;
						return false;
					}
				} else if (str1.CompareNoCase("MAX_ACCEL")==0) {
					str2.Replace(","," ");
					int j=sscanf_s(str2,"%lf", &m_dMaxAccel);
					if (j != 1) {
						error.Format("%s: Cannot read maximum acceleration: '%s'",
							configfilename, line);
						errorstr += error;
						m_dMaxAccel = 10000;
						return false;
					}
				} else {
					error.Format("%s: Unrecognized token '%s'\n", configfilename, str1);
					errorstr += error;
				}
			} else {
				error.Format("%s: Cannot parse '%s'\n", configfilename, line);
				errorstr += error;
			}
		}
	} while (readok);

	file.Close();

	//gather all of the configuration information into a compact format
	for (int i=1; i<=POSITION_AXES; i++)
	{
		//two limit switches per axis, configuration stored in printer component
		m_arBLimitSwitch[2*component[i].axis]=component[i].posLimitSwitch;
		m_arBLimitSwitch[(2*component[i].axis)+1]=component[i].negLimitSwitch;
		//store the travel for the axes
		m_ardMaxTravel[i-1] = abs((component[i].rangemax)-(component[i].rangemin));
	}
	//TODO: handle limit switch configuration for tool axes

	return true;
}

//--------------------------------------------------------------------
void CPrinter::Clear(void)
//--------------------------------------------------------------------
{
	name = "";
	description= "";	

	component.RemoveAll();
}

//--------------------------------------------------------------------
bool CPrinter::IsFabricating()
//--------------------------------------------------------------------
{
	//return true if the model is valid and fabrication has been started
	if(pModel != NULL)
	{
		if(pModel->fab.IsFabricating()) return true;
	}
	return false;
}

//--------------------------------------------------------------------
bool CPrinter::Draw(bool bCommanded)
//--------------------------------------------------------------------
{// if bCommanded, draw the desired destination, else
	//show the "real-time" (delayed) position

	if (!IsDefined())
		return false;

	//draw the current tool
	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock(2*m_dwTGTStatusPeriod);
	if(GetCurTool()!=NULL)
		GetCurTool()->Draw(bCommanded);

	for (int i=0; i<component.GetSize(); i++) 
	{
		component[i].Draw(bCommanded);
	}

	return true;
}

//--------------------------------------------------------------------
void CPrinter::JogCarriageBy(CVec delta, bool bQueue)
//--------------------------------------------------------------------
{// move carriage by specified amount in mm

	CFabAtHomeApp *pApp = (CFabAtHomeApp *) AfxGetApp();

	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	component[1].stepstomove = (delta.x/component[1].mmps);
	component[2].stepstomove = (delta.y/component[2].mmps);
	component[3].stepstomove = (delta.z/component[3].mmps);

	//update the current commanded position
	SetCurrentCmdPos(delta + GetCurrentPos(bQueue));
	//TRACE("%.2f %.2f %.2f\n", delta.x, delta.y, delta.z);
}

//--------------------------------------------------------------------
void CPrinter::JogCarriageTo(CVec abspos, bool bQueue, CVec *pCurPos)
//--------------------------------------------------------------------
{// move carriage to specified position

	//if queuing this command then use the commanded position to eliminate latency errors
	//in "real-time" position
	//TRACE("%.2f %.2f %.2f\n", abspos.x, abspos.y, abspos.z);
	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();

	CVec delta = abspos - GetCurrentPos(bQueue);
	if(pCurPos!=NULL)
		delta = abspos - *pCurPos;
	JogCarriageBy(delta, bQueue);

}

//--------------------------------------------------------------------
CVec CPrinter::GetCurrentPos(bool bCommanded)
//--------------------------------------------------------------------
{
	double x,y,z;

	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	
	if(bCommanded)
	{
		//just report the commanded value
		x = component[1].GetCMDPos();
		y = component[2].GetCMDPos();
		z = component[3].GetCMDPos();
		TRACE("GetCurPos:CMD(%.2f,%.2f,%.2f)\n", x, y, z);
	}
	else
	{
		//the "real-time" (typically inaccurate during motion) value is desired
		x = component[1].GetRTPos();
		y = component[2].GetRTPos();
		z = component[3].GetRTPos();
		TRACE("GetCurPos:RT(%.2f,%.2f,%.2f)\n", x, y, z);
	}

	return CVec(x,y,z);
}

//--------------------------------------------------------------------
void CPrinter::SetCurrentCmdPos(CVec abspos)
//--------------------------------------------------------------------
{// update the current commanded position for the carriage

	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	component[1].SetCMDPos(abspos.x);
	component[2].SetCMDPos(abspos.y);
	component[3].SetCMDPos(abspos.z);
	//TRACE("%0.2f %0.2f %0.2f\n", component[1].cmdstep, component[2].cmdstep, component[3].cmdstep);
}

//--------------------------------------------------------------------
bool CPrinter::InPosition(double tol)
//--------------------------------------------------------------------
{
	//true if the real time position of the printer is 
	//within tol (each axis) of the commanded pos
	//positions are not valid prior to homing, so always return when not homed
	if(!IsHomed()) return true;

	CVec err = (GetCurrentPos(false)-GetCurrentPos(true));
	TRACE("InPosition Distance: (%0.3f,%0.3f,%0.3f)\n",err.x, err.y, err.z);
		
	return((tol*tol) > err.Length2());
}

//--------------------------------------------------------------------
void CPrinter::JogToolBy(double delta, bool bQueue)
//--------------------------------------------------------------------
{// move tool actuator by specified amount in mm

	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	GetCurTool()->stepstomove = (delta/GetCurTool()->mmps);

	//update the current commanded position
	//SetCurrentToolCmdPos(delta + GetCurrentToolPos(bQueue));
	SetCurrentToolCmdPos(0);
}

//--------------------------------------------------------------------
void CPrinter::JogToolTo(double abspos, bool bQueue)
//--------------------------------------------------------------------
{// move tool axis to specified position

	//if this command is to be queued, then calculate using
	//the commanded position because of latency in "real-time" position
	//for immediate commands, use the "real-time"
	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	double delta = abspos - GetCurrentToolPos(bQueue);

	JogToolBy(delta, bQueue);

}

//--------------------------------------------------------------------
bool CPrinter::Pushout(bool bQueue)
//--------------------------------------------------------------------
{
	//command a standard pushout for the active tool
	//only pushout if pushout state is <=0, meaning net negative pressure
	CString msg1,msg2;
	msg1.Format("Pushout(%d)",bQueue);
	msg2.Format("m_nPushoutState:%d",m_nPushoutState);
	Log(msg1,msg2);
	if(m_nPushoutState<=0)
	{
		double mmpushout = GetCurTool()->pushout *
						OLD_MSPS *
						GetCurTool()->mmps;
		DWORD index = 0;
		JogToolBy(mmpushout, bQueue);
		Move(bQueue, &index);
		WaitForMoveStart(index);
		WaitForMoveDone(index);
		m_nPushoutState++;
		return true;
	}
	return false;
}

//--------------------------------------------------------------------
bool CPrinter::Suckback(bool bQueue)
//--------------------------------------------------------------------
{
	//command a standard suckback for the active tool
	//only suckback if pushout state is >= 0, meaning net positive pressure
	CString msg1, msg2;
	msg1.Format("Suckback(%d)",bQueue);
	msg2.Format("m_nPushoutState:%d",m_nPushoutState);
	Log(msg1,msg2);
	if(m_nPushoutState>=0)
	{
		double mmsuckback = GetCurTool()->pushout *
						OLD_MSPS *
						GetCurTool()->mmps;
		DWORD index = 0;
		JogToolBy(-mmsuckback, bQueue); //immediately
		Move(bQueue, &index);
		WaitForMoveStart(index);
		WaitForMoveDone(index);
		m_nPushoutState--;
		return true;
	}
	return false;
}


//--------------------------------------------------------------------
double CPrinter::GetCurrentToolPos(bool bCommanded)
//--------------------------------------------------------------------
{
	//if bCommanded, return the commanded destination for the tool
	//else return the "real-time" (delayed)
	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	double x;
	if(bCommanded)
		x = GetCurTool()->cmdstep*GetCurTool()->mmps;
	else
		x = GetCurTool()->curstep*GetCurTool()->mmps;

	return x;
}

//--------------------------------------------------------------------
void CPrinter::SetCurrentToolCmdPos(double abspos)
//--------------------------------------------------------------------
{
	//set the currently commanded destination for the actuator of the specified tool
	//ensure thread safety
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	GetCurTool()->cmdstep = (abspos/GetCurTool()->mmps);
}

//--------------------------------------------------------------------
double CPrinter::GetClearance( bool inChunk )
//--------------------------------------------------------------------
{
	//TODO: Move all path planning to a planner module
	//if inChunk, then assume we are not going to collide with 
	//other, possibly taller chunks, so just return the path to path clearance
	//height specified for this tool
	//otherwise,return the vertical clearance required to prevent tool tip
	//from colliding with the tallest part of the model built thus far

	//start by getting the recommended path to path clearance for this tool
	double z = GetCurTool()->GetClearance();
	//if we are leaving the bounding box of the current chunk, we might
	//collide with a different chunk, so increase clearance by max current height of model
	if(!inChunk)
		z += m_dModelClearance-(GetOrigin().z-GetCurrentPos().z);

	if( (z > 0.0) && (z < 300) ) return z;
	else return DEFAULT_TRAVEL_CLEARANCE;
}

//--------------------------------------------------------------------
CVec CPrinter::GetSafePos(void)
//--------------------------------------------------------------------
{ 
	//return the safe position set by the user
	return m_vSafePos;
}

//--------------------------------------------------------------------
bool CPrinter::SetSafePos(CVec sfpos)
//--------------------------------------------------------------------
{
	//set the specified position as the safe position
	if( sfpos != CVec(0,0,0) )
	{
		m_vSafePos = sfpos;
	}
	else //set the current real-time position as the safe position
	{
		m_vSafePos = GetCurrentPos(false);
	}
	m_bSafeSet = true;
	return m_bSafeSet;
}

//--------------------------------------------------------------------
CVec CPrinter::GetLastPos(void)
//--------------------------------------------------------------------
{
	//return the position stored as the "last" position, e.g. before a pause
	return m_vLastPos;
}

//--------------------------------------------------------------------
bool CPrinter::SetLastPos(CVec lpos)
//--------------------------------------------------------------------
{
	//set the specified position as the prior or last position; for resuming from a pause
	if( lpos != CVec(0,0,0) )
	{
		m_vLastPos = lpos;
	}
	else //set the current real-time position as the last position
	{
		m_vLastPos = GetCurrentPos(false);
	}
	m_bLastSet = true;
	CString msg1;
	msg1.Format("SetLastPos(%0.2f,%0.2f,%0.2f)",m_vLastPos.x,m_vLastPos.y,m_vLastPos.z);
	Log(msg1,msg1);
	return m_bLastSet;
}

//--------------------------------------------------------------------
CVec CPrinter::RobotToModelTfm( CVec &v )
//--------------------------------------------------------------------
{
	//transform the given vector into model coords
	return( CVec(v.x,v.y,-v.z) );
}

//--------------------------------------------------------------------
CVec CPrinter::ModelToRobotTfm( CVec &v )
//--------------------------------------------------------------------
{
	//transform the given vector into robot coords
	return( CVec(v.x,v.y,-v.z) );
}

//---------------------------------------------------------------------------
bool CPrinter::CanAutoRange()
//---------------------------------------------------------------------------
{
	//return true if the printer configuration allows for automatic homing
	//and automatic identification of range of motion
	
	if(!bEmulateHardware) //if only emulating hardware, then always true
	{
		//check that x, y, z limit switches are configured
		//for both forward and backward motion
		int i = 0;
		while(i<POSITION_AXES && 
			m_arBLimitSwitch[2*component[i+1].axis] &&
			m_arBLimitSwitch[(2*component[i+1].axis)+1])
		{
			i++;
		}
		return (i==POSITION_AXES); //xfwd,xbkd,yfwd,ybkd,zfwd,zbkd all configured
	}
	return true;
}

//---------------------------------------------------------------------------
UINT CPrinter::HomeSeqProc( LPVOID pParam )
//---------------------------------------------------------------------------
{
	//worker function for homing sequence
	CPrinter *pMachine = (CPrinter *)pParam;
	if(pMachine->IsHomed())
		pMachine->FindHomePos();
	else if(AfxMessageBox("Automatically find home position?", MB_OKCANCEL)==IDOK)
			pMachine->FindHomePos(); //try to automatically find the home position
	return 0;
}

//---------------------------------------------------------------------------
void CPrinter::ExecuteHomeSequence()
//---------------------------------------------------------------------------
{
	//start a worker thread to execute a short sequence of immediate motions
	//these execute ahead of any queued motion.

	AfxBeginThread(HomeSeqProc,this);

}

//--------------------------------------------------------------------
void CPrinter::GotoHome()
//--------------------------------------------------------------------
{// move printer head to home position (0,0,0)

	CVec home = CVec(0.0,0.0,0.0);
	if(bEmulateHardware || IsHomed())
	{
		DWORD index = 0; //var to store index for completion check
		JogCarriageTo(home, false); //immediate motion
		Move(false, &index); //immediate
		WaitForMoveStart(index);
		WaitForMoveDone(index);
	}
	else
	{
		CString msg;
		msg.Format("Hardware not homed");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	}
	// TODO: If limit switches installed, drive a little extra into the switches
}

//--------------------------------------------------------------------
bool CPrinter::IsHomed()
//--------------------------------------------------------------------
{
	//true if software is homed and emulating or both software and hardware
	//are homed and using hardware
	if(bEmulateHardware)
		return m_bHomed;
	if(!bEmulateHardware && bHardwareInitialized)
		return (m_bHomed && m_stateFlags.HOMED);
	return false;
}

//--------------------------------------------------------------------
void CPrinter::GotoOrigin()
//--------------------------------------------------------------------
{// move printer head to build origin position

	if(bEmulateHardware || !bHardwareInitialized || m_bOriginSet)
	{
		DWORD index = 0; //var to store index for completion check

		//determine where to go
		CVec org = GetOrigin();
		double trav = GetClearance(false); //false to indicate possible collision
		//move down for safe traverse
		JogCarriageBy(CVec(0,0,-trav), false); //immediate, not queued
		Move(false, &index);
		WaitForMoveStart(index);
		WaitForMoveDone(index);
		//move to the last position, xy first
		CVec cur = GetCurrentPos(false);
		JogCarriageTo(CVec(org.x, org.y, cur.z),false); //immediate, not queued
		Move(false, &index);
		WaitForMoveStart(index);
		WaitForMoveDone(index);
		//then move the z
		JogCarriageTo(org, false); //immediate, not queued
		Move(false, &index);
		WaitForMoveStart(index);
		WaitForMoveDone(index);
	}
	else
	{
		CString msg;
		msg.Format("Last return position not set");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	}
}

//---------------------------------------------------------------------------
UINT CPrinter::OriginSeqProc( LPVOID pParam )
//---------------------------------------------------------------------------
{
	//worker function for 
	CPrinter *pMachine = (CPrinter *)pParam;
	if(pMachine->IsOriginSet())
		pMachine->GotoOrigin();
	else if(AfxMessageBox("Automatically find origin X,Y position?", MB_OKCANCEL)==IDOK)
		pMachine->FindOrigin(); //move to origin automatically
	return 0;
}

//---------------------------------------------------------------------------
void CPrinter::ExecuteOriginSequence()
//---------------------------------------------------------------------------
{
	//start a worker thread to execute a short sequence of immediate motions
	//these execute ahead of any queued motion.

	AfxBeginThread(OriginSeqProc,this);

}

//--------------------------------------------------------------------
void CPrinter::GotoSafe()
//--------------------------------------------------------------------
{// move printer head to safe position

	if(m_bSafeSet)
	{
		DWORD index = 0; //var to store index for completion check
		//determine where to go
		CVec safe = GetSafePos();
		double trav = GetClearance(false); //false to indicate possible collision
		//move down for safe traverse
		JogCarriageBy(CVec(0,0,-trav), false); //immediate, not queued
		Move(false, &index);
		WaitForMoveStart(index);
		WaitForMoveDone(index);
		//move to the safe position, xy first if safe z is higher
		CVec cur = GetCurrentPos(false);
		CString msg1, msg2;
		msg1.Format("GotoSafe(%0.2f,%0.2f,%0.2f)",safe.x,safe.y,safe.z);
		msg2.Format("CurRTPos:%0.2f,%0.2f,%0.2f", cur.x,cur.y,cur.z);
		Log(msg1,msg2);
		if(safe.z > cur.z)
		{
			//if safe z is higher than current, move xy first
			JogCarriageTo(CVec(safe.x, safe.y, cur.z), false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
			//now move the z
			JogCarriageTo(safe, false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
		}
		else
		{
			//move down first
			JogCarriageTo(CVec(cur.x, cur.y, safe.z), false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
			//now move the xy
			JogCarriageTo(safe, false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
		}
	}
	else
	{
		CString msg;
		msg.Format("Safe position not set");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	}
}

//---------------------------------------------------------------------------
UINT CPrinter::SafeSeqProc( LPVOID pParam )
//---------------------------------------------------------------------------
{
	//worker function for safe position search sequence
	CPrinter *pMachine = (CPrinter *)pParam;
	//if safe has already been set, then drive to limits
	//and reset that first position (for error correction)
	if(pMachine->IsSafeSet()) pMachine->FindSafePos();
	else if(AfxMessageBox("Automatically find safe position?", MB_OKCANCEL)==IDOK)
			pMachine->FindSafePos(); //try to automatically find the safe position
	return 0;
}

//---------------------------------------------------------------------------
void CPrinter::ExecuteSafeSequence()
//---------------------------------------------------------------------------
{
	//start a worker thread to execute a short sequence of immediate motions
	//these execute ahead of any queued motion.

	AfxBeginThread(SafeSeqProc,this);
}

//--------------------------------------------------------------------
void CPrinter::GotoLast()
//--------------------------------------------------------------------
{// move printer head to "last" position - e.g. last position prior to a pause

	if(m_bLastSet)
	{
		DWORD index = 0;
		//determine where to go
		CVec last = GetLastPos();
		double trav = GetClearance(false); //false to indicate possible collision
		////move down for safe traverse
		//JogCarriageBy(CVec(0,0,-trav), false); //immediate, not queued
		//Move(false, &index);
		//WaitForMoveStart(index);
		//WaitForMoveDone(index);
		//move to the last position, xy first if last z is higher than current z
		CVec cur = GetCurrentPos(false);
		CString msg1, msg2;
		msg1.Format("GotoLast(%0.2f,%0.2f,%0.2f)",last.x,last.y,last.z);
		msg2.Format("CurRTPos:%0.2f,%0.2f,%0.2f", cur.x,cur.y,cur.z);
		Log(msg1,msg2);
		if(last.z > cur.z)
		{
			//if last z is higher than current, move xy first
			JogCarriageTo(CVec(last.x, last.y, cur.z), false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
			//now move the z
			JogCarriageTo(last, false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
		}
		else
		{
			//move down first
			JogCarriageTo(CVec(cur.x, cur.y, last.z), false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
			//now move the xy
			JogCarriageTo(last, false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
		}
	}
	else
	{
		CString msg;
		msg.Format("Last return position not set");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	}
}

//--------------------------------------------------------------------
void CPrinter::GotoNext()
//--------------------------------------------------------------------
{// move printer head to the start of the next path

	if(pModel != NULL)
	{
		DWORD index = 0;
		double trav = GetClearance(false); //false to indicate possible collision
		//fetch the first vertex of the first path of the current layer
		CVec next = GetOrigin()+ModelToRobotTfm(pModel->fab.layer[pModel->fab.GetCurrentLayer()].region[0].path[0].v[0]);
		//adjust the z for the travel height
		next.z -= trav;
		//move down for safe traverse
		JogCarriageBy(CVec(0,0,-trav), false); //immediate, not queued
		Move(false, &index);
		WaitForMoveStart(index);
		WaitForMoveDone(index);
		
		//move to the last position, xy first if last z is higher than current z
		CVec cur = GetCurrentPos(false);
		if(next.z > cur.z)
		{
			//if next z is higher than current, move xy first
			JogCarriageTo(CVec(next.x, next.y, cur.z), false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
			//now move the z
			JogCarriageTo(next, false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
		}
		else
		{
			//move down first
			JogCarriageTo(CVec(cur.x, cur.y, next.z), false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
			//now move the xy
			JogCarriageTo(next, false); //immediate, not queued
			Move(false, &index);
			WaitForMoveStart(index);
			WaitForMoveDone(index);
		}
	}
	else
	{
		CString msg;
		msg.Format("Unable to return to next path");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	}
}

//---------------------------------------------------------------------------
UINT CPrinter::LastSeqProc( LPVOID pParam )
//---------------------------------------------------------------------------
{
	//worker function for 
	CPrinter *pMachine = (CPrinter *)pParam;
	pMachine->GotoLast();
	return 0;
}

//---------------------------------------------------------------------------
void CPrinter::ExecuteLastSequence()
//---------------------------------------------------------------------------
{
	//start a worker thread to execute a short sequence of immediate motions
	//these execute ahead of any queued motion.

	AfxBeginThread(LastSeqProc,this);

}

//---------------------------------------------------------------------------
UINT CPrinter::CalibrateSeqProc( LPVOID pParam )
//---------------------------------------------------------------------------
{
	//worker function for 
	CPrinter *pMachine = (CPrinter *)pParam;
	if (pMachine->FindHomePos())
		if (pMachine->FindSafePos())
			pMachine->FindOrigin();
	return 0;
}

//---------------------------------------------------------------------------
void CPrinter::ExecuteCalibrateSequence()
//---------------------------------------------------------------------------
{
	//start a worker thread to execute a short sequence of immediate motions
	//these execute ahead of any queued motion.

	AfxBeginThread(CalibrateSeqProc,this);

}

//--------------------------------------------------------------------
CVec CPrinter::GetOrigin()
//--------------------------------------------------------------------
{// return the build origin

	return m_vOrigin;
}

//--------------------------------------------------------------------
void CPrinter::SetOrigin(CVec org)
//--------------------------------------------------------------------
{
	// set the specified location as the origin, unless not specified
	//in which case, use the current location

	if( org != CVec(0,0,0) )
	{
		m_vOrigin = org;
	}
	else //set the current commanded position as the origin
	{
		m_vOrigin = GetCurrentPos();
	}
	//now set the point of deposition based on the current tool
	m_vPODOffset = GetCurTool()->tip - m_vPOD;
	m_vPOD = GetCurTool()->tip;
	m_bOriginSet = true;
	//init the last position to the origin
	SetLastPos(m_vOrigin);
}

//--------------------------------------------------------------------
CVec CPrinter::GetHomePos()
//--------------------------------------------------------------------
{// get the printer home position FOR GRAPHICS ONLY

	ASSERT(component.GetSize() == 4);
	if (component.GetSize() != 4)
		return CVec(0,0,0);

	CVec home;
	home.x = component[1].home;
	home.y = component[2].home;
	home.z = component[3].home;

	return home;
}

//--------------------------------------------------------------------
bool CPrinter::SetHomePos(CVec& pos)
//--------------------------------------------------------------------
{// set current position as the home
	//store it for use in keeping graphics displayed correctly
	//zero the hardware and software position registers
	//if hardware is initialized, don't set home until motion has ceased

	ASSERT(component.GetSize() == 4);
	if (component.GetSize() != 4)
		return false;
	
	//now clear the realtime and commanded position registers
	component[1].SetCMDPos(pos.x);
	component[1].SetRTPos(pos.x);
	component[1].ClearErrorOffset();
	component[2].SetCMDPos(pos.y);
	component[2].SetRTPos(pos.y);
	component[2].ClearErrorOffset();
	component[3].SetCMDPos(pos.z);
	component[3].SetRTPos(pos.z);
	component[3].ClearErrorOffset();

	m_bHomed = true;
	if(!bEmulateHardware)
		return (m_bHomed = HomeHW()); //tell printer it is home, clear position registers

	return true;
}

//--------------------------------------------------------------------
bool CPrinter::FindOrigin()
//--------------------------------------------------------------------
{
	//move to the X,Y coords of the origin,
	//ask the user to set the z coord manually
	if(!IsSafeSet() || !IsHomed())
	{
		((CFabAtHomeApp *)AfxGetApp())->Log("Please set the home and safe positions before setting the origin.");
		return false;
	}
	DWORD index = 0;
	m_vOrigin = CVec(100,100,50);
	JogCarriageTo(m_vOrigin,false);
	Move(false, &index);
	WaitForMoveStart(index);
	WaitForMoveDone(index);
	if(!InPosition()) return false;
	//now ask user to move build surface up to tool
	CString msg;
	msg.Format("Please ensure that %s is installed, then jog the build surface up until it contacts the tool tip, and hit Set Build Origin",
		GetCurToolName());
	((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	//AfxMessageBox(msg, MB_OK);
	return true;
}


//--------------------------------------------------------------------
bool CPrinter::FindHomePos()
//--------------------------------------------------------------------
{
	//if limit switches are configured (CanAutoRange() == true)
	//then seek the home limit switches
	//else tell user to jog manually to home
	if(bEmulateHardware)
	{
		JogCarriageTo(CVec(0,0,0),false);
		Move();
		if(SetHomePos())
		{
			((CFabAtHomeApp *)AfxGetApp())->Log("Hardware successfully homed.");
			return true;
		}
	}
	else
	{
		if(CanAutoRange())
		{
			DWORD index = 0;
			//TODO: unscramble the limit and motion directions
			//need the xfwd (-x_model), yfwd (-y_model), zbkd (+z_model) limits to be active at home
			//and remember active == 0

			if(IsHomed())
			{
				GotoHome();
				((CFabAtHomeApp *)AfxGetApp())->Log("Home position successfully reached.");
				return true;
			}

			JogCarriageBy(CVec(-1.1*m_ardMaxTravel[0],-1.1*m_ardMaxTravel[1],-1.1*m_ardMaxTravel[2]), false); 
			Move(false, &index); //immediate motion. full speed because we'll use limits to stop
			WaitForMoveStart(index);
			WaitForMoveDone(index); //wait for completion
			
			if(!GetLimit(AXIS_X,true) && !GetLimit(AXIS_Y,true) && !GetLimit(AXIS_Z,false))
			{
				//set the home position here to clear the position registers
				SetHomePos();
		
				CVec avePos;
				int i = 0;
				while( i < AVERAGE )
				{
					if( IsEStop() ) return false;

					if(!GetLimit(AXIS_X,true) && !GetLimit(AXIS_Y,true) && !GetLimit(AXIS_Z,false))
					{
						//we are now at the home position, so store it
						avePos += GetCurrentPos(false);
						i++;
					}
					//move off limits a small distance
					JogCarriageBy(CVec(1,1,1), false); 
					Move(false, &index); //immediate motion. full speed because we'll use limits to stop
					WaitForMoveStart(index);
					WaitForMoveDone(index); //wait for completion
					//move back into limits by slightly more distance to be sure to trigger
					JogCarriageBy(CVec(-2,-2,-2), false); 
					Move(false, &index); //immediate motion. full speed because we'll use limits to stop
					WaitForMoveStart(index);
					WaitForMoveDone(index); //wait for completion
				}
							
				//now calculate the average position of the limit trigger
				avePos /= (double)i;			

				//and set the home position to be the offset of our current real-time position from the average trigger point
				if(SetHomePos(GetCurrentPos(false)-avePos))
				{
					((CFabAtHomeApp *)AfxGetApp())->Log("Hardware successfully homed.");
					return true;
				}
			}
		}
		((CFabAtHomeApp *)AfxGetApp())->Log("Unable to home automatically. Please move to home position via jog controls, then <Set Home>.");
	}
	return false;
}

//--------------------------------------------------------------------
bool CPrinter::TrackError(CVec &pos)
//--------------------------------------------------------------------
{
	//track position error by comparing pos to calibrated safe position
	/*CString msg;
	msg.Format("TrackError(pos(%0.2f,%0.2f,%0.2f)-m_vSafePos(%0.2f,%0.2f,%0.2f))",
		pos.x,pos.y,pos.z,m_vSafePos.x,m_vSafePos.y,m_vSafePos.z);
	((CFabAtHomeApp *)AfxGetApp())->Log(msg);*/
	component[1].AccumulateErrorOffset(pos.x-m_vSafePos.x);
	component[2].AccumulateErrorOffset(pos.y-m_vSafePos.y);
	component[3].AccumulateErrorOffset(pos.z-m_vSafePos.z);
	return true;
}


//--------------------------------------------------------------------
bool CPrinter::FindSafePos(CVec firstSafe)
//--------------------------------------------------------------------
{
	//if limit switches are configured (CanAutoRange() == true, and system IsHomed
	//then seek the safe limit switches (front, right, bottom when facing front of machine)
	//else tell user to jog manually to a safe position
	//if firstSafe is non-zero, then set the safe position to the provided value
	CString msg;
	if(bEmulateHardware)
	{
		JogCarriageTo(CVec(m_ardMaxTravel[0],m_ardMaxTravel[1],0), false); 
		Move();
		if(!InPosition()) return false;
		if(SetSafePos(firstSafe))
		{

			if(firstSafe==CVec(0,0,0)) 
				((CFabAtHomeApp *)AfxGetApp())->Log("Safe position successfully found.");
			return true;
		}
	}
	else
	{
		if(!IsHomed())
		{
			msg.Format("Please home the system before trying to find the safe position");
		}
		else if(!CanAutoRange())
		{
			msg.Format("Unable to find safe position automatically. Please move to a safe position via jog controls, then <Set Safe Pos>.");
		}
		else 
		{
			DWORD index = 0;
			//TODO: unscramble the limit and motion directions
			//need the xbkd (+x_model), ybkd (+y_model), zbkd (+z_model) limits to be active at safe
			//and remember active == 0

			// Enable the ability to manually set the safe position
			if(IsSafeSet() && m_bSafeSetMan)
			{
				//Use GotoSafe because it moves down before moving over to protect parts from collision
				GotoSafe();
				((CFabAtHomeApp *)AfxGetApp())->Log("Safe position successfully reached.");
				return true;
				// move toward front, right, bottom a bit more (10% of travel) in case of lost steps
				//JogCarriageBy(CVec(0.25*m_ardMaxTravel[0],0.25*m_ardMaxTravel[1],-0.25*m_ardMaxTravel[2]), false); 
			}
			else
			{
				//move to front, right, bottom when facing machine front
				//ensure limit contact by moving a bit extra (x= 1.1*max travel, y= 1.1*max travel, z = -0.1*max travel)
				//JogCarriageTo(CVec(250,250,-200), false); 
				
				JogCarriageBy(CVec(1.1*m_ardMaxTravel[0],1.1*m_ardMaxTravel[1],-1.1*m_ardMaxTravel[2]), false); 
				Move(false, &index); //immediate motion. full speed because we'll use limits to stop
				WaitForMoveStart(index);
				WaitForMoveDone(index); //wait for completion
			}

				
				
				if(!GetLimit(AXIS_X,false) && !GetLimit(AXIS_Y,false) && !GetLimit(AXIS_Z,false))
				{
					CVec avePos;
					int i = 0;
					while( i < AVERAGE )
					{
						if( IsEStop() ) return false;

						if(!GetLimit(AXIS_X,false) && !GetLimit(AXIS_Y,false) && !GetLimit(AXIS_Z,false))
						{
							//we are now at the safe position, so store it
							avePos += GetCurrentPos(false);
							i++;
						}
						//move off limits a small distance
						JogCarriageBy(CVec(-1,-1,1), false); 
						Move(false, &index); //immediate motion. full speed because we'll use limits to stop
						WaitForMoveStart(index);
						WaitForMoveDone(index); //wait for completion
						//move back into limits by slightly more distance to be sure to trigger
						JogCarriageBy(CVec(5,5,-5), false); 
						Move(false, &index); //immediate motion. full speed because we'll use limits to stop
						WaitForMoveStart(index);
						WaitForMoveDone(index); //wait for completion
					}
								
					//now calculate the average position of the limit trigger
					avePos /= (double)i;
					//if the safe position has been set already via calibration, then only track error
					//otherwise set the safe position
					if(IsSafeSet())
					{
						TrackError(avePos);
						return true;
					}
					else
					{
						if(firstSafe==CVec(0,0,0))
							SetSafePos(avePos);
						else
							SetSafePos(firstSafe);
						((CFabAtHomeApp *)AfxGetApp())->Log("Safe Position Found.");
						return true;
					}
				}

			msg.Format("Unable to find safe position automatically.");
		}
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	}
	return false;
}

//--------------------------------------------------------------------
void CPrinter::Move(bool bQueue, DWORD *pIndex)
//--------------------------------------------------------------------
{
	//this overload is to allow calling with a default slowfactor
	//but still specifying bQueue and pIndex
	Move(-1, bQueue, pIndex);
}

//--------------------------------------------------------------------
void CPrinter::Move(double slowfactor, bool bQueue, DWORD *pIndex)
//--------------------------------------------------------------------
{ // move motors simultaneously by specified amounts

	CFabAtHomeApp *pApp = (CFabAtHomeApp *) AfxGetApp();
	if(slowfactor < 1) //default to m_dJogSpeed
		slowfactor = GetMaxPathSpeed()/GetJogSpeed();
	ASSERT(slowfactor >= 1);

	CSegment curSeg;

	// first 3 counters are for x,y,z - read control axis from component
	for(int i = 0; i<POSITION_AXES; i++)
	{
		curSeg.d[pApp->printer.component[i+1].axis] = 
			CUtils::Round(pApp->printer.component[i+1].stepstomove); //fir
		///////////////8-4-2006 Fixing Simultaneity////////////////////////////////////////
		pApp->printer.component[i+1].stepstomove = 0;
		///////////////8-4-2006 Fixing Simultaneity////////////////////////////////////////
	}

	// rest of counters are for tools
	//again, read the control axis (which amplifier) from the tool
	curSeg.d[GetCurTool()->axis] = (long)GetCurTool()->stepstomove;
	///////////////8-4-2006 Fixing Simultaneity////////////////////////////////////////
	GetCurTool()->stepstomove = 0;
	///////////////8-4-2006 Fixing Simultaneity////////////////////////////////////////

	//s2 needs to be even larger than 32bits, else overflow
	long long s2=0;
	for (int i=0; i<AXES_CNT; i++) {
		s2 += (long long)curSeg.d[i]*(long long)curSeg.d[i];
	}

	curSeg.s = CUtils::Round(sqrt((long double)s2)*slowfactor); // compute hypotenuse
	curSeg.L = curSeg.s;  //L == s
	curSeg.pIndex = pIndex;

	//if logging is on, log the command
	CString fun, bq;
	if(bQueue) bq = "true";
	else bq = "false";
	fun.Format("Move(%0.2f, %s)",slowfactor,bq);
	Log(fun,fun);
	//send the segment to the hardware or simulate it
	//record the index of the command
	
	if(bEmulateHardware)
		DoEmulatorStep(curSeg, bQueue, pIndex);
	else
		DoHardwareStep(curSeg, bQueue, pIndex);
}

/*
//--------------------------------------------------------------------
bool CPrinter::DoHardwareStep(CSegment &curSeg, bool bQueue, DWORD* pIndex)
//--------------------------------------------------------------------
{
	// move hardware (or emulate hardware motion)
	//if bQueue, then the command will be queued, and should
	//be based on commanded positions rather than "real-time"
	//to eliminate latency error

	// curSeg.d: array of motion signed deltas in stepping units
	// curSeg.s: pulse threshold (inversely proportional to speed)
	// curSeg.L: Number of times to loop
	// return false if error occured (abort requested), otherwise true.
	
	CFabAtHomeApp *pApp = (CFabAtHomeApp *) AfxGetApp();
	CSingleLock aryLock(&m_mutUpdate);
	long lastQueued = 0;
	
	if(!IsStarted() || IsEStop())
	{
		if(IsEStop())
		{
			if(IDNO == AfxMessageBox("Clear Emergency Stop, and resume motion?", MB_YESNO))
			{
				//if queue is not empty, make sure it is paused so that user does not
				//keep getting asked to enable
				//AbortBuild();
				pModel->fab.RequestAbort();
				return true; //user wants this condition, so good result;
			}
			else
				ClearEStop();
		}
	}
	
		
	if (curSeg.d[0]<3000 || curSeg.d[1]<3000 || curSeg.d[3] != 0 || curSeg.d[4] != 0 || !IsHomed())
	{ // no ramp for syringes deposition stepper motor
		if(!bEmulateHardware)
		{
			if(!IsStarted())
				Start(); //enable motion
			
			curSeg.d[component[1].axis] *= component[1].axisDir;
			curSeg.d[component[2].axis] *= component[2].axisDir;
			curSeg.d[component[3].axis] *= component[3].axisDir;
				
			curSeg.d[GetCurTool()->axis] *= GetCurTool()->axisDir;
			//don't forget to correct the status packets as well!
			///////////////////////////////////////////////////////////////////////
			
			
			aryLock.Lock();
			if(bQueue) //load segment into the m_pathArray buffer for transmission to uC
			{
				//make the m_pathArray thread safe; accessed by status thread and fab thread
				m_pathArray.Add(curSeg);
				//tell the worker thread to start moving path data to the uC
				m_bQPathDone = false;	
			}
			else if(!IMMSegment(curSeg, pIndex)) //send an immediate segment
				return false;
			aryLock.Unlock();
		} 
	}
	else
	{
		
		CSegment curSegOld = curSeg;
		double minslowfactor = GetMaxPathSpeed()/GetJogSpeed();
		double maxslowfactor = GetMaxPathSpeed()/MINSPEED;
		//long long s2=0;
		vector<int> ssf0,ssf1,ssf2; //step per slow factor for each motor
							
		//for (int i=0; i<AXES_CNT; i++)
		//	s2 += (long long)curSeg.d[i]*(long long)curSeg.d[i];
		
		int nsteps = CUtils::Round((GetJogSpeed()-MINSPEED)/STEPSPEED); // steps to accelerate					
		int astep0 = 0, astep1 = 0, astep2 = 0, astep3 = 0; // steps accumulated
		
		
		// stepper motor 0 - "X"
		for (int i = 0; i <= nsteps; i++)
		{	
			double area=(curSeg.d[0]/(2*nsteps))*(minslowfactor);
			ssf0.push_back(CUtils::Round((area*(i*STEPSPEED+MINSPEED))/GetMaxPathSpeed()));
			astep0 += ssf0[i];
		}

		// stepper motor 1 - "y"
		for (int i = 0; i <= nsteps; i++)
		{
			double area=(curSeg.d[1]/(2*nsteps))*(minslowfactor);
			ssf1.push_back(CUtils::Round((area*(i*STEPSPEED+MINSPEED))/GetMaxPathSpeed()));
			astep1 += ssf1[i];
		}

		// stepper motor 2 - "z"
		for (int i = 0; i <= nsteps; i++)
		{
			double area=(curSeg.d[2]/(2*nsteps))*(minslowfactor);
			ssf2.push_back(CUtils::Round((area*(i*STEPSPEED+MINSPEED))/GetMaxPathSpeed()));
			astep2 += ssf2[i];
		}

		// ramp up
		if(!IsStarted())
			Start(); //enable motion

		//pApp->printer.PauseQueue();

		bQueue = true;
		for (int i = 0; i <= nsteps ; i++)
		{
			double slowfactor=(GetMaxPathSpeed()/(i*STEPSPEED+MINSPEED));
			CSegment curSeg;
			curSeg.d[0]=ssf0[nsteps-i];
			curSeg.d[1]=ssf1[nsteps-i];
			curSeg.d[2]=ssf2[nsteps-i];

			long long s2=0;
			for (int j=0; j<AXES_CNT; j++)
				s2 += (long long)curSeg.d[j]*(long long)curSeg.d[j];
			
			curSeg.s = CUtils::Round(sqrt((long double)s2)*slowfactor); // compute hypotenuse
			curSeg.L = curSeg.s;  //L == s
			curSeg.pIndex = pIndex;
		
			if(!bEmulateHardware)
			{
								
				curSeg.d[component[1].axis] *= component[1].axisDir;
				curSeg.d[component[2].axis] *= component[2].axisDir;
				curSeg.d[component[3].axis] *= component[3].axisDir;
					
				curSeg.d[GetCurTool()->axis] *= GetCurTool()->axisDir;
				//don't forget to correct the status packets as well!
				///////////////////////////////////////////////////////////////////////
				
				
				aryLock.Lock();
				if(bQueue) //load segment into the m_pathArray buffer for transmission to uC
				{
					//make the m_pathArray thread safe; accessed by status thread and fab thread
					m_pathArray.Add(curSeg);
					//tell the worker thread to start moving path data to the uC
					m_bQPathDone = false;	
				}
				else if(!IMMSegment(curSeg, pIndex)) //send an immediate segment
					return false;
				aryLock.Unlock();
			}
		}



		// jogspeed
		if(!bEmulateHardware)
			{
				//if(!IsStarted())
				//	Start(); //enable motion
				CSegment curSeg;

				curSeg.d[0]=curSegOld.d[0]-2*astep0;
				curSeg.d[1]=curSegOld.d[1]-2*astep1;
				curSeg.d[2]=curSegOld.d[2]-2*astep2;

				long long s2=0;
				for (int i=0; i<AXES_CNT; i++)
					s2 += (long long)curSeg.d[i]*(long long)curSeg.d[i];

				curSeg.s = CUtils::Round(sqrt((long double)s2)*minslowfactor); // compute hypotenuse
				curSeg.L = curSeg.s;  //L == s
				curSeg.pIndex = pIndex;
				//double GetCarriageSpeed(); //return the current path-tangential speed of the carriage
				//bool SetJogSpeed(double spd); //set the jog speed for all non-build motions
				//double GetJogSpeed(){return m_dJogSpeed;};
				//double GetActualPathSpeed(); //return the current path tangential speed
				//double GetMaxPathSpeed(); //return the maximum path tangential speed
				
				curSeg.d[component[1].axis] *= component[1].axisDir;
				curSeg.d[component[2].axis] *= component[2].axisDir;
				curSeg.d[component[3].axis] *= component[3].axisDir;
					
				curSeg.d[GetCurTool()->axis] *= GetCurTool()->axisDir;
							
				aryLock.Lock();
				if(bQueue) //load segment into the m_pathArray buffer for transmission to uC
				{
					//make the m_pathArray thread safe; accessed by status thread and fab thread
					TRACE("Ramp max vel.:%d, path: %d  \n",curSeg.L,curSeg.d[0]);
					m_pathArray.Add(curSeg);
					//tell the worker thread to start moving path data to the uC
					m_bQPathDone = false;	
				}
				else if(!IMMSegment(curSeg, pIndex)) //send an immediate segment
					return false;
				aryLock.Unlock();
			}
			
		// ramp down
		for (int i = 0; i <= nsteps ; i++)
		{
			double slowfactor=(GetMaxPathSpeed()/((nsteps-i)*STEPSPEED+MINSPEED));
			CSegment curSeg;					
			curSeg.d[0]=ssf0[i];
			curSeg.d[1]=ssf1[i];
			curSeg.d[2]=ssf2[i];

			long long s2=0;
			for (int j=0; j<AXES_CNT; j++)
				s2 += (long long)curSeg.d[j]*(long long)curSeg.d[j];

			curSeg.s = CUtils::Round(sqrt((long double)s2)*slowfactor); // compute hypotenuse
			curSeg.L = curSeg.s;  //L == s
			curSeg.pIndex = pIndex;

			if(!bEmulateHardware)
			{
				//if(!IsStarted())
				//	Start(); //enable motion
				
				curSeg.d[component[1].axis] *= component[1].axisDir;
				curSeg.d[component[2].axis] *= component[2].axisDir;
				curSeg.d[component[3].axis] *= component[3].axisDir;
					
				curSeg.d[GetCurTool()->axis] *= GetCurTool()->axisDir;
				//don't forget to correct the status packets as well!
				///////////////////////////////////////////////////////////////////////
				
				aryLock.Lock();
				if(bQueue) //load segment into the m_pathArray buffer for transmission to uC
				{
					//make the m_pathArray thread safe; accessed by status thread and fab thread
					m_pathArray.Add(curSeg);
					//tell the worker thread to start moving path data to the uC
					m_bQPathDone = false;	
				}
				else if(!IMMSegment(curSeg, pIndex)) //send an immediate segment
					return false;
				aryLock.Unlock();
			} 
		}
	bQueue = false;
	}
	
	//do 
	//{	if (!IsQEmpty() && !IsMoving() && IsHomed())
	//	{
	//		pApp->printer.WaitForStatusUpdate(2);
	//		TRACE("Trying to restart queue...\n");
	//		pApp->printer.ResumeQueue();
	//		
	//	}	
	//}while(GetLastCmdExecuted() < (DWORD)(lastQueued=GetLastCmdQueued()));

	if (!IsQEmpty() && !IsMoving() && IsHomed())
		{
			pApp->printer.WaitForStatusUpdate(2);
			TRACE("Trying to restart queue...\n");
			pApp->printer.ResumeQueue();
			pApp->printer.WaitForMoveStart();
			
		}
		
	return true;
}	

*/

//--------------------------------------------------------------------
bool CPrinter::DoHardwareStep(CSegment &curSeg, bool bQueue, DWORD* pIndex)
//--------------------------------------------------------------------
{ // move hardware (or emulate hardware motion)
	//if bQueue, then the command will be queued, and should
	//be based on commanded positions rather than "real-time"
	//to eliminate latency error

  // curSeg.d: array of motion signed deltas in stepping units
  // curSeg.s: pulse threshold (inversely proportional to speed)
  // curSeg.L: Number of times to loop
  // return false if error occured (abort requested), otherwise true.

	CFabAtHomeApp *pApp = (CFabAtHomeApp *) AfxGetApp();
	CSingleLock aryLock(&m_mutUpdate);
	
	if(!IsStarted() || IsEStop())
	{
		if(IsEStop())
		{
			if(IDNO == AfxMessageBox("Clear Emergency Stop, and resume motion?", MB_YESNO))
			{
				//if queue is not empty, make sure it is paused so that user does not
				//keep getting asked to enable
				//AbortBuild();
				pModel->fab.RequestAbort();
				return true; //user wants this condition, so good result;
			}
			else
				ClearEStop();
		}
	}
	if(!bEmulateHardware)
	{
		if(!IsStarted())
			Start(); //enable motion
		
		// move real hardware here
		// component.curstep and tool.curstep updated
		// in GetStatus, running in a worker thread with some latency
		// when status is successfully returned, bNewStatus is set
		// the views can then be updated only when necessary
		
		////////////////////////////////////////////////////////////////////////
		//TODO: have firmware handle axes directions via configuration packet
		//need to accommodate the different orientations of the hardware axes
		//relative to the graphics here
		//for now - just change the signs of the d values appropriately
		curSeg.d[component[1].axis] *= component[1].axisDir;
		curSeg.d[component[2].axis] *= component[2].axisDir;
		curSeg.d[component[3].axis] *= component[3].axisDir;
			
		curSeg.d[GetCurTool()->axis] *= GetCurTool()->axisDir;
		//don't forget to correct the status packets as well!
		///////////////////////////////////////////////////////////////////////
		
		
		aryLock.Lock();
		if(bQueue) //load segment into the m_pathArray buffer for transmission to uC
		{
			//make the m_pathArray thread safe; accessed by status thread and fab thread
			m_pathArray.Add(curSeg);
			//tell the worker thread to start moving path data to the uC
			m_bQPathDone = false;	
		}
		else if(!IMMSegment(curSeg, pIndex)) //send an immediate segment
			return false;
		aryLock.Unlock();
	} 
	return true;
}

//--------------------------------------------------------------------
bool CPrinter::DoEmulatorStep(CSegment &curSeg, bool bQueue, DWORD* pIndex)
//--------------------------------------------------------------------
{ // emulate hardware motion)
	//if bQueue, then the command will be queued, and should
	//be based on commanded positions rather than "real-time"
	//to eliminate latency error

  // curSeg.d: array of motion signed deltas in stepping units
  // curSeg.s: pulse threshold (inversely proportional to speed)
  // curSeg.L: Number of times to loop
  // return false if error occured (abort requested), otherwise true.

	CFabAtHomeApp *pApp = (CFabAtHomeApp *) AfxGetApp();
	int i;
	
	if(!IsStarted() || IsEStop())
	{
		if(IsEStop())
		{
			if(IDNO == AfxMessageBox("Clear Emergency Stop, and resume motion?", MB_YESNO))
			{
				//if queue is not empty, make sure it is paused so that user does not
				//keep getting asked to enable
				pModel->fab.RequestAbort();

				return true; //user wants this condition, so good result;
			}
			else
				ClearEStop();
		}
	}
	// Emulate hardware
	unsigned int c[AXES_CNT]; // counters
	double h[AXES_CNT];
	for (i=0; i<AXES_CNT; i++)
	{
		c[i]=0;
		if (curSeg.d[i]>0)
		{
			h[i] = 1.0;
		}
		else
		{
			h[i] = -1.0;
		}
		curSeg.d[i] = abs(curSeg.d[i]);
	}
	for (unsigned int j=0; j<=curSeg.L; j++)
	{
		for (i=0; i<AXES_CNT; i++)
		{
			c[i] += curSeg.d[i];
			if (c[i] > curSeg.s)
			{
				c[i] -= curSeg.s;
				if (i<3)
				{ 
					component[i+1].SetRTPos(component[i+1].GetRTPos()+h[i]*component[i+1].mmps);
					// emulate carriage hardware limit switches (if exist)
					if (component[i+1].GetRTPos()<component[i+1].rangemin) 
					{
						component[i+1].SetRTPos(component[i+1].rangemin);
						//MessageBeep(MB_ICONHAND);
					}
					if (component[i+1].GetRTPos()>component[i+1].rangemax) 
					{
						component[i+1].SetRTPos(component[i+1].rangemax);
						//MessageBeep(MB_ICONHAND);
					}
				} 
				else
				{
					GetCurTool()->curstep+=h[i]*m_dEmulatorSlowdown;
					// emulate tool hardware limit switches (if exist)
					if (GetCurTool()->curstep*GetCurTool()->mmps<GetCurTool()->rangemin)
					{
						GetCurTool()->curstep=GetCurTool()->rangemin/GetCurTool()->mmps;
						MessageBeep(MB_ICONHAND);
					}
					if (GetCurTool()->curstep*GetCurTool()->mmps>GetCurTool()->rangemax)
					{
						GetCurTool()->curstep=GetCurTool()->rangemax/GetCurTool()->mmps;
						MessageBeep(MB_ICONHAND);
					}
					//collect trace points while depositing
					if(pModel != NULL)
					{
						CVec X;
						X.x = component[1].GetRTPos();
						X.y = component[2].GetRTPos();
						X.z = component[3].GetRTPos();
						pModel->TracePoint(ModelToRobotTfm(X-m_vOrigin));
					}
				}
			}
			if(IsEStop()) return false;
		}
		//tell everyone that the graphics need updating
		if(j%(int)(5000.0/m_dEmulatorSlowdown) == 0)
			AfxGetMainWnd()->Invalidate();
	}
	return true;
}

//--------------------------------------------------------------------
bool CPrinter::EmulateSlower()
//--------------------------------------------------------------------
{
	//speed up the emulation rate
	if(m_dEmulatorSlowdown < 1000)
	{
		m_dEmulatorSlowdown*=1.1;
		return true;
	}
	return false;
}

//--------------------------------------------------------------------
bool CPrinter::EmulateFaster()
//--------------------------------------------------------------------
{
	//slow down the emulation rate
	if(m_dEmulatorSlowdown > 0)
	{
		m_dEmulatorSlowdown/=1.1;
		return true;
	}
	return false;
}

//--------------------------------------------------------------------
double CPrinter::GetCarriageSpeed()
//--------------------------------------------------------------------
{
	//return the current path-tangential speed of the carriage
	CSingleLock updateLock(&m_mutUpdate);
	if(!updateLock.Lock((DWORD)(2*GetTargetStatusPeriod())))
	{
		//have lock timeout
		return false;
	}
	double vi, speed=0.0;
	for(int i = 1; i<=POSITION_AXES; i++)
	{
		vi=component[i].GetVel();
		speed+=vi*vi;
	}


	//TRACE("Speed^2: %f\n", speed);
	return sqrt(speed);
}

//--------------------------------------------------------------------
bool CPrinter::IsMoving()
//--------------------------------------------------------------------
{
	//check whether hardware "MOVING" flag is set
	//or return immediately if simulating
	if(bEmulateHardware) return (GetCarriageSpeed()>0.0);
	return (m_stateFlags.MOVING && (GetCarriageSpeed()>0.0));
}

//--------------------------------------------------------------------
bool CPrinter::IsToolMoving()
//--------------------------------------------------------------------
{
	//check whether hardware "MOVING" flag is set
	//or return immediately if simulating
	if(bEmulateHardware) return (false);
	return (m_bToolMoving);
}

//--------------------------------------------------------------------
bool CPrinter::WaitForMoveDone(long index, int timeout_ms)
//--------------------------------------------------------------------
{
	//sleep until the hardware reports completion of the indexed command
	//or wait for hardware MOVING flag to be false if index not valid
	//or return immediately if simulating
	//returns false if the commanded move is reported as done or motion has stopped, but not InPosition
	//TODO: make the firmware handle the MOVING flag more carefully to prevent false reporting
	
	if (m_dwTGTStatusPeriod < STATUS_UPDATE_PERIOD)
	{
		((CFabAtHomeApp *)AfxGetApp())->Log("Could not control the printer movement, please increase Status Update Period.");
		return false;
	}
	

	if(bEmulateHardware) return true;

	if(index < 0)
	{
		while( (timeout_ms > 0) && (IsMoving() || IsToolMoving()))
		{
			Sleep(SLEEP_PERIOD);
			if(!IsMoving() && !IsToolMoving())
			{
				timeout_ms -= SLEEP_PERIOD;
			}
		}
	}
	else
	{
		//wait for confirmation from the micro that the indexed command has been completed
		//but also include a timeout and a check for motion having stopped
		while( ((GetLastCmdExecuted() < (DWORD)index) || IsMoving() || IsToolMoving()) && (timeout_ms > 0))
		{
			Sleep(SLEEP_PERIOD);
			if(!IsMoving() && !IsToolMoving())
			{
				timeout_ms -= SLEEP_PERIOD;
			}
		}
	}
	return InPosition();
}

//--------------------------------------------------------------------
bool CPrinter::WaitForMoveStart(long index, int timeout_ms)
//--------------------------------------------------------------------
{
	//sleep until the hardware reports that the indexed command is being executed
	//or wait for hardware MOVING flag to be true if index not valid
	//or return immediately if simulating

	
	if(bEmulateHardware) return true;

	if(index < 0)
	{
			while((!IsMoving() || !IsToolMoving()) && (timeout_ms > 0))
		{
			Sleep(SLEEP_PERIOD);
			timeout_ms -= SLEEP_PERIOD;
		}
		if(timeout_ms <= 0)
			return false;
	}
	else
	{
		while( (GetCurCommand() < (DWORD)index) && (timeout_ms > 0) )
		{
			Sleep(SLEEP_PERIOD);
			timeout_ms -= SLEEP_PERIOD;
		}
		if(timeout_ms <= 0)
			return false;
	}

	return true;
}

//--------------------------------------------------------------------
void CPrinter::WaitForStatusUpdate(int nPeriods)
//--------------------------------------------------------------------
{
	//wait for status update thread to update the status info
	DWORD timeout = nPeriods * m_dwTGTStatusPeriod;
	while(timeout > 0)
	{
		Sleep(m_dwTGTStatusPeriod);
		timeout-=m_dwTGTStatusPeriod;
	}
}

//--------------------------------------------------------------------
bool CPrinter::CleanupBuild(void)
//--------------------------------------------------------------------
{
	//clean up variables and system state after successful build
	if(pModel!=NULL)
	{
		if(pModel->fab.IsFabricating())
			pModel->fab.RequestAbort();
	}
	//now stop sending commands 
	if(!m_bQPathDone)
		m_bQPathDone = true; //this will stop the queueing thread from sending any more segments

	//and empty the path array
	m_pathArray.RemoveAll();
	//zero out the path index counter
	m_nPathIndex = 0;

	//make sure the queue is empty
	if(!IsQEmpty()) Abort();
	WaitForStatusUpdate();
	//and clear any aborts
	if(IsAborted()) Abort();
	
	//success
	return true;
}



//--------------------------------------------------------------------
bool CPrinter::PauseBuild(bool bFindSafe, bool bNoSuckback)
//--------------------------------------------------------------------
{
	//pause the fabrication process - pause queue
	//unless bNoSuckback, also move to safe position and suckback

	CString msg1;
	msg1.Format("PauseBuild(%d,%d)",bFindSafe, bNoSuckback);
	Log(msg1,msg1);

	pModel->fab.RequestPause();

	//now queue & motion should be stopped
	//so figure out where to return to
	WaitForStatusUpdate();
	SetLastPos(); //sets current RT position as the last position

	if(!bNoSuckback)
	{
		Suckback();
	}
	if(bFindSafe)
	{
		FindSafePos();
	}
	return true;
}

//--------------------------------------------------------------------
bool CPrinter::ResumeBuild(bool bToolChange, bool bNoPushout)
//--------------------------------------------------------------------
{
	//resume the fabrication process - move back to last position, pushout, resume queue

	CString msg1;
	msg1.Format("ResumeBuild(%d,%d)",bToolChange, bNoPushout);
	Log(msg1,msg1);

	if(bToolChange)
		GotoNext(); //move to the start of the next path point
	else
		GotoLast(); //move back to the last position
	WaitForMoveDone();

	if(!bNoPushout)
	{
		Pushout();
	}

	//resume the fabrication thread
	pModel->fab.RequestResume();
	return true;
}

//--------------------------------------------------------------------
bool CPrinter::AbortBuild()
//--------------------------------------------------------------------
{
	//emergency stop and abort the build underway
	//this includes flushing the uC queue, and throwing out the
	//paths generated by the process planner

	//tell the fabrication process to abort
	int timeout = 100;
	if(pModel!=NULL)
	{
		if(pModel->fab.IsFabricating())
			pModel->fab.RequestAbort();
	}
	//now stop sending commands 
	m_bQPathDone = true; //this will stop the queueing thread from sending any more segments

	//and empty the path array
	m_pathArray.RemoveAll();
	//zero out the path index counter
	m_nPathIndex = 0;
	//aryLock.Unlock();

	//emergency stop all motion
	//and empty the queue by aborting
	if(bHardwareInitialized && !IsAborted())
	{
		Stop();
		if(!Abort())return false;
		//now clear the abort
		if(IsAborted()) return Abort();
	}
	//success
	return true;
}


//--------------------------------------------------------------------
bool CPrinter::IsDefined(void)
//--------------------------------------------------------------------
{ // return true if printer components are defined

	m_bDefined = (component.GetSize()==4);
	return (m_bDefined);
}

//--------------------------------------------------------------------
bool CPrinter::InitializeHardware(void)
//--------------------------------------------------------------------
{// Initialize hardware comm and start comm thread
	
	//start by opening/refreshing the com port
	if(IsChannelOpen())
	{
		CloseChannel();
	}
	if(!OpenChannel(false)) //try to autofind the port
		if(!OpenChannel(true))	//ask user to select it
		{
			bHardwareInitialized = false; //failed
			return bHardwareInitialized;
		}

	//now try to initialize the microcontroller motion control subsystem
	if(!Reset()) //send a reset packet to the machine
	{
		bHardwareInitialized = false; 
		return bHardwareInitialized;
	}

	//attempt to send configuration data to the microcontroller
	if(!Configure())
	{
		//if configuration fails - probably communication error
		bHardwareInitialized = false; 
		return bHardwareInitialized;
	}

	//now start the status collection thread to collect status info
	if(!CollectStatus(true))
	{	
		bHardwareInitialized = false; 
		return bHardwareInitialized;
	}

	//reset the comms status
	m_dCommsErrorRate = 0.0;
	m_dwCMDStatusPeriod = GetUserStatusPeriod(); 
	m_dwTGTStatusPeriod = GetUserStatusPeriod();
	m_dwACTStatusPeriod = 0;
	m_nPeriodCalcStep = 0;
	m_dwMachineElapsedTime_ms = 0;
	m_ctsIdleTime = 0; 
	m_ctIdleStart = 0;
	m_bEStop = false;
	//we should be ready to go now
	bHardwareInitialized = true;
	
	return bHardwareInitialized;
}

//--------------------------------------------------------------------
bool CPrinter::ShutdownHardware(void)
//--------------------------------------------------------------------
{// terminate status thread, reset micro, close USB channel

	//try to stop the status collection thread
	if(CollectStatus(false))
	{
		//try to reinitialize the microcontroller motion control subsystem
		Reset();
	}
	//no matter what, try to shut down the channel
	if(CloseChannel())
	{
		bHardwareInitialized = false;
		return true;
	}
	return false;
}


//---------------------------------------------------------------------------
bool CPrinter::MountTool(CString &toolName)
//---------------------------------------------------------------------------
{
	//set the named tool as mounted, true if successful
	int idx = CTool::SearchByName(toolName);
	if(idx < 0) return false;
	
	bool mounted = CTool::Mount(toolName);

	//set the last tool mounted as active
	return (mounted && SetCurTool(toolName));
}

//---------------------------------------------------------------------------
bool CPrinter::UnmountTool(CString &toolName)
//---------------------------------------------------------------------------
{
	//set the named tool as unmounted, true if successful
	int idx = CTool::SearchByName(toolName);
	if(idx < 0) return false;
	//if this was the active tool
	if(m_sCurTool.CompareNoCase(toolName) == 0)
	{
		//if there were one or fewer mounted tools
		if(CTool::MountedToolCount() <= 1)
		{
			SetCurTool("Undefined");
			return CTool::Unmount(toolName);
		}
		else
		{
			//set the current tool to the next mounted tool
			CString next = CTool::FindNextMounted(toolName);
			SetCurTool(next);
		}
	}
	//finally unmount the tool
	return CTool::Unmount(toolName);
}

//---------------------------------------------------------------------------
bool CPrinter::ChangePOD()
//---------------------------------------------------------------------------
{
	//change the current point of deposition to compensate for offsets of
	//multiple tools
	//subtract the old POD from the new to get offset
	//store the new POD
	m_vPODOffset = GetCurTool()->tip - m_vPOD;
	m_vPOD = GetCurTool()->tip;
	//now offset the "last" and "origin" positions with the new offset
	m_vLastPos = m_vLastPos-m_vPODOffset;
	m_vOrigin = m_vOrigin-m_vPODOffset;
	CString msg1, msg2;
	msg1.Format("ChangePOD");
	msg2.Format("PODOffs(%0.2f,%0.2f,%0.2f), pod(%0.2f,%0.2f,%0.2f), m_vLastPos(%0.2f,%0.2f,%0.2f), m_vOrigin(%0.2f,%0.2f,%0.2f)",
		m_vPODOffset.x,m_vPODOffset.y,m_vPODOffset.z,
		m_vPOD.x,m_vPOD.y,m_vPOD.z,
		m_vLastPos.x,m_vLastPos.y,m_vLastPos.z,
		m_vOrigin.x,m_vOrigin.y,m_vOrigin.z);
	Log(msg1,msg2);
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::FindToolToRemove(CString& newToolName, CString& removeTool)
//---------------------------------------------------------------------------
{
	//find name of tool which should be removed to minimize swaps
	//pass back through removeTool; return true if a tool needs to be removed
	if(GetMaxTools() < 2)
	{
		removeTool = m_sCurTool;
		return true;
	}
	//for now, just make sure we don't remove the next tool needed
	//TODO: do proper optimization for arbitrary number of tools
	else
	{
		int newAxis = CTool::GetByName(newToolName)->axis;
		for(int i = 0; i < pApp->tool.GetSize(); i++)
		{
			//if a mounted tool is using the same axis as the new tool, then remove it
			if(pApp->tool[i].IsMounted() && (pApp->tool[i].axis == newAxis))
			{
				removeTool = pApp->tool[i].GetName();
				return true;
			}
		}
	}
	//if no mounted tool is using the same axis, then no tool needs to be removed.
	removeTool = "";
	return false;
}

//---------------------------------------------------------------------------
bool CPrinter::SetCurTool(CString newToolName, CString newMatName)
//---------------------------------------------------------------------------
{
	//change the currently active tool
	//if the tool is already mounted (e.g. multiple syringe tool)
	//then just update variables; else ask user to mount

	//if newMatName not specified, just keep the old one
	if(newMatName.CompareNoCase("")==0)
	{
		newMatName = GetCurMatName();
	}
	//if the tool name is undefined, just change the name and return
	//this should only be temporary; don't change POD yet
	if(newToolName.CompareNoCase("Undefined")==0)
	{
		m_sCurTool = newToolName;
		m_sCurMaterial = newMatName;
		return true;
	}

	EnsureMountedTool(newToolName);

	if((newToolName.CompareNoCase(m_sCurTool) == 0) && 
		(newMatName.CompareNoCase(m_sCurMaterial) == 0) &&
		GetCurTool()->IsMounted()) return true;

	
	//tool is loaded and mounted and not already current
	m_sCurTool = newToolName;
	m_sCurMaterial = newMatName;
	//note that the view contents have changed
	bNewStatus = true;
	//change point of deposition
	return ChangePOD();
}

//---------------------------------------------------------------------------
bool CPrinter::ChangeTool(CString newToolName, CString newMatName)
//---------------------------------------------------------------------------
{
	//if multitool, and new tool is already mounted, 
	//switch automatically if bPauseAtChange;
	//if new tool needs to be manually mounted first,
	//move to safe position, ask user to change the tool/material
	//remain paused until user resumes build

	CString msg;
	//if newMatName not specified, just keep the old one
	if(newMatName.CompareNoCase("")==0)
	{
		newMatName = GetCurMatName();
	}

	if((newToolName.CompareNoCase(m_sCurTool) == 0) && 
		(newMatName.CompareNoCase(m_sCurMaterial) == 0) &&
		GetCurTool()->IsMounted()) return true;

	//check that the new tool and material are present in the arrays
	EnsureLoadedTool(newToolName);

	//TODO: add material capability back in
	/*if( (CMaterial::SearchByName(newMatName) < 0) )
	{
		msg.Format("Cannot find material %s", newMatName);
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}*/

	//Grab the current position as the place to return to, and pause the queue
	if(IsFabricating())
	{
		if(!PauseBuild(false,true))
			((CFabAtHomeApp *)AfxGetApp())->Log("PauseBuild failed");

		
		//if new tool isn't already mounted (e.g. multi-syringe tool)
		//of if user wants pause, or configuration is single tool
		if(!CTool::GetByName(newToolName)->IsMounted() || GetPauseAtToolChange())
		{
			//move to safe position and ask user to swap out or remind to resume
			FindSafePos(m_vSafePos);

			if(!CTool::GetByName(newToolName)->IsMounted())
			{
				//if the configuration supports multiple tools, figure out which tool to remove
				//to minimize number of swaps
				CString removeTool;
				if(FindToolToRemove(newToolName, removeTool))
				{
					//need to remove a tool
					msg.Format("Please replace %s with\n%s,then resume build (Fabrication->Resume Printing).",
						removeTool, newToolName);
				}
				else
				{
					//only need to mount a tool
					msg.Format("Please mount %s, then resume build (Fabrication->Resume Printing).",
						newToolName);
				}
				((CFabAtHomeApp *)AfxGetApp())->Log(msg);
				if(AfxMessageBox(msg, MB_OKCANCEL) != IDOK)
				{
					msg.Format("Aborted tool change: aborting build.");
					((CFabAtHomeApp *)AfxGetApp())->Log(msg);
					return(AbortBuild());
				}
				//bring up the tool change dialog
				pApp->UserToolChange();
			}
			else //tool already mounted, but user wanted pause
			{
				((CFabAtHomeApp *)AfxGetApp())->Log("Please hit Fabrication->Resume Printing when ready to continue");
			}
			//now while a pause is requested
			while(pModel->fab.PauseRequested())
				Sleep(100);
		}
		SetCurTool(newToolName, newMatName);
		//now resume the build process
		if(!ResumeBuild(true, true))
		{
			((CFabAtHomeApp *)AfxGetApp())->Log("ResumeBuild failed");
			return false;
		}
		else
			return true;
	}
	//not fabricating, so just change the tool
	return SetCurTool(newToolName, newMatName);
}

//---------------------------------------------------------------------------
bool CPrinter::OpenChannel( bool isManual )
//---------------------------------------------------------------------------
{
	//open up a communications channel to the machine
	//ask user via dialog if isManual, else find automatically
	if( isManual )
	{
		return m_channel.DoDialog();
	}
	else
	{
		return m_channel.AutoFindPort();
	}
}

//---------------------------------------------------------------------------
bool CPrinter::CloseChannel()
//---------------------------------------------------------------------------
{
	//disconnect from the communications channel
	//kill the status thread
	if(!IsChannelOpen()) return bEmulateHardware;
	m_bCollectStatus = false;
	return m_channel.Disconnect();
}

//---------------------------------------------------------------------------
bool CPrinter::Start(void)
//---------------------------------------------------------------------------
{
	//tell the hardware to enable/disable motion
	//note that start toggles

	if(!bHardwareInitialized) return bEmulateHardware;
	CSingleLock aryLock(&m_mutUpdate);
	aryLock.Lock();
	CStartPacket pkt;
	if(!pkt.InitPacket()) return false;
	CString msg;
	int i = 0;
	//send out the Start command; try a few times if necessary
	while( !m_channel.Send(&pkt) && (i < RETRIES) )
	{
		i++;
		Sleep(RETRY_DLY);
	}
	if(i == RETRIES)
	{	
		msg.Format("CPrinter::Start: timed out sending");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}
	m_bEnableRequested = !m_bEnableRequested;
	
	return true;
}

//---------------------------------------------------------------------------
void CPrinter::SetEStop()
//---------------------------------------------------------------------------
{
	//set the EStop flag
	m_bEStop = true;
}

//---------------------------------------------------------------------------
void CPrinter::ClearEStop()
//---------------------------------------------------------------------------
{
	//clear the EStop flag, and any aborts
	if(!bEmulateHardware)
		if(IsAborted())
			Abort();
	m_bEStop = false;
}

//---------------------------------------------------------------------------
bool CPrinter::Stop(void)
//---------------------------------------------------------------------------
{
	//stop motion (terminate current command)
	if(bEmulateHardware || !IsStarted())
	{
		SetEStop();
		return true;
	}

	Abort();
	SetEStop(); //set E stop flag
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::PauseQueue(void)
//---------------------------------------------------------------------------
{
	//pause at current position in segment queue
	if(!bHardwareInitialized) return bEmulateHardware;

	CPausePacket pkt;
	if(!pkt.InitPacket()) return false;
	CString msg;
	int i = 0;
	//send out the Pause command; try a few times if necessary
	while( !m_channel.Send(&pkt) && (i < RETRIES) )
	{
		i++;
		Sleep(RETRY_DLY);
	}
	if(i == RETRIES)
	{	
		msg.Format("CPrinter::Start: timed out sending");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::ResumeQueue(void)
//---------------------------------------------------------------------------
{
	//resume at next position in seqment queue
	if(!bHardwareInitialized) return bEmulateHardware;

	CResumePacket pkt;
	if(!pkt.InitPacket()) return false;
	CString msg;
	int i = 0;
	//send out the Resume command; try a few times if necessary
	while( !m_channel.Send(&pkt) && (i < RETRIES) )
	{
		i++;
		Sleep(RETRY_DLY);
	}
	if(i == RETRIES)
	{	
		msg.Format("CPrinter::Start: timed out sending");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::Abort(void)
//---------------------------------------------------------------------------
{
	//stop all motion, flush the segment queue
	if(!bHardwareInitialized) return bEmulateHardware;

	CAbortPacket pkt;
	if(!pkt.InitPacket()) return false;
	CString msg;
	int i = 0;
	//send out the Abort command; try a few times if necessary
	while( !m_channel.Send(&pkt) && (i < RETRIES) )
	{
		i++;
		Sleep(RETRY_DLY);
	}
	if(i == RETRIES)
	{	
		msg.Format("CPrinter::Start: timed out sending");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::ClearError(void)
//---------------------------------------------------------------------------
{
	//try to clear error condition
	return false;
}

//---------------------------------------------------------------------------
bool CPrinter::Reset(void)
//---------------------------------------------------------------------------
{
	//hard reset of microcontroller
	if(!IsChannelOpen()) return bEmulateHardware;

	CResetPacket pkt;
	if(!pkt.InitPacket()) return false;
	CString msg;
	int i = 0;
	//send out the Reset command; try a few times if necessary
	while( !m_channel.Send(&pkt) && (i < RETRIES) )
	{
		i++;
		Sleep(RETRY_DLY);
	}
	if(i == RETRIES)
	{	
		msg.Format("CPrinter::Start: timed out sending");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}
	//reset the PC elapsed time counter as well
	m_bFirstPacket = true;
	//variables that needs to be reseted when microcontroller is reseted | CTI - BRAZIL
	m_bSafeSet = false;
	m_bSafeSetMan = false;
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::HomeHW(void)
//---------------------------------------------------------------------------
{
	//declare current location as home; reset global positions
	if(!IsChannelOpen()) return bEmulateHardware;

	CHomePacket pkt;
	if(!pkt.InitPacket()) return false;
	CString msg;
	int i = 0;
	//send out the Home command; try a few times if necessary
	while( !m_channel.Send(&pkt) && (i < RETRIES) )
	{
		i++;
		Sleep(RETRY_DLY);
	}
	if(i == RETRIES)
	{	
		msg.Format("CPrinter::Start: timed out sending");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::QueuePath( void )
//---------------------------------------------------------------------------
{
	//handle queuing a single path
	//return the array index of the next segment
	//to be sent - respects the queue capacity on the uC
	//the user should write new path data to m_pathArray
	//set m_nPathIndex to indicate the first segment to send
	//and then set m_bQPathDone to false to start the fn

	//VERY COMPLICATED AND COUPLED: BE CAREFUL WITH THIS

	//if the hardware is not running, then fail
	if(!bHardwareInitialized) return bEmulateHardware;

	//check validity of arguments

	//if the path is already done, then no new path to send
	if(m_bQPathDone) return true;

	//make the m_pathArray thread safe; accessed by status thread and fab thread
	CSingleLock aryLock(&m_mutUpdate);
	aryLock.Lock();
	if((m_nPathIndex < 0) || (m_nPathIndex > m_pathArray.GetSize())) 
	{
		//some index error
		return false; 
	}

	//check the queue space - remember that it may not
	//update while this function is running, so need to calculate
	int qAvail = GetQSpace();
	TRACE("QueuePath: m_nPathIndex %d, pathSize %d, qAvail %d\n", m_nPathIndex, m_pathArray.GetSize(), qAvail);
	qAvail += m_nPathIndex; //indicate relative queue remaining
	CSegmentPacket segPkt;
	int cnt = 0;
	for(int i = m_nPathIndex; (i<m_pathArray.GetSize())&&(i<qAvail); i++)
	{
		if(!segPkt.InitPacket(m_pathArray[i]))
			return false;
		CString msg;
		int timer = 0;
		//send out the request for status; try a few times if necessary
		while( !m_channel.Send(&segPkt) && (timer < RETRIES) )
		{
			timer++;
			Sleep(RETRY_DLY);
		}
		if(timer == RETRIES)
		{	
			msg.Format("CPrinter::QueuePath: timed out sending segment");
			((CFabAtHomeApp *)AfxGetApp())->Log(msg);
			return false;
		}
		//successfully sent a packet, so increment m_nPathIndex
		m_nPathIndex++;
		//get the segment index for completion tracking
		m_dwQueuePathIndex = segPkt.GetIndex();
		if(m_pathArray[i].pIndex != NULL)
			*(m_pathArray[i].pIndex) = m_dwQueuePathIndex;
		//debugging
		cnt++;
		TRACE("QSegment#%d:d(%d,%d,%d,%d),s:%d, L:%d\n",
			m_dwQueuePathIndex,m_pathArray[i].d[0],m_pathArray[i].d[1],m_pathArray[i].d[2],
			m_pathArray[i].d[GetCurTool()->axis],m_pathArray[i].s,m_pathArray[i].L);
	}
	//if we have sent the whole array, then we are done
	m_bQPathDone = (m_nPathIndex == m_pathArray.GetSize());
	TRACE("QueuePath: qAvail %d, sent %d\n",qAvail-m_nPathIndex, cnt);
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::IMMSegment( CSegment &curSeg, DWORD* pIndex )
//---------------------------------------------------------------------------
{
	//execute a single segment move immediately
	//return the packet index via *index
	if(!bHardwareInitialized) return bEmulateHardware;

	CIMMSegmentPacket segPkt;
	if(!segPkt.InitPacket(curSeg))
		return false;
	CString msg;
	int timer = 0;
	//send out the request for status; try a few times if necessary
	while( !m_channel.Send(&segPkt) && (timer < RETRIES) )
	{
		timer++;
		Sleep(RETRY_DLY);
	}
	if(timer == RETRIES)
	{	
		msg.Format("CPrinter::IMMSegment: timed out sending segment");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}
	//if a valid index pointer has been provided, return the index of the command sent
	if(pIndex != NULL)
		*pIndex = segPkt.GetIndex();

	TRACE("IMMSegment#%d:d(%d,%d,%d,%d),s:%d, L:%d\n",
		segPkt.GetIndex(),curSeg.d[0],curSeg.d[1],curSeg.d[2],curSeg.d[GetCurTool()->axis],curSeg.s,curSeg.L);
	return true;
}
//---------------------------------------------------------------------------
bool CPrinter::IMMDIO( CDIO &curDIO, DWORD* pIndex )
//---------------------------------------------------------------------------
{
	//execute a single segment move immediately
	//return the packet index via *index
	if(!bHardwareInitialized) return bEmulateHardware;

	CIMMDIOPacket dioPkt;
	if(!dioPkt.InitPacket(curDIO))
		return false;
	CString msg;
	int timer = 0;
	//send out the request for status; try a few times if necessary
	while( !m_channel.Send(&dioPkt) && (timer < RETRIES) )
	{
		timer++;
		Sleep(RETRY_DLY);
	}
	msg.Format("CPrinter::IMMDIO: finished while loop");
	((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	if(timer == RETRIES)
	{	
		msg.Format("CPrinter::IMMDIO: timed out sending segment");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}
	//if a valid index pointer has been provided, return the index of the command sent
	if(pIndex != NULL)
		*pIndex = dioPkt.GetIndex();

//	TRACE("IMMDIO#%d:d(%d,%d,%d,%d),s:%d, L:%d\n",
//		dioPkt.GetIndex(),curDIO.d[0],curDIO.d[1],curDIO.d[2],curDIO.d[GetCurTool()->axis],curDIO.s,curDIO.L);
	return true;
}

//---------------------------------------------------------------------------
double CPrinter::GetActualPathSpeed()
//---------------------------------------------------------------------------
{
	//return the current path tangential speed
	double spd = 0;
	for(int i = 0; i < POSITION_AXES; i++)
	{
		spd+=(component[i+1].GetVel()*component[i+1].GetVel());
	}
	return(sqrt(spd));
}

//---------------------------------------------------------------------------
double CPrinter::GetMaxPathSpeed()
//---------------------------------------------------------------------------
{
	//return the maximum path tangential speed (in XY plane)
	double mmps = min(component[1].mmps,component[2].mmps);
	ASSERT((mmps > 0.0)&&(mmps<1.0));
    return(mmps*MAX_STEP_FREQ);
}

//---------------------------------------------------------------------------
bool CPrinter::SetJogSpeed(double spd)
//---------------------------------------------------------------------------
{
	//set the non-build motion speed
	//return true if below maximum attainable
	if(spd > GetMaxPathSpeed())
	{
		m_dJogSpeed = GetMaxPathSpeed();
		return false;
	}
	m_dJogSpeed = spd;
	return true;
}

//---------------------------------------------------------------------------
DWORD CPrinter::GetPCElapsedTime()
//---------------------------------------------------------------------------
{
	//return the time in ms of the PC clock since the printer was reset
	return (GetTickCount() - m_dwMachineStartTime_ms);
}

//---------------------------------------------------------------------------
DWORD CPrinter::GetCommandedStatusPeriod()
//---------------------------------------------------------------------------
{
	//return the commanded status update rate in milliseconds

	return m_dwCMDStatusPeriod;
}

//---------------------------------------------------------------------------
DWORD CPrinter::GetTargetStatusPeriod()
//---------------------------------------------------------------------------
{
	//return the target status update period in milliseconds
	return m_dwTGTStatusPeriod;
}

//---------------------------------------------------------------------------
void CPrinter::SetTargetStatusPeriod(DWORD msPeriod)
//---------------------------------------------------------------------------
{
	//set the target status update period in milliseconds
	if(msPeriod > MAX_STATUS_UPDATE_PERIOD)
		msPeriod = MAX_STATUS_UPDATE_PERIOD;
	m_dwTGTStatusPeriod = (DWORD)msPeriod;
}

//---------------------------------------------------------------------------
void CPrinter::SetUserStatusPeriod(DWORD msPeriod)
//---------------------------------------------------------------------------
{
	//set the user's requested update period
	if(msPeriod > 0 && msPeriod < MAX_STATUS_UPDATE_PERIOD)
		m_dwUSRStatusPeriod = msPeriod;
	else
		m_dwUSRStatusPeriod = STATUS_UPDATE_PERIOD;
}

//---------------------------------------------------------------------------
bool CPrinter::CalcStatusPeriod(DWORD deltaT)
//---------------------------------------------------------------------------
{
	//calculate the actual status update period being achieved in milliseconds
	//use windowed average, with window size m_nStatusSamples

	//while calc_step is less than m_nStatusSamples, just accumulate
	//deltaT fractions; after m_nStatusSamples steps, remove the oldest value

	int i;

	if(deltaT <= 0) return false;

	//calculate the average weighted deltaT increment
	double dTinc = deltaT/m_nStatusSamples;
	
	if(m_nPeriodCalcStep < m_nStatusSamples)
	{
		//track the old deltaT increments
		m_arStatusPeriod.Add(dTinc);
		//track how many ticks have accumulated
		m_nPeriodCalcStep++;
	}
	else
	{
		//after accumulating m_nStatusSamples increments
		//start removing oldest increment and shift the array down
		for(i = 0; i < m_nStatusSamples-1; i++)
		{
			m_arStatusPeriod[i] = m_arStatusPeriod[i+1];
		}
		m_arStatusPeriod[m_nStatusSamples-1] = dTinc;
	}
	//finally calculate and store the average period
	double tmp = 0.0;
	for(i = 0; i < m_nPeriodCalcStep; i++)
	{
		tmp+=m_arStatusPeriod[i];
	}
	if(tmp > 0) m_dwACTStatusPeriod = (DWORD)tmp;
	return true;
}

//---------------------------------------------------------------------------
DWORD CPrinter::GetActualStatusPeriod()
//---------------------------------------------------------------------------
{
	//return the rolling average value of the status update period
	return m_dwACTStatusPeriod;
}

//---------------------------------------------------------------------------
bool CPrinter::GetStatus(void)
//---------------------------------------------------------------------------
{
	//fetch the status information from the machine
	//reinit the packets to increment their indices

	//lock the update mutex to ensure that state update is atomic
	if(!bHardwareInitialized) return bEmulateHardware;

	CSingleLock updateLock(&m_mutUpdate);
	if(!updateLock.Lock((DWORD)(2*GetTargetStatusPeriod())))
	{
		//have lock timeout
		return false;
	}

	if(!m_statusPkt.InitPacket()) return false;
	if(!m_statusAckPkt.InitPacket(m_BFirmwareVersion)) return false;

	CString msg;
	bool result = false;
	//send out the request for status, and receive the response
	//use a tight timeout here to quickly indicate bad connection
	result = m_channel.SendReceive(&m_statusPkt, &m_statusAckPkt,(DWORD)(2*GetTargetStatusPeriod()));
	if(!result)
	{
		msg.Format("GetStatus failed");
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}

	//now extract the status info from the packet
	m_nQSpace = m_statusAckPkt.GetQSpace();
	for(int i = 0; i < AXES_CNT; i++)
	{
		m_arlGlobalPos[i] = m_statusAckPkt.GetGlobalPos(i);
		//m_arlEncoder[i] = m_statusAckPkt.GetEncoderRdg(i);
		m_arbLimitState[2*i] = (m_statusAckPkt.GetLimitSwitches() & (1 << (2*i)))>0;
		m_arbLimitState[(2*i)+1] = (m_statusAckPkt.GetLimitSwitches() & (1 << ((2*i)+1)))>0;
	}
	m_stateFlags = m_statusAckPkt.GetState(); 
	m_dwCurCommand = m_statusAckPkt.GetIdxCurCommand();
	m_dwLastCmdExecuted = m_statusAckPkt.GetIdxLastExecuted();

	//calculate the elapsed time for the last update cycle
	//and update the running average
	DWORD priorT = m_dwMachineElapsedTime_ms;
	m_dwMachineElapsedTime_ms = m_statusAckPkt.GetElapsedTime_ms();
	CalcStatusPeriod(m_dwMachineElapsedTime_ms-priorT); 
	//if this is the first packet received, store the PC tick count
	//to verify that micro timer interrupt is running correctly
	if(m_bFirstPacket)
	{
		//now this can be subtracted from the tick count to get PC elapsed time
		m_dwMachineStartTime_ms = GetTickCount()+m_dwMachineElapsedTime_ms;
		m_bFirstPacket = false;
	}
	//tell the graphics where to be
	//read axis positions from the component specifications
	//moveable components start at index = 1 (index 0 is the base)
	//TODO: have firmware handle axes directions via configuration packet
	//for now we are fixing the directions 

	CVec X;
	X.x = m_arlGlobalPos[component[1].axis]*component[1].mmps;
	X.y = m_arlGlobalPos[component[2].axis]*component[2].mmps;
	X.z = m_arlGlobalPos[component[3].axis]*component[3].mmps;
	component[1].SetRTPos(X.x*component[1].axisDir);
	component[2].SetRTPos(X.y*component[2].axisDir);
	component[3].SetRTPos(X.z*component[3].axisDir);

	//check for motion by comparing current positions with last

	// rest of counters are for tools
	int nt = pApp->tool.GetSize();
	bool moving = false;
	for (int i=0; i<nt; i++) 
	{
		double laststep = pApp->tool[i].curstep;
		pApp->tool[i].curstep = m_arlGlobalPos[pApp->tool[i].axis];
		if(laststep != pApp->tool[i].curstep)
		{
			X.x = component[1].GetRTPos();
			X.y = component[2].GetRTPos();
			X.z = component[3].GetRTPos();
			if(pModel != NULL) pModel->TracePoint(ModelToRobotTfm(X-m_vOrigin));
			moving = true;
		}
	}
	m_bToolMoving = moving;

	//set flag to indicate updated status info
	bNewStatus = true;
	
	//if logging is on, log the command
	CString fun;
	fun.Format("GetStatus");
	Log(fun,fun);
	return true;
}

//---------------------------------------------------------------------------
void CPrinter::ManageAmpDisable()
//---------------------------------------------------------------------------
{
	//manage the automatic disabling of amplifiers during idle time
	if(!bHardwareInitialized) return;

	if(!IsStarted() || IsMoving() || IsToolMoving())
	{
		m_ctIdleStart = CTime::GetCurrentTime();
		m_ctsIdleTime = 0;
		return;
	}
	m_ctsIdleTime = CTime::GetCurrentTime()-m_ctIdleStart;
	if(m_ctsIdleTime > CTimeSpan(AMP_IDLE_DISABLE_TIME))
		if(IsStarted()) Start(); //disable the amps
}

//---------------------------------------------------------------------------
bool CPrinter::ManageComms(bool bError)
//---------------------------------------------------------------------------
{
	//manage the comms workload and check for error conditions
	//set bError true if a malfunction has occurred
	//return false only if fatal condition
	if(!bHardwareInitialized) return bEmulateHardware;

	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock(10000); //give up after 10s
	if(!updateLock.IsLocked()) return false; //fatal error

	DWORD targetPeriod = GetTargetStatusPeriod();
	double err = ((double)targetPeriod-(double)GetActualStatusPeriod());

	//if we experience very large error, consider it a comms fault
	if(abs(err)*2.0 > targetPeriod) bError = true;

	if(bError)
		m_dCommsErrorRate += 1.0/COMMS_AVE_WINDOW;
	m_dCommsErrorRate -= m_dCommsErrorRate/COMMS_AVE_WINDOW;
	if(m_dCommsErrorRate > 1.0) m_dCommsErrorRate = 1.0;
	if(m_dCommsErrorRate < 0.0) m_dCommsErrorRate = 0.0;

	if(m_dCommsErrorRate >= COMMS_FATAL_THRESH) return false; //declare fatal condition

	//now makes changes to commanded update period, slowly
	if((GetLastCmdSent()/10)%10 == 9) //every 100 packets
	{
		if(m_dCommsErrorRate >= COMMS_DERATE_THRESH)
		{
			//derate the target period by 10%
			SetTargetStatusPeriod((DWORD)min(1.1*GetTargetStatusPeriod(),MAX_STATUS_UPDATE_PERIOD));
		}
		if(m_dCommsErrorRate <= COMMS_RERATE_THRESH)
		{
			//rerate (decrease) the target period by 5%
			SetTargetStatusPeriod((DWORD)max(0.95*GetTargetStatusPeriod(),GetUserStatusPeriod()));
		}
		//update the rate with a low gain
		double cmd = m_dwCMDStatusPeriod;
		cmd += err/m_dwCMDStatusPeriod*COMMS_P_GAIN;
		if((cmd >= GetUserStatusPeriod()) && (cmd < MAX_STATUS_UPDATE_PERIOD))
			m_dwCMDStatusPeriod = (DWORD)cmd;
	}
	TRACE("CMDPeriod: %d, TGTPeriod: %d, ACTPeriod: %d, err %f\n", m_dwCMDStatusPeriod, GetTargetStatusPeriod(), GetActualStatusPeriod(), err);

	return true;
}

//---------------------------------------------------------------------------
void CPrinter::NetworkConnect(bool bConnect)
//---------------------------------------------------------------------------
{
	if(!bConnect) //force disconnection
	{
		m_sStatusBarMessage.Format("Disconnecting...");
		if(p_connEctor->isConnected())
			p_connEctor->disconnect();
		else 
			p_connListener->cancel();
		//m_connListener.disconnect();
	}
}

//---------------------------------------------------------------------------
void CPrinter::StartNetworkThread()
//---------------------------------------------------------------------------
{
	AfxBeginThread(NetworkThreadProc,this);
	m_bNetworkConnect = true;
}


//---------------------------------------------------------------------------
UINT CPrinter::NetworkThreadProc( LPVOID pParam )
//---------------------------------------------------------------------------
{
	//worker function for external process communications
	CPrinter *pMachine = (CPrinter *)pParam;
	AfxSocketInit();
	pMachine->p_connEctor = new CConn();
	pMachine->p_connListener = new CConn();
	if(pMachine->p_connEctor == NULL || pMachine->p_connListener == NULL)
	{
		pMachine->m_sStatusBarMessage.Format("Unable to make network sockets");
		return 1;
	}
	CString msg;
	bool commOK = true;
	if(pMachine->p_connListener->listen())
	{
		pMachine->m_sStatusBarMessage.Format("Listening on network...");
		pMachine->m_bNetworkConnect = true;
		if(pMachine->p_connListener->accept(*(pMachine->p_connEctor)))
		{
			pMachine->m_sStatusBarMessage.Format("Connected on Network");
			commOK = pMachine->p_connEctor->sendString("Hello World\n");
			commOK = pMachine->p_connEctor->flush();
			while(commOK && pMachine->m_bNetworkConnect)
			{
				commOK = pMachine->p_connEctor->readString(msg);
				pMachine->m_sStatusBarMessage=msg;
				Sleep(100);
			}
			pMachine->p_connEctor->disconnect();
			pMachine->p_connListener->disconnect();
		}
	}
	if(pMachine->p_connEctor != NULL) delete pMachine->p_connEctor;
	if(pMachine->p_connListener != NULL) delete pMachine->p_connListener;

	pMachine->m_sStatusBarMessage.Format("Network Connection Closed");
	pMachine->m_bNetworkConnect = false;
	return 0;
}

//---------------------------------------------------------------------------
UINT CPrinter::StatusThreadProc( LPVOID pParam )
//---------------------------------------------------------------------------
{
	//worker function for fetching status data from Fab@Home
	bool statusOK = false;
	bool queueOK = false;
	bool commsOK = true;
	int retries = 20;
	CString msg;
	CPrinter *pMachine = (CPrinter *)pParam;
	CFabAtHomeApp *pApp = (CFabAtHomeApp *) AfxGetApp();
	
	int counter = 0;
	do
	{
		counter++; //track status fetches
		if(pMachine->bEmulateHardware) //if emulating, do nothing
		{
			//TODO: fetch status from simulated hardware
			statusOK = true;
			queueOK = true;
			commsOK = true;
		}
		else
		{
			//first fetch the status
			statusOK = pMachine->GetStatus();

			//now try to queue some path segments
			// 04-11-2008: Support for pause buiding if U- or V- limit switch is active
			// The printing process is only pause if the limit switch of the active tool is active
			if(statusOK)
			{
				queueOK = pMachine->QueuePath();
				if(pMachine->IsFabricating() && 
					((!pMachine->GetLimit(AXIS_U,false) && pMachine->GetCurTool()->axis == AXIS_U) || 
					(!pMachine->GetLimit(AXIS_V,false) && pMachine->GetCurTool()->axis == AXIS_V)))

					pMachine->pModel->fab.RequestPause();
			}
		}

		//now sleep for the status period
		Sleep(pMachine->GetCommandedStatusPeriod());

		//manage amplifier auto-disable
		pMachine->ManageAmpDisable();

		//manage the comms workload and check for fatal malfunctions
		if(pMachine->GetFirmwareVersion() > 2)
			commsOK = true; 
		else
			pMachine->ManageComms(!(statusOK && queueOK));

		pMachine->UpdateStatusBarMessage();
		if(counter % VIEW_REFRESH_MULT == 0)
			AfxGetMainWnd()->Invalidate();

	} while( (statusOK || queueOK) && commsOK && pMachine->m_bCollectStatus );
	//if both fail at same time, then probably something wrong
	//so kill the thread
	if(statusOK && queueOK && commsOK && !pMachine->m_bCollectStatus)
	{
		AfxEndThread(0); //success
		return 0;  //successful completion
	}
	else
	{
		//tell the base class we are no longer running
		pMachine->m_bCollectStatus = false;
		//tell user
		CString qMsg, sMsg, cMsg;
		if(statusOK)
			sMsg.Format("GetStatus: OK");
		else
			sMsg.Format("GetStatus: Fail");
		if(queueOK)
			qMsg.Format("QueuePath: OK");
		else
			qMsg.Format("QueuePath: Fail");
		if(commsOK)
			cMsg.Format("Comms: OK");
		else
			cMsg.Format("Comms: Fail");

		//probable cause is loss of connection, abort and try to disconnect
		pMachine->AbortBuild();
		pMachine->ShutdownHardware();
		pMachine->bNewStatus = true;
		msg.Format("Connection to hardware lost! Please disconnect and reconnect the USB cable, and try a lower STATUS_UPDATE_PERIOD (%s, %s, %s)",
			sMsg, qMsg, cMsg);
		pApp->Log(msg);
		AfxEndThread(1); //failed
		return 1;
	}
}

//---------------------------------------------------------------------------
bool CPrinter::CollectStatus( bool start )
//---------------------------------------------------------------------------
{
	//start/stop a worker thread to collect status info
	//also handles sending queued motion commands
	if(start && !m_bCollectStatus)
	{
		//this is an important thread - run at high priority
		m_pStatusThread = AfxBeginThread(StatusThreadProc, this, THREAD_PRIORITY_TIME_CRITICAL);
		m_bCollectStatus = (m_pStatusThread != NULL);
		return m_bCollectStatus;
	}
	else
	{
		//tell status thread to terminate
		m_bCollectStatus = false;
		//wait for the thread to die
		if(m_pStatusThread == NULL) //CWinThread already destroyed
		{
			return true;
		}
		else
		{	
			switch( WaitForSingleObject(m_pStatusThread->m_hThread, 10* m_dwTGTStatusPeriod) )
			{
			case WAIT_OBJECT_0:
				return true;
			case WAIT_TIMEOUT:
				return false;
			default:
				return false;
			}
		}
	}
	return true;
}

//---------------------------------------------------------------------------
bool CPrinter::Configure(void)
//---------------------------------------------------------------------------
{
	//send config info to the machine 
	//right now, just which limit switches are used
	if(!IsChannelOpen()) return bEmulateHardware;

	CConfigurePacket pkt;
	CConfigAckPacket ackPkt;
	//fill in the packet with the limit switch configuration
	if(!pkt.InitPacket(m_arBLimitSwitch)) return false;
	//prep the configuration acknowledgement packet to receive ack
	if(!ackPkt.InitPacket()) return false;

	//now do atomic send/receive to prevent goofy behavior
	if(!m_channel.SendReceive(&pkt, &ackPkt)) return false;

	//now unpack the packet
	m_BFirmwareVersion = ackPkt.GetFWVersion();

	//confirm that the limit switch configuration was successful
	int mismatch = 0;
	for(int i = 0; i < (2*AXES_CNT); i++)
	{
		if(m_arBLimitSwitch[i]!=((ackPkt.GetLimitConfig().data.W & (1 << i)) >> i))
			mismatch++;
	}

	CString msg;
	if( mismatch > 0 )
	{
		msg.Format("Firmware configuration of &d limit switches failed!", mismatch);
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
		return false;
	}

	//check that the firmware version is compatible
	if(m_BFirmwareVersion < NEEDS_FW_VERSION)
	{
		msg.Format("This Fab@Home requires firmware version %d! Behavior will be unpredictable.", NEEDS_FW_VERSION);
		((CFabAtHomeApp *)AfxGetApp())->Log(msg);
	}

	return true;
}

//---------------------------------------------------------------------------
long CPrinter::GetGlobalPos( BYTE axis )
//---------------------------------------------------------------------------
{
	//return the global position for the specified axis
	//in steps from the home position
	return m_arlGlobalPos[axis];
}

//---------------------------------------------------------------------------
bool CPrinter::LimitsActive()
//---------------------------------------------------------------------------
{
	//true if any limits are active
	for(BYTE i = 0; i < AXES_CNT; i++ )
	{
		if(GetLimit(i,true)) return true;
		if(GetLimit(i,false)) return true;
	}
	return false;
}

//---------------------------------------------------------------------------
bool CPrinter::GetLimit( BYTE axis, bool fwd )
//---------------------------------------------------------------------------
{
	//test limit switch active for specified axis and direction
	//limits stored as Xfwd, Xbkd, Yfwd,...
	//TODO: unscramble the limit and motion directions!
	if(fwd)
		return m_arbLimitState[2*axis]; 
	else
		return m_arbLimitState[(2*axis)+1];
}

//--------------------------------------------------------------------
WORD CPrinter::GetQSpace()
//--------------------------------------------------------------------
{
	return m_nQSpace;
}

//--------------------------------------------------------------------
bool CPrinter::IsStarted()
//--------------------------------------------------------------------
{
	return m_stateFlags.STARTED;
}

//--------------------------------------------------------------------
bool CPrinter::IsPaused()
//--------------------------------------------------------------------
{
	return m_stateFlags.PAUSED;
}

//--------------------------------------------------------------------
bool CPrinter::IsAborted()
//--------------------------------------------------------------------
{
	return m_stateFlags.ABORTED;};

//--------------------------------------------------------------------
bool CPrinter::IsOriginSet()
//--------------------------------------------------------------------
{
	return m_bOriginSet;
}

//--------------------------------------------------------------------
bool CPrinter::IsSafeSet()
//--------------------------------------------------------------------
{
	return m_bSafeSet;
}

//--------------------------------------------------------------------
bool CPrinter::IsPathDone()
//--------------------------------------------------------------------
{
	//true when path array is empty
	return m_bQPathDone;
} 

//--------------------------------------------------------------------
bool CPrinter::IsError()
//--------------------------------------------------------------------
{
	return m_stateFlags.MALF;
}

//--------------------------------------------------------------------
bool CPrinter::IsQEmpty()
//--------------------------------------------------------------------
{
	return m_stateFlags.QEMPTY;
}

//--------------------------------------------------------------------
bool CPrinter::IsConfigured()
//--------------------------------------------------------------------
{
	//microcontroller only returns true if configuration was successful
	return m_stateFlags.CONFIGURED;
}  

//--------------------------------------------------------------------
bool CPrinter::IsCollecting()
//--------------------------------------------------------------------
{
	//return true if the worker thread is collecting status

	return m_bCollectStatus;
}

//--------------------------------------------------------------------
DWORD CPrinter::GetLastCmdSent()
//--------------------------------------------------------------------
{
	//get the index of the last command sent over the channel
	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	return m_channel.GetLastSentIdx();
}	

//--------------------------------------------------------------------
DWORD CPrinter::GetLastCmdQueued()
//--------------------------------------------------------------------
{
	//get the index of the last command queued to the microcontroller
	return m_dwQueuePathIndex;
}	

//--------------------------------------------------------------------
DWORD CPrinter::GetLastCmdRecd()
//--------------------------------------------------------------------
{
	//get the index of the last command recd over the channel

	CSingleLock updateLock(&m_mutUpdate);
	updateLock.Lock();
	return m_channel.GetLastRecdIdx();

}
//--------------------------------------------------------------------
DWORD CPrinter::GetLastCmdExecuted()
//--------------------------------------------------------------------
{
	//get the index of the last command executed by the Fab@Home
	return m_dwLastCmdExecuted;
} 

//--------------------------------------------------------------------
DWORD CPrinter::GetCurCommand()
//--------------------------------------------------------------------
{
	//get the index of the command currently being executed by the Fab@Home
	return m_dwCurCommand;
} 

//--------------------------------------------------------------------
DWORD CPrinter::GetMachineElapsedTime_ms()
//--------------------------------------------------------------------
{
	return m_dwMachineElapsedTime_ms;
}

//--------------------------------------------------------------------
bool CPrinter::StatusOK()
//--------------------------------------------------------------------
{
	//return false if any abnormal condition (e.g. EStop, abort, etc)
	if(IsEStop()) return false;
	if(IsAborted()) return false;
	return true;
}

//--------------------------------------------------------------------
void CPrinter::UpdateStatusBarMessage()
//--------------------------------------------------------------------
{
	//look at system state and post a message accordingly
	if(IsEStop())
		m_sStatusBarMessage.Format("!!!!!EMERGENCY STOP!!!!!");
	else if(IsAborted())
		m_sStatusBarMessage.Format("!!!!!HARDWARE ABORT!!!!!");
	else if(bEmulateHardware)
		m_sStatusBarMessage.Format("Hardware Emulation Mode");
	else if(bHardwareInitialized)
		m_sStatusBarMessage.Format("Connected to Hardware");
	else
		m_sStatusBarMessage.Format("Unknown Status");
}

//--------------------------------------------------------------------
//CString CPrinter::GetStatusText(void)
////--------------------------------------------------------------------
//{	// Describe HW status info
//
//	if (!IsDefined()) 
//		return CString("Printer not defined. Use 'Load Configuration'.");
//
//
//	static CString msg;
//	msg = "";
//	if (this->bHardwareInitialized)
//	{
//		msg.Append("------FIRMWARE/COMMUNICATIONS--------\n");
//		msg.AppendFormat("Firmware Version: %d\n", GetFirmwareVersion());
//		msg.AppendFormat("Elapsed Time: %0.1fs (PC), %0.1fs (uC)\n", 
//			GetPCElapsedTime()/1000.0, GetMachineElapsedTime_ms()/1000.0);
//		msg.AppendFormat("COM Port Handle: %d\n", GetPortHandle());
//		msg.AppendFormat("Update: %0.1fHz (TGT), %0.1fHz (AVE(%d))\n",
//			1000.0/GetTargetStatusPeriod(), 1000.0/GetActualStatusPeriod(), m_nStatusSamples);
//		msg.AppendFormat("Comms error rate: %0.1f%% (AVE(%d))\n", GetCommsErrorRate()*100, COMMS_AVE_WINDOW); 
//		msg.Append("----------------COMMANDS---------------------\n");
//		msg.AppendFormat("Last Sent: %6d  Last Recd: %6d\n", GetLastCmdSent(), GetLastCmdSent());
//		msg.AppendFormat("Running: %6d  Last Executed: %6d\n",
//			GetCurCommand(), GetLastCmdExecuted());
//		msg.Append("-----------------MOTION---------------------\n");
//		msg.AppendFormat("Hardware Moving: %d\n", IsMoving());
//		msg.AppendFormat("Carriage Axes:\n");
//		msg.AppendFormat("X:%.2f%+.2f mm, %.2f mm/s\n", 
//			component[1].GetRTPos(),component[1].GetErrorOffset(),component[1].GetVel());
//		msg.AppendFormat("Y:%.2f%+.2f mm, %.2f mm/s\n",
//			component[2].GetRTPos(),component[2].GetErrorOffset(),component[2].GetVel());
//		msg.AppendFormat("Z:%.2f%+.2f mm, %.2f mm/s\n",
//			component[3].GetRTPos(),component[3].GetErrorOffset(),component[3].GetVel());
//		msg.AppendFormat("Tangential Speed: %5.2f mm/s\n", GetActualPathSpeed());
//		msg.AppendFormat("Tool Axes:\nU:%d step, V:%d step, W:%d step\n",
//				GetGlobalPos(AXIS_U),GetGlobalPos(AXIS_V),GetGlobalPos(AXIS_W));
//		msg.Append("--------------LIMIT SWITCHES-----------------\n0 means active, 1 means inactive\n");
//		msg.AppendFormat("X-=%d, X+=%d\nY-=%d, Y+=%d\nZ-=%d, Z+=%d\nU-=%d\nV-=%d\n", 
//			GetLimit(AXIS_X,true),GetLimit(AXIS_X,false),
//			GetLimit(AXIS_Y,true),GetLimit(AXIS_Y,false),
//			GetLimit(AXIS_Z,false),GetLimit(AXIS_Z,true),
//			GetLimit(AXIS_U,false),
//			GetLimit(AXIS_V,false));
//		msg.Append("-------------------STATUS-----------------------\n");
//		msg.AppendFormat("Aborted: %d  Homed: %d\n", IsAborted(), IsHomed());
//		msg.AppendFormat("Enabled: %d  Paused: %d\n", IsStarted(), IsPaused());
//		msg.AppendFormat("Configd: %d  Error: %d\n", IsConfigured(), IsError());
//		if(IsEStop()) msg.AppendFormat("!!!!!!!!!EMERGENCY STOP!!!!!!!!!\n");
//		if(IsStarted() && !IsMoving()) 
//			msg.AppendFormat("Amplifier idle auto-disable in: %s\n", 
//			(CTimeSpan(AMP_IDLE_DISABLE_TIME)-m_ctsIdleTime).Format("%H:%M.%S"));
//		msg.Append("--------------MOTION QUEUE-------------------\n");
//		msg.AppendFormat("Queue Empty: %d  Queue Space: %d\n", IsQEmpty(), GetQSpace());
//	}
//	else
//	{
//		msg.Format("Hardware Offline\n");
//	}
//
//	return msg;
//}

//--------------------------------------------------------------------
CString CPrinter::GetStatusText(void)
//--------------------------------------------------------------------
{	// Describe HW status info

	if (!IsDefined()) 
		return CString("Printer not defined. Use 'Load Configuration'.");


	static CString msg;
	msg = "";
	if (bEmulateHardware)
	{
		msg.Format("-----------EMULATION MODE------------\n");
		bNewStatus = true;
	}
	msg.Append("------FIRMWARE/COMMUNICATIONS--------\n");
	msg.AppendFormat("Firmware Version: %d\n", GetFirmwareVersion());
	msg.AppendFormat("Elapsed Time: %0.1fs (PC), %0.1fs (uC)\n", 
		GetPCElapsedTime()/1000.0, GetMachineElapsedTime_ms()/1000.0);
	msg.AppendFormat("COM Port Handle: %d\n", GetPortHandle());
	msg.AppendFormat("Update: %0.1fHz (TGT), %0.1fHz (AVE(%d))\n",
		1000.0/GetTargetStatusPeriod(), 1000.0/GetActualStatusPeriod(), m_nStatusSamples);
	msg.AppendFormat("Comms error rate: %0.1f%% (AVE(%d))\n", GetCommsErrorRate()*100, COMMS_AVE_WINDOW); 
	msg.Append("----------------COMMANDS---------------------\n");
	msg.AppendFormat("Last Sent: %6d  Last Recd: %6d\n", GetLastCmdSent(), GetLastCmdSent());
	msg.AppendFormat("Running: %6d  Last Executed: %6d\n",
		GetCurCommand(), GetLastCmdExecuted());
	msg.Append("-----------------MOTION---------------------\n");
	msg.AppendFormat("Hardware Moving: %d\n", IsMoving() || IsToolMoving());
	msg.AppendFormat("Hardware InPosition: %d\n", InPosition());
	msg.AppendFormat("Carriage Axes:\n");
	if(true)/*m_BFirmwareVersion > 3)
	{
		msg.AppendFormat("X:%.2f%+.2f mm, ENC:%d, %.2f mm/s\n", 
			component[1].GetRTPos(),component[1].GetErrorOffset(),
			m_arlEncoder[0], component[1].GetVel());
		msg.AppendFormat("Y:%.2f%+.2f mm, ENC:%d, %.2f mm/s\n",
			component[2].GetRTPos(),component[2].GetErrorOffset(),
			m_arlEncoder[1], component[2].GetVel());
		msg.AppendFormat("Z:%.2f%+.2f mm, ENC:%d, %.2f mm/s\n",
			component[3].GetRTPos(),component[3].GetErrorOffset(),
			m_arlEncoder[2], component[3].GetVel());
	} else*/
	{
		msg.AppendFormat("X:%.2f%+.2f mm, %.2f mm/s\n", 
			component[1].GetRTPos(),component[1].GetErrorOffset(),
			component[1].GetVel());
		msg.AppendFormat("Y:%.2f%+.2f mm, %.2f mm/s\n",
			component[2].GetRTPos(),component[2].GetErrorOffset(),
			component[2].GetVel());
		msg.AppendFormat("Z:%.2f%+.2f mm, %.2f mm/s\n",
			component[3].GetRTPos(),component[3].GetErrorOffset(),
			component[3].GetVel());
	}
	msg.AppendFormat("Tangential Speed: %5.2f mm/s\n", GetActualPathSpeed());
	msg.AppendFormat("Pos Axes:\nX:%d step, Y:%d step, Z:%d step\n",
			GetGlobalPos(AXIS_X),GetGlobalPos(AXIS_Y),GetGlobalPos(AXIS_Z));
	msg.AppendFormat("Tool Axes:\nU:%d step, V:%d step, W:%d step\n",
			GetGlobalPos(AXIS_U),GetGlobalPos(AXIS_V),GetGlobalPos(AXIS_W));
	msg.Append("--------------LIMIT SWITCHES-----------------\n0 means active, 1 means inactive\n");
	msg.AppendFormat("X-=%d, X+=%d\nY-=%d, Y+=%d\nZ-=%d, Z+=%d\nU-=%d\nV-=%d\n", 
		GetLimit(AXIS_X,true),GetLimit(AXIS_X,false),
		GetLimit(AXIS_Y,true),GetLimit(AXIS_Y,false),
		GetLimit(AXIS_Z,false),GetLimit(AXIS_Z,true),
		GetLimit(AXIS_U,false),
		GetLimit(AXIS_V,false));
	msg.Append("-------------------STATUS-----------------------\n");
	msg.AppendFormat("Aborted: %d  Homed: %d\n", IsAborted(), IsHomed());
	msg.AppendFormat("Enabled: %d  Paused: %d\n", IsStarted(), IsPaused());
	msg.AppendFormat("Configd: %d  Error: %d\n", IsConfigured(), IsError());
	if(IsEStop()) msg.AppendFormat("!!!!!!!!!EMERGENCY STOP!!!!!!!!!\n");
	if(IsStarted() && !IsMoving() && !IsToolMoving()) 
		msg.AppendFormat("Amplifier idle auto-disable in: %s\n", 
		(CTimeSpan(AMP_IDLE_DISABLE_TIME)-m_ctsIdleTime).Format("%H:%M.%S"));
	msg.Append("--------------MOTION QUEUE-------------------\n");
	msg.AppendFormat("Queue Empty: %d  Queue Space: %d\n", IsQEmpty(), GetQSpace());
	return msg;
}

//-------------------------------------------------------------------