File: eqmodbase.cpp

package info (click to toggle)
indi-eqmod 1.0%2B20230126190232-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,116 kB
  • sloc: cpp: 8,918; ansic: 1,365; xml: 570; makefile: 2
file content (3706 lines) | stat: -rw-r--r-- 132,305 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
/* Copyright 2012 Geehalel (geehalel AT gmail DOT com) */
/* This file is part of the Skywatcher Protocol INDI driver.

    The Skywatcher Protocol INDI driver is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with the Skywatcher Protocol INDI driver.  If not, see <http://www.gnu.org/licenses/>.

    2013-10-20: Fixed a few bugs and init/update properties issue (Jasem Mutlaq)
    2013-10-24: Use updateTime from new INDI framework (Jasem Mutlaq)
    2013-10-31: Added support for joysticks (Jasem Mutlaq)
    2013-11-01: Fixed issues with logger and Skywatcher's readout for InquireHighSpeedRatio.
    2018-04-27: Added abnormalDisconnect to properly disconnect the driver in case of unrecoverable errors (Jasem Mutlaq)
    2018-04-27: Since all dispatch_command are always followed by read_eqmod, we decided to include it inside
                and on failure, we retries up to the EQMOD_MAX_RETRY before giving up in case of occasional traient errors. (Jasem Mutlaq)
*/

/* TODO */
/* HORIZONTAL_COORDS -> HORIZONTAL_COORD - OK */
/* DATE -> TIME_LST/LST and TIME_UTC/UTC - OK */
/*  Problem in time initialization using gettimeofday/gmtime: 1h after UTC on summer, because of DST ?? */
/* TELESCOPE_MOTION_RATE in arcmin/s */
/* use/snoop a GPS ??*/

#include "eqmodbase.h"

#include "mach_gettime.h"

#include <cmath>
#include <memory>
#include <cstring>
#include <unistd.h>
#include <assert.h>
#include <indicom.h>

#include <connectionplugins/connectiontcp.h>

#ifdef WITH_ALIGN
#include <alignment/DriverCommon.h> // For DBG_ALIGNMENT
using namespace INDI::AlignmentSubsystem;
#endif

#include <libnova/sidereal_time.h>
#include <libnova/transform.h>
#include <libnova/utility.h>

#define GOTO_RATE      2        /* slew rate, degrees/s */
#define SLEW_RATE      0.5      /* slew rate, degrees/s */
#define FINE_SLEW_RATE 0.1      /* slew rate, degrees/s */
#define SID_RATE       0.004178 /* sidereal rate, degrees/s */

#define GOTO_LIMIT      5   /* Move at GOTO_RATE until distance from target is GOTO_LIMIT degrees */
#define SLEW_LIMIT      2   /* Move at SLEW_LIMIT until distance from target is SLEW_LIMIT degrees */
#define FINE_SLEW_LIMIT 0.5 /* Move at FINE_SLEW_RATE until distance from target is FINE_SLEW_LIMIT degrees */

#define GOTO_ITERATIVE_LIMIT 5 /* Max GOTO Iterations */
#define RAGOTORESOLUTION     5 /* GOTO Resolution in arcsecs */
#define DEGOTORESOLUTION     5 /* GOTO Resolution in arcsecs */

/* Preset Slew Speeds */
#define SLEWMODES 11
double slewspeeds[SLEWMODES - 1] = { 1.0, 2.0, 4.0, 8.0, 32.0, 64.0, 128.0, 600.0, 700.0, 800.0 };

#define RA_AXIS     0
#define DEC_AXIS    1
#define GUIDE_NORTH 0
#define GUIDE_SOUTH 1
#define GUIDE_WEST  0
#define GUIDE_EAST  1

#if 0
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
    /* Perform the carry for the later subtraction by updating y. */
    if (x->tv_usec < y->tv_usec)
    {
        int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
        y->tv_usec -= 1000000 * nsec;
        y->tv_sec += nsec;
    }
    if (x->tv_usec - y->tv_usec > 1000000)
    {
        int nsec = (x->tv_usec - y->tv_usec) / 1000000;
        y->tv_usec += 1000000 * nsec;
        y->tv_sec -= nsec;
    }

    /* Compute the time remaining to wait.
     tv_usec is certainly positive. */
    result->tv_sec  = x->tv_sec - y->tv_sec;
    result->tv_usec = x->tv_usec - y->tv_usec;

    /* Return 1 if result is negative. */
    return x->tv_sec < y->tv_sec;
}
#endif

EQMod::EQMod()
{
    //ctor
    setVersion(EQMOD_VERSION_MAJOR, EQMOD_VERSION_MINOR);
    // Do not define dynamic properties on startup, and do not delete them from memory
    setDynamicPropertiesBehavior(false, false);
    currentRA            = 0;
    currentDEC           = 90;
    gotoparams.completed = true;
    last_motion_ns       = -1;
    last_motion_ew       = -1;
    pulseInProgress      = 0;

    DBG_SCOPE_STATUS = INDI::Logger::getInstance().addDebugLevel("Scope Status", "SCOPE");
    DBG_COMM         = INDI::Logger::getInstance().addDebugLevel("Serial Port", "COMM");
    DBG_MOUNT        = INDI::Logger::getInstance().addDebugLevel("Verbose Mount", "MOUNT");

    mount = new Skywatcher(this);

    SetTelescopeCapability(TELESCOPE_CAN_PARK | TELESCOPE_CAN_SYNC | TELESCOPE_CAN_GOTO | TELESCOPE_CAN_ABORT |
                           TELESCOPE_HAS_TIME | TELESCOPE_HAS_LOCATION
                           | TELESCOPE_HAS_PIER_SIDE | TELESCOPE_HAS_TRACK_RATE | TELESCOPE_HAS_TRACK_MODE | TELESCOPE_CAN_CONTROL_TRACK,
                           SLEWMODES);

    RAInverted = DEInverted = false;
    bzero(&syncdata, sizeof(syncdata));
    bzero(&syncdata2, sizeof(syncdata2));

#ifdef WITH_ALIGN_GEEHALEL
    align = new Align(this);
#endif

    simulator = new EQModSimulator(this);

#ifdef WITH_SCOPE_LIMITS
    horizon = new HorizonLimits(this);
#endif

    /* initialize time */
    tzset();
    gettimeofday(&lasttimeupdate, nullptr); // takes care of DST
    gmtime_r(&lasttimeupdate.tv_sec, &utc);
    lndate.seconds = utc.tm_sec + ((double)lasttimeupdate.tv_usec / 1000000);
    lndate.minutes = utc.tm_min;
    lndate.hours   = utc.tm_hour;
    lndate.days    = utc.tm_mday;
    lndate.months  = utc.tm_mon + 1;
    lndate.years   = utc.tm_year + 1900;
    get_utc_time(&lastclockupdate);
    /* initialize random seed: */
    srand(time(nullptr));
    // Others
    AutohomeState      = AUTO_HOME_IDLE;
    restartguidePPEC   = false;
}

EQMod::~EQMod()
{
    //dtor
    delete mount;
    mount = nullptr;
}

#if defined WITH_ALIGN || defined WITH_ALIGN_GEEHALEL
bool EQMod::isStandardSync()
{
    return (strcmp(IUFindOnSwitch(AlignSyncModeSP)->name, "ALIGNSTANDARDSYNC") == 0);
}
#endif

void EQMod::setStepperSimulation(bool enable)
{
    if ((enable && !isSimulation()) || (!enable && isSimulation()))
    {
        mount->setSimulation(enable);
        if (not simulator->updateProperties(enable))
            LOG_WARN("setStepperSimulator: Disable/Enable error");
    }
    INDI::Telescope::setSimulation(enable);
}

const char *EQMod::getDefaultName()
{
    return "EQMod Mount";
}

double EQMod::getLongitude()
{
    return (IUFindNumber(&LocationNP, "LONG")->value);
}

double EQMod::getLatitude()
{
    return (IUFindNumber(&LocationNP, "LAT")->value);
}

double EQMod::getJulianDate()
{
    /*
    struct timeval currenttime, difftime;
    double usecs;
    gettimeofday(&currenttime, nullptr);
    if (timeval_subtract(&difftime, &currenttime, &lasttimeupdate) == -1)
    return juliandate;
    */
    struct timespec currentclock, diffclock;
    double nsecs;
    get_utc_time(&currentclock);
    diffclock.tv_sec  = currentclock.tv_sec - lastclockupdate.tv_sec;
    diffclock.tv_nsec = currentclock.tv_nsec - lastclockupdate.tv_nsec;
    while (diffclock.tv_nsec > 1000000000)
    {
        diffclock.tv_sec++;
        diffclock.tv_nsec -= 1000000000;
    }
    while (diffclock.tv_nsec < 0)
    {
        diffclock.tv_sec--;
        diffclock.tv_nsec += 1000000000;
    }
    //IDLog("Get Julian; ln_date was %02d:%02d:%.9f\n", lndate.hours, lndate.minutes, lndate.seconds);
    //IDLog("Clocks last: %d secs %d nsecs current: %d secs %d nsecs\n", lastclockupdate.tv_sec,  lastclockupdate.tv_nsec, currentclock.tv_sec,  currentclock.tv_nsec);
    //IDLog("Diff %d secs %d nsecs\n", diffclock.tv_sec,  diffclock.tv_nsec);
    //IDLog("Diff %d %d\n", difftime.tv_sec,  difftime.tv_usec);
    //lndate.seconds += (difftime.tv_sec + (difftime.tv_usec / 1000000));
    //usecs=lndate.seconds - floor(lndate.seconds);
    lndate.seconds += (diffclock.tv_sec + ((double)diffclock.tv_nsec / 1000000000.0));
    nsecs        = lndate.seconds - floor(lndate.seconds);
    utc.tm_sec   = lndate.seconds;
    utc.tm_isdst = -1; // let mktime find if DST already in effect in utc
    //IDLog("Get julian: setting UTC secs to %f", utc.tm_sec);
    mktime(&utc); // normalize time
    //IDLog("Get Julian; UTC is now %s", asctime(&utc));
    ln_get_date_from_tm(&utc, &lndate);
    //IDLog("Get Julian; ln_date is now %02d:%02d:%.9f\n", lndate.hours, lndate.minutes, lndate.seconds);
    //lndate.seconds+=usecs;
    //lasttimeupdate = currenttime;
    lndate.seconds += nsecs;
    //IDLog("     ln_date with nsecs %02d:%02d:%.9f\n", lndate.hours, lndate.minutes, lndate.seconds);
    lastclockupdate = currentclock;
    juliandate      = ln_get_julian_day(&lndate);
    //IDLog("julian diff: %g\n", juliandate - ln_get_julian_from_sys());
    return juliandate;
    //return ln_get_julian_from_sys();
}

double EQMod::getLst(double jd, double lng)
{
    double lst;
    //lst=ln_get_mean_sidereal_time(jd);
    lst = ln_get_apparent_sidereal_time(jd);
    lst += (lng / 15.0);
    lst = range24(lst);
    return lst;
}

bool EQMod::initProperties()
{
    /* Make sure to init parent properties first */
    INDI::Telescope::initProperties();

    loadProperties();

    for (int i = 0; i < SlewRateSP.nsp - 1; i++)
    {
        SlewRateSP.sp[i].s = ISS_OFF;
        sprintf(SlewRateSP.sp[i].label, "%.fx", slewspeeds[i]);
        SlewRateSP.sp[i].aux = (void *)&slewspeeds[i];
    }

    // Since last item is NOT maximum (but custom), let's set item before custom to SLEWMAX
    SlewRateSP.sp[SlewRateSP.nsp - 2].s = ISS_ON;
    strncpy(SlewRateSP.sp[SlewRateSP.nsp - 2].name, "SLEW_MAX", MAXINDINAME);
    // Last is custom
    strncpy(SlewRateSP.sp[SlewRateSP.nsp - 1].name, "SLEWCUSTOM", MAXINDINAME);
    strncpy(SlewRateSP.sp[SlewRateSP.nsp - 1].label, "Custom", MAXINDILABEL);

    AddTrackMode("TRACK_SIDEREAL", "Sidereal", true);
    AddTrackMode("TRACK_SOLAR", "Solar");
    AddTrackMode("TRACK_LUNAR", "Lunar");
    AddTrackMode("TRACK_CUSTOM", "Custom");

    SetParkDataType(PARK_RA_DEC_ENCODER);

    setDriverInterface(getDriverInterface() | GUIDER_INTERFACE);
#ifdef WITH_ALIGN
    InitAlignmentProperties(this);

    // Force the alignment system to always be on
    getSwitch("ALIGNMENT_SUBSYSTEM_ACTIVE")->sp[0].s = ISS_ON;
#endif

    tcpConnection->setDefaultHost("192.168.4.1");
    tcpConnection->setDefaultPort(11880);
    tcpConnection->setConnectionType(Connection::TCP::TYPE_UDP);

    addAuxControls();
    return true;
}

void EQMod::ISGetProperties(const char *dev)
{
    INDI::Telescope::ISGetProperties(dev);

    if (isConnected())
    {
        defineProperty(&GuideNSNP);
        defineProperty(&GuideWENP);
        defineProperty(SlewSpeedsNP);
        defineProperty(GuideRateNP);
        defineProperty(PulseLimitsNP);
        defineProperty(MountInformationTP);
        defineProperty(SteppersNP);
        defineProperty(CurrentSteppersNP);
        defineProperty(PeriodsNP);
        defineProperty(JulianNP);
        defineProperty(TimeLSTNP);
        defineProperty(RAStatusLP);
        defineProperty(DEStatusLP);
        defineProperty(HemisphereSP);
        defineProperty(HorizontalCoordNP);
        defineProperty(ReverseDECSP);
        defineProperty(TargetPierSideSP);
        defineProperty(StandardSyncNP);
        defineProperty(StandardSyncPointNP);
        defineProperty(SyncPolarAlignNP);
        defineProperty(SyncManageSP);
        defineProperty(BacklashNP);
        defineProperty(UseBacklashSP);
        defineProperty(TrackDefaultSP);
        defineProperty(ST4GuideRateNSSP);
        defineProperty(ST4GuideRateWESP);

#if defined WITH_ALIGN && defined WITH_ALIGN_GEEHALEL
        defineProperty(&AlignMethodSP);
#endif
#if defined WITH_ALIGN || defined WITH_ALIGN_GEEHALEL
        defineProperty(AlignSyncModeSP);
#endif
        if (mount->HasHomeIndexers())
        {
            defineProperty(AutoHomeSP);
        }

        if (mount->HasAuxEncoders())
        {
            defineProperty(AuxEncoderSP);
            defineProperty(AuxEncoderNP);
        }
        if (mount->HasPPEC())
        {
            defineProperty(PPECTrainingSP);
            defineProperty(PPECSP);
        }
        if (mount->HasSnapPort1())
        {
            defineProperty(SNAPPORT1SP);
        }
        if (mount->HasSnapPort2())
        {
            defineProperty(SNAPPORT2SP);
        }
        if (mount->HasPolarLed())
        {
            defineProperty(LEDBrightnessNP);
        }

#ifdef WITH_ALIGN_GEEHALEL
        if (align)
        {
            align->ISGetProperties();
        }
#endif

#ifdef WITH_SCOPE_LIMITS
        if (horizon)
        {
            horizon->ISGetProperties();
        }
#endif

        simulator->updateProperties(isSimulation());
    }
}

bool EQMod::loadProperties()
{
    buildSkeleton("indi_eqmod_sk.xml");

    GuideRateNP = getNumber("GUIDE_RATE");
    GuideRateN  = GuideRateNP->np;

    PulseLimitsNP  = getNumber("PULSE_LIMITS");
    MinPulseN      = IUFindNumber(PulseLimitsNP, "MIN_PULSE");
    MinPulseTimerN = IUFindNumber(PulseLimitsNP, "MIN_PULSE_TIMER");

    MountInformationTP = getText("MOUNTINFORMATION");
    SteppersNP         = getNumber("STEPPERS");
    CurrentSteppersNP  = getNumber("CURRENTSTEPPERS");
    PeriodsNP          = getNumber("PERIODS");
    JulianNP           = getNumber("JULIAN");
    TimeLSTNP          = getNumber("TIME_LST");
    RAStatusLP         = getLight("RASTATUS");
    DEStatusLP         = getLight("DESTATUS");
    SlewSpeedsNP       = getNumber("SLEWSPEEDS");
    HemisphereSP       = getSwitch("HEMISPHERE");
    TrackDefaultSP     = getSwitch("TELESCOPE_TRACK_DEFAULT");
    ReverseDECSP       = getSwitch("REVERSEDEC");
    TargetPierSideSP    = getSwitch("TARGETPIERSIDE");

    HorizontalCoordNP   = getNumber("HORIZONTAL_COORD");
    StandardSyncNP      = getNumber("STANDARDSYNC");
    StandardSyncPointNP = getNumber("STANDARDSYNCPOINT");
    SyncPolarAlignNP    = getNumber("SYNCPOLARALIGN");
    SyncManageSP        = getSwitch("SYNCMANAGE");
    BacklashNP          = getNumber("BACKLASH");
    UseBacklashSP       = getSwitch("USEBACKLASH");
    AutoHomeSP          = getSwitch("AUTOHOME");
    AuxEncoderSP        = getSwitch("AUXENCODER");
    AuxEncoderNP        = getNumber("AUXENCODERVALUES");
    ST4GuideRateNSSP    = getSwitch("ST4_GUIDE_RATE_NS");
    ST4GuideRateWESP    = getSwitch("ST4_GUIDE_RATE_WE");
    PPECTrainingSP      = getSwitch("PPEC_TRAINING");
    PPECSP              = getSwitch("PPEC");
    LEDBrightnessNP     = getNumber("LED_BRIGHTNESS");
    SNAPPORT1SP         = getSwitch("SNAPPORT1");
    SNAPPORT2SP         = getSwitch("SNAPPORT2");
#ifdef WITH_ALIGN_GEEHALEL
    align->initProperties();
#endif
#if defined WITH_ALIGN && defined WITH_ALIGN_GEEHALEL
    IUFillSwitch(&AlignMethodS[0], "ALIGN_METHOD_EQMOD", "EQMod Align", ISS_ON);
    IUFillSwitch(&AlignMethodS[1], "ALIGN_METHOD_SUBSYSTEM", "Alignment Subsystem", ISS_OFF);
    IUFillSwitchVector(&AlignMethodSP, AlignMethodS, NARRAY(AlignMethodS), getDeviceName(), "ALIGN_METHOD",
                       "Align Method", OPTIONS_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
#endif
#if defined WITH_ALIGN || defined WITH_ALIGN_GEEHALEL
    AlignSyncModeSP = getSwitch("ALIGNSYNCMODE");
#endif

    simulator->initProperties();

    INDI::GuiderInterface::initGuiderProperties(this->getDeviceName(), MOTION_TAB);

#ifdef WITH_SCOPE_LIMITS
    if (horizon)
    {
        if (!horizon->initProperties())
            return false;
    }
#endif

    return true;
}

bool EQMod::updateProperties()
{
    INDI::Telescope::updateProperties();

    if (isConnected())
    {
        defineProperty(&GuideNSNP);
        defineProperty(&GuideWENP);
        defineProperty(SlewSpeedsNP);
        defineProperty(GuideRateNP);
        defineProperty(PulseLimitsNP);
        defineProperty(MountInformationTP);
        defineProperty(SteppersNP);
        defineProperty(CurrentSteppersNP);
        defineProperty(PeriodsNP);
        defineProperty(JulianNP);
        defineProperty(TimeLSTNP);
        defineProperty(RAStatusLP);
        defineProperty(DEStatusLP);
        defineProperty(HemisphereSP);
        defineProperty(HorizontalCoordNP);
        defineProperty(ReverseDECSP);
        defineProperty(TargetPierSideSP);
        defineProperty(StandardSyncNP);
        defineProperty(StandardSyncPointNP);
        defineProperty(SyncPolarAlignNP);
        defineProperty(SyncManageSP);
        defineProperty(BacklashNP);
        defineProperty(UseBacklashSP);
        defineProperty(TrackDefaultSP);
        defineProperty(ST4GuideRateNSSP);
        defineProperty(ST4GuideRateWESP);

#if defined WITH_ALIGN && defined WITH_ALIGN_GEEHALEL
        defineProperty(&AlignMethodSP);
#endif
#if defined WITH_ALIGN || defined WITH_ALIGN_GEEHALEL
        defineProperty(AlignSyncModeSP);
#endif
        try
        {
            mount->InquireBoardVersion(MountInformationTP);

            for (int i = 0; i < MountInformationTP->ntp; i++)
                LOGF_DEBUG("Got Board Property %s: %s", MountInformationTP->tp[i].name,
                           MountInformationTP->tp[i].text);

            mount->InquireRAEncoderInfo(SteppersNP);
            mount->InquireDEEncoderInfo(SteppersNP);

            for (int i = 0; i < SteppersNP->nnp; i++)
                LOGF_DEBUG("Got Encoder Property %s: %.0f", SteppersNP->np[i].label,
                           SteppersNP->np[i].value);

            mount->InquireFeatures();
            if (mount->HasHomeIndexers())
            {
                LOG_INFO("Mount has home indexers. Enabling Autohome.");
                defineProperty(AutoHomeSP);
            }

            if (mount->HasAuxEncoders())
            {
                defineProperty(AuxEncoderSP);
                defineProperty(AuxEncoderNP);
                LOG_INFO("Mount has auxiliary encoders. Turning them off.");
                mount->TurnRAEncoder(false);
                mount->TurnDEEncoder(false);
            }
            if (mount->HasPPEC())
            {
                bool intraining, inppec;
                defineProperty(PPECTrainingSP);
                defineProperty(PPECSP);
                LOG_INFO("Mount has PPEC.");
                mount->GetPPECStatus(&intraining, &inppec);
                if (intraining)
                {
                    PPECTrainingSP->sp[0].s = ISS_OFF;
                    PPECTrainingSP->sp[1].s = ISS_ON;
                    PPECTrainingSP->s       = IPS_BUSY;
                    IDSetSwitch(PPECTrainingSP, nullptr);
                }
                if (inppec)
                {
                    PPECSP->sp[0].s = ISS_OFF;
                    PPECSP->sp[1].s = ISS_ON;
                    PPECSP->s       = IPS_BUSY;
                    IDSetSwitch(PPECSP, nullptr);
                }
            }

            if (mount->HasPolarLed())
            {
                defineProperty(LEDBrightnessNP);
            }

            LOG_DEBUG("Init backlash.");
            mount->SetBacklashUseRA((IUFindSwitch(UseBacklashSP, "USEBACKLASHRA")->s == ISS_ON ? true : false));
            mount->SetBacklashUseDE((IUFindSwitch(UseBacklashSP, "USEBACKLASHDE")->s == ISS_ON ? true : false));
            mount->SetBacklashRA((uint32_t)(IUFindNumber(BacklashNP, "BACKLASHRA")->value));
            mount->SetBacklashDE((uint32_t)(IUFindNumber(BacklashNP, "BACKLASHDE")->value));

            if (mount->HasSnapPort1())
            {
                defineProperty(SNAPPORT1SP);
            }
            if (mount->HasSnapPort2())
            {
                defineProperty(SNAPPORT2SP);
            }

            mount->Init();

            zeroRAEncoder  = mount->GetRAEncoderZero();
            totalRAEncoder = mount->GetRAEncoderTotal();
            homeRAEncoder  = mount->GetRAEncoderHome();
            zeroDEEncoder  = mount->GetDEEncoderZero();
            totalDEEncoder = mount->GetDEEncoderTotal();
            homeDEEncoder  = mount->GetDEEncoderHome();

            parkRAEncoder = GetAxis1Park();
            parkDEEncoder = GetAxis2Park();

            INumber *latitude = IUFindNumber(&LocationNP, "LAT");
            INumber *longitude = IUFindNumber(&LocationNP, "LONG");
            INumber *elevation = IUFindNumber(&LocationNP, "ELEV");
            if (latitude && longitude && elevation)
                updateLocation(latitude->value, longitude->value, elevation->value);
            //            else
            //                updateLocation(0.0, 0.0, 0.0);

            //            if ((latitude) && (latitude->value < 0.0))
            //                SetSouthernHemisphere(true);
            //            else
            //                SetSouthernHemisphere(false);

            sendTimeFromSystem();
        }
        catch (EQModError &e)
        {
            return (e.DefaultHandleException(this));
        }
    }
    else
    {
        deleteProperty(GuideNSNP.name);
        deleteProperty(GuideWENP.name);
        deleteProperty(GuideRateNP->name);
        deleteProperty(PulseLimitsNP->name);
        deleteProperty(MountInformationTP->name);
        deleteProperty(SteppersNP->name);
        deleteProperty(CurrentSteppersNP->name);
        deleteProperty(PeriodsNP->name);
        deleteProperty(JulianNP->name);
        deleteProperty(TimeLSTNP->name);
        deleteProperty(RAStatusLP->name);
        deleteProperty(DEStatusLP->name);
        deleteProperty(SlewSpeedsNP->name);
        deleteProperty(HemisphereSP->name);
        deleteProperty(HorizontalCoordNP->name);
        deleteProperty(ReverseDECSP->name);
        deleteProperty(TargetPierSideSP->name);
        deleteProperty(StandardSyncNP->name);
        deleteProperty(StandardSyncPointNP->name);
        deleteProperty(SyncPolarAlignNP->name);
        deleteProperty(SyncManageSP->name);
        deleteProperty(TrackDefaultSP->name);
        deleteProperty(BacklashNP->name);
        deleteProperty(UseBacklashSP->name);
        deleteProperty(ST4GuideRateNSSP->name);
        deleteProperty(ST4GuideRateWESP->name);
        deleteProperty(LEDBrightnessNP->name);

        if (mount->HasHomeIndexers())
            deleteProperty(AutoHomeSP->name);
        if (mount->HasAuxEncoders())
        {
            deleteProperty(AuxEncoderSP->name);
            deleteProperty(AuxEncoderNP->name);
        }
        if (mount->HasPPEC())
        {
            deleteProperty(PPECTrainingSP->name);
            deleteProperty(PPECSP->name);
        }
        if (mount->HasSnapPort1())
        {
            deleteProperty(SNAPPORT1SP->name);
        }
        if (mount->HasSnapPort2())
        {
            deleteProperty(SNAPPORT2SP->name);
        }
        if (mount->HasPolarLed())
        {
            deleteProperty(LEDBrightnessNP->name);
        }
#if defined WITH_ALIGN && defined WITH_ALIGN_GEEHALEL
        deleteProperty(AlignMethodSP.name);
#endif
#if defined WITH_ALIGN || defined WITH_ALIGN_GEEHALEL
        deleteProperty(AlignSyncModeSP->name);
#endif
        //MountInformationTP=nullptr;
        //}
    }
#ifdef WITH_ALIGN_GEEHALEL
    if (align)
    {
        if (!align->updateProperties())
            return false;
    }
#endif

#ifdef WITH_SCOPE_LIMITS
    if (horizon)
    {
        if (!horizon->updateProperties())
            return false;
    }
#endif

    simulator->updateProperties(isSimulation());

    return true;
}

bool EQMod::Handshake()
{
    try
    {
        if (!getActiveConnection()->name().compare("CONNECTION_TCP")
                && tcpConnection->connectionType() == Connection::TCP::TYPE_UDP)
        {
            tty_set_generic_udp_format(1);
        }

        mount->setPortFD(PortFD);
        mount->Handshake();
        // Mount initialisation is in updateProperties as it sets directly Indi properties which should be defined
    }
    catch (EQModError &e)
    {
        return false;
        //return (e.DefaultHandleException(this));
    }

#ifdef WITH_ALIGN
    // Set this according to mount type
    SetApproximateMountAlignmentFromMountType(EQUATORIAL);
#endif

    LOG_INFO("Successfully connected to EQMod Mount.");
    return true;
}

void EQMod::abnormalDisconnectCallback(void *userpointer)
{
    EQMod *p = static_cast<EQMod *>(userpointer);
    if (p->Connect())
    {
        p->setConnected(true, IPS_OK);
        p->updateProperties();
    }
}

void EQMod::abnormalDisconnect()
{
    // Ignore disconnect errors
    INDI::Telescope::Disconnect();

    // Set Disconnected
    setConnected(false, IPS_IDLE);
    // Update properties
    updateProperties();

    // Reconnect in 2 seconds
    IEAddTimer(2000, (IE_TCF *)abnormalDisconnectCallback, this);
}

bool EQMod::Disconnect()
{
    if (isConnected())
    {
        try
        {
            mount->Disconnect();
        }
        catch (EQModError &e)
        {
            LOGF_ERROR("Error when disconnecting mount -> %s", e.message);
            return (false);
        }
        return INDI::Telescope::Disconnect();
    }
    else
        return false;
}

void EQMod::TimerHit()
{
    if (isConnected())
    {
        bool rc;

        // Skip reading scope status if we are in a middle of a pulse
        // to avoid delaying it
        if (pulseInProgress != 0)
        {
            rc = true;
        }
        else
        {
            rc = ReadScopeStatus();
        }

        if (rc == false)
        {
            // read was not good
            EqNP.s = IPS_ALERT;
            IDSetNumber(&EqNP, nullptr);
        }

        SetTimer(getCurrentPollingPeriod());
    }
}

bool EQMod::ReadScopeStatus()
{
    // Time
    double juliandate = 0;
    double lst = 0;
    char hrlst[12] = {0};

    const char *datenames[] = { "LST", "JULIANDATE", "UTC" };
    double periods[2];
    const char *periodsnames[] = { "RAPERIOD", "DEPERIOD" };
    double horizvalues[2];
    const char *horiznames[2] = { "AZ", "ALT" };
    double steppervalues[2];
    const char *steppernames[] = { "RAStepsCurrent", "DEStepsCurrent" };

    juliandate = getJulianDate();
    lst        = getLst(juliandate, getLongitude());

    fs_sexa(hrlst, lst, 2, 360000);
    hrlst[11] = '\0';
    DEBUGF(DBG_SCOPE_STATUS, "Compute local time: lst=%2.8f (%s) - julian date=%8.8f", lst, hrlst, juliandate);

    IUUpdateNumber(TimeLSTNP, &lst, (char **)(datenames), 1);
    TimeLSTNP->s = IPS_OK;
    IDSetNumber(TimeLSTNP, nullptr);

    IUUpdateNumber(JulianNP, &juliandate, (char **)(datenames + 1), 1);
    JulianNP->s = IPS_OK;
    IDSetNumber(JulianNP, nullptr);

    try
    {
        TelescopePierSide pierSide;
        currentRAEncoder = mount->GetRAEncoder();
        currentDEEncoder = mount->GetDEEncoder();
        DEBUGF(DBG_SCOPE_STATUS, "Current encoders RA=%ld DE=%ld", static_cast<long>(currentRAEncoder),
               static_cast<long>(currentDEEncoder));
        EncodersToRADec(currentRAEncoder, currentDEEncoder, lst, &currentRA, &currentDEC, &currentHA, &pierSide);
        setPierSide(pierSide);

        alignedRA    = currentRA;
        alignedDEC   = currentDEC;
        ghalignedRA  = currentRA;
        ghalignedDEC = currentDEC;
        bool aligned = false;
#ifdef WITH_ALIGN_GEEHALEL
        if (align)
        {
            align->GetAlignedCoords(syncdata, juliandate, &m_Location, currentRA, currentDEC, &ghalignedRA,
                                    &ghalignedDEC);
            aligned = true;
        }
        //   else
#endif
#ifdef WITH_ALIGN
        // Only use INDI Alignment Subsystem if it is active.
        if (AlignMethodSP.sp[1].s == ISS_ON)
        {
            const char *maligns[3] = { "ZENITH", "NORTH", "SOUTH" };
            INDI::IEquatorialCoordinates RaDec;
            // Use HA/Dec as  telescope coordinate system
            RaDec.rightascension = currentRA;
            RaDec.declination = currentDEC;
            TelescopeDirectionVector TDV = TelescopeDirectionVectorFromEquatorialCoordinates(RaDec);
            DEBUGF(INDI::AlignmentSubsystem::DBG_ALIGNMENT,
                   "Status: Mnt. Algnt. %s Date %lf encoders RA=%ld DE=%ld Telescope RA %lf DEC %lf",
                   maligns[GetApproximateMountAlignment()], juliandate,
                   static_cast<long>(currentRAEncoder), static_cast<long>(currentDEEncoder),
                   currentRA, currentDEC);
            DEBUGF(INDI::AlignmentSubsystem::DBG_ALIGNMENT, " Direction RA(deg.)  %lf DEC %lf TDV(x %lf y %lf z %lf)",
                   RaDec.rightascension, RaDec.declination, TDV.x, TDV.y, TDV.z);
            aligned = true;
            if (!TransformTelescopeToCelestial(TDV, alignedRA, alignedDEC))
            {
                aligned = false;
                DEBUGF(INDI::AlignmentSubsystem::DBG_ALIGNMENT,
                       "Failed TransformTelescopeToCelestial: Scope RA=%g Scope DE=%f, Aligned RA=%f DE=%f", currentRA,
                       currentDEC, alignedRA, alignedDEC);
            }
            else
            {
                DEBUGF(INDI::AlignmentSubsystem::DBG_ALIGNMENT,
                       "TransformTelescopeToCelestial: Scope RA=%f Scope DE=%f, Aligned RA=%f DE=%f", currentRA, currentDEC,
                       alignedRA, alignedDEC);
            }
        }
#endif
        if (!aligned && (syncdata.lst != 0.0))
        {
            DEBUGF(DBG_SCOPE_STATUS, "Aligning with last sync delta RA %g DE %g", syncdata.deltaRA, syncdata.deltaDEC);
            // should check values are in range!
            alignedRA += syncdata.deltaRA;
            alignedDEC += syncdata.deltaDEC;
            if (alignedDEC > 90.0 || alignedDEC < -90.0)
            {
                alignedRA += 12.00;
                if (alignedDEC > 0.0)
                    alignedDEC = 180.0 - alignedDEC;
                else
                    alignedDEC = -180.0 - alignedDEC;
            }
            alignedRA = range24(alignedRA);
        }

#if defined WITH_ALIGN_GEEHALEL && !defined WITH_ALIGN
        alignedRA  = ghalignedRA;
        alignedDEC = ghalignedDEC;
#endif
#if defined WITH_ALIGN_GEEHALEL && defined WITH_ALIGN
        if (AlignMethodSP.sp[0].s == ISS_ON)
        {
            alignedRA  = ghalignedRA;
            alignedDEC = ghalignedDEC;
        }
#endif

        lnradec.rightascension  = alignedRA;
        lnradec.declination = alignedDEC;
        // Only update Alt/Az if the scope is not idle.
        if (TrackState != SCOPE_IDLE && TrackState != SCOPE_PARKED)
        {
            /* uses sidereal time, not local sidereal time */
            INDI::EquatorialToHorizontal(&lnradec, &m_Location, juliandate, &lnaltaz);
            horizvalues[0] = lnaltaz.azimuth;
            horizvalues[1] = lnaltaz.altitude;
            IUUpdateNumber(HorizontalCoordNP, horizvalues, (char **)horiznames, 2);
            IDSetNumber(HorizontalCoordNP, nullptr);
        }

        steppervalues[0] = currentRAEncoder;
        steppervalues[1] = currentDEEncoder;
        IUUpdateNumber(CurrentSteppersNP, steppervalues, (char **)steppernames, 2);
        IDSetNumber(CurrentSteppersNP, nullptr);

        mount->GetRAMotorStatus(RAStatusLP);
        mount->GetDEMotorStatus(DEStatusLP);
        IDSetLight(RAStatusLP, nullptr);
        IDSetLight(DEStatusLP, nullptr);

        periods[0] = mount->GetRAPeriod();
        periods[1] = mount->GetDEPeriod();
        IUUpdateNumber(PeriodsNP, periods, (char **)periodsnames, 2);
        IDSetNumber(PeriodsNP, nullptr);

        // Log all coords
        {
            char CurrentRAString[64] = {0}, CurrentDEString[64] = {0},
                                       AlignedRAString[64] = {0}, AlignedDEString[64] = {0},
                                               AZString[64] = {0}, ALString[64] = {0};
            fs_sexa(CurrentRAString, currentRA, 2, 3600);
            fs_sexa(CurrentDEString, currentDEC, 2, 3600);
            fs_sexa(AlignedRAString, alignedRA, 2, 3600);
            fs_sexa(AlignedDEString, alignedDEC, 2, 3600);
            fs_sexa(AZString, horizvalues[0], 2, 3600);
            fs_sexa(ALString, horizvalues[1], 2, 3600);

            LOGF_DEBUG("Scope RA (%s) DE (%s) Aligned RA (%s) DE (%s) AZ (%s) ALT (%s), PierSide (%s)",
                       CurrentRAString,
                       CurrentDEString,
                       AlignedRAString,
                       AlignedDEString,
                       AZString,
                       ALString,
                       pierSide == PIER_EAST ? "East" : (pierSide == PIER_WEST ? "West" : "Unknown"));
        }

        if (mount->HasAuxEncoders())
        {
            double auxencodervalues[2];
            const char *auxencodernames[] = { "AUXENCRASteps", "AUXENCDESteps" };
            auxencodervalues[0]           = mount->GetRAAuxEncoder();
            auxencodervalues[1]           = mount->GetDEAuxEncoder();
            IUUpdateNumber(AuxEncoderNP, auxencodervalues, (char **)auxencodernames, 2);
            IDSetNumber(AuxEncoderNP, nullptr);
        }

        if (gotoInProgress())
        {
            if (!(mount->IsRARunning()) && !(mount->IsDERunning()))
            {
                // Goto iteration
                gotoparams.iterative_count += 1;
                LOGF_INFO(
                    "Iterative Goto (%d): RA diff = %4.2f arcsecs DE diff = %4.2f arcsecs",
                    gotoparams.iterative_count, 3600 * fabs(gotoparams.ratarget - currentRA),
                    3600 * fabs(gotoparams.detarget - currentDEC));
                if ((gotoparams.iterative_count <= GOTO_ITERATIVE_LIMIT) &&
                        (((3600 * fabs(gotoparams.ratarget - currentRA)) > RAGOTORESOLUTION) ||
                         ((3600 * fabs(gotoparams.detarget - currentDEC)) > DEGOTORESOLUTION)))
                {
                    gotoparams.racurrent        = currentRA;
                    gotoparams.decurrent        = currentDEC;
                    gotoparams.racurrentencoder = currentRAEncoder;
                    gotoparams.decurrentencoder = currentDEEncoder;
                    EncoderTarget(&gotoparams);
                    // Start iterative slewing
                    LOGF_INFO(
                        "Iterative goto (%d): slew mount to RA increment = %d, DE increment = %d",
                        gotoparams.iterative_count, static_cast<int>(gotoparams.ratargetencoder - gotoparams.racurrentencoder),
                        static_cast<int>(gotoparams.detargetencoder - gotoparams.decurrentencoder));
                    mount->SlewTo(static_cast<int>(gotoparams.ratargetencoder - gotoparams.racurrentencoder),
                                  static_cast<int>(gotoparams.detargetencoder - gotoparams.decurrentencoder));
                }
                else
                {
                    ISwitch *sw;
                    sw = IUFindSwitch(&CoordSP, "TRACK");
                    if ((gotoparams.iterative_count > GOTO_ITERATIVE_LIMIT) &&
                            (((3600 * fabs(gotoparams.ratarget - currentRA)) > RAGOTORESOLUTION) ||
                             ((3600 * fabs(gotoparams.detarget - currentDEC)) > DEGOTORESOLUTION)))
                    {
                        LOGF_INFO(
                            "Iterative Goto Limit reached (%d iterations): RA diff = %4.2f arcsecs DE diff = %4.2f "
                            "arcsecs",
                            gotoparams.iterative_count, 3600 * fabs(gotoparams.ratarget - currentRA),
                            3600 * fabs(gotoparams.detarget - currentDEC));
                    }

                    // For AstroEQ (needs an explicit :G command at the end of gotos)
                    mount->ResetMotions();

                    if ((RememberTrackState == SCOPE_TRACKING) || ((sw != nullptr) && (sw->s == ISS_ON)))
                    {
                        char *name;

                        if (RememberTrackState == SCOPE_TRACKING)
                        {
                            sw   = IUFindOnSwitch(&TrackModeSP);
                            name = sw->name;
                            mount->StartRATracking(GetRATrackRate());
                            mount->StartDETracking(GetDETrackRate());
                        }
                        else
                        {
                            sw    = IUFindOnSwitch(TrackDefaultSP);
                            name  = sw->name;
                            mount->StartRATracking(GetDefaultRATrackRate());
                            mount->StartDETracking(GetDefaultDETrackRate());

#if 0
                            IUResetSwitch(TrackModeSP);
                            IUUpdateSwitch(TrackModeSP, &state, &name, 1);
                            TrackModeSP->s = IPS_BUSY;
                            IDSetSwitch(TrackModeSP, nullptr);
#endif
                        }

                        TrackState = SCOPE_TRACKING;
                        RememberTrackState = TrackState;

#if 0
                        TrackModeSP->s = IPS_BUSY;
                        IDSetSwitch(TrackModeSP, nullptr);
#endif
                        LOGF_INFO("Telescope slew is complete. Tracking %s...", name);
                    }
                    else
                    {
                        TrackState = SCOPE_IDLE;
                        RememberTrackState = TrackState;
                        LOG_INFO("Telescope slew is complete. Stopping...");
                    }
                    gotoparams.completed = true;
                    //EqNP.s               = IPS_OK;
                }
            }
        }

#ifdef WITH_SCOPE_LIMITS
        if (horizon)
        {
            if (horizon->checkLimits(horizvalues[0], horizvalues[1], TrackState, gotoInProgress()))
                Abort();
        }
#endif

        if (TrackState == SCOPE_PARKING)
        {
            if (!(mount->IsRARunning()) && !(mount->IsDERunning()))
            {
                SetParked(true);
            }
        }

        if (mount->HasPPEC())
        {
            if (PPECTrainingSP->s == IPS_BUSY)
            {
                bool intraining, inppec;
                mount->GetPPECStatus(&intraining, &inppec);
                if (!(intraining))
                {
                    LOG_INFO("PPEC Training completed.");
                    PPECTrainingSP->sp[0].s = ISS_ON;
                    PPECTrainingSP->sp[1].s = ISS_OFF;
                    PPECTrainingSP->s       = IPS_IDLE;
                    IDSetSwitch(PPECTrainingSP, nullptr);
                }
            }
        }

        if (AutohomeState == AUTO_HOME_CONFIRM)
        {
            if (ah_confirm_timeout > 0)
                ah_confirm_timeout -= 1;
            if (ah_confirm_timeout == 0)
            {
                AutohomeState = AUTO_HOME_IDLE;
                LOG_INFO("Autohome confirm timeout.");
            }
        }

        if (TrackState == SCOPE_AUTOHOMING)
        {
            uint32_t indexRA = 0, indexDE = 0;

            LOGF_DEBUG("Autohoming status: %d", AutohomeState);
            switch (AutohomeState)
            {
                case AUTO_HOME_IDLE:
                case AUTO_HOME_CONFIRM:
                    AutohomeState = AUTO_HOME_IDLE;
                    TrackState    = SCOPE_IDLE;
                    RememberTrackState = TrackState;
                    LOG_INFO("Invalid status while Autohoming. Aborting");
                    break;
                case AUTO_HOME_WAIT_PHASE1:
                    if (!(mount->IsRARunning()) && !(mount->IsDERunning()))
                    {
                        LOG_INFO("Autohome phase 1: end");
                        LOG_INFO(
                            "AutoHome phase 2: reading home position indexes for extra moves");
                        mount->GetRAIndexer();
                        mount->GetDEIndexer();
                        uint32_t raindex = mount->GetlastreadRAIndexer();
                        uint32_t deindex = mount->GetlastreadDEIndexer();
                        LOGF_INFO(
                            "AutoHome phase 2: read home position indexes: RA=0x%x DE=0x%x", raindex, deindex);
                        if (raindex == 0 || raindex == 0xFFFFFF)
                            ah_bIndexChanged_RA = false;
                        else
                            ah_bIndexChanged_RA = true;
                        if (deindex == 0 || deindex == 0xFFFFFF)
                            ah_bIndexChanged_DE = false;
                        else
                            ah_bIndexChanged_DE = true;
                        if (ah_bIndexChanged_RA)
                        {
                            LOGF_INFO(
                                "AutoHome phase 2: RA home index changed RA=0x%x, slewing again", raindex);
                            ah_iPosition_RA = mount->GetRAEncoder();
                            ah_iChanges     = (5 * mount->GetRAEncoderTotal()) / 360;
                            if (ah_bSlewingUp_RA)
                                ah_iPosition_RA = ah_iPosition_RA - ah_iChanges;
                            else
                                ah_iPosition_RA = ah_iPosition_RA + ah_iChanges;
                        }
                        if (ah_bIndexChanged_DE)
                        {
                            LOGF_INFO(
                                "AutoHome phase 2: DE home index changed DE=0x%x, slewing again", deindex);
                            ah_iPosition_DE = mount->GetDEEncoder();
                            ah_iChanges     = (5 * mount->GetDEEncoderTotal()) / 360;
                            if (ah_bSlewingUp_DE)
                                ah_iPosition_DE = ah_iPosition_DE - ah_iChanges;
                            else
                                ah_iPosition_DE = ah_iPosition_DE + ah_iChanges;
                        }
                        if ((ah_bIndexChanged_RA) || (ah_bIndexChanged_DE))
                        {
                            LOGF_INFO(
                                "AutoHome phase 2: slewing to RA=0x%x (up=%c) DE=0x%x (up=%c)", ah_iPosition_RA,
                                (ah_bSlewingUp_RA ? '1' : '0'), ah_iPosition_DE, (ah_bSlewingUp_DE ? '1' : '0'));
                            mount->AbsSlewTo(ah_iPosition_RA, ah_iPosition_DE, ah_bSlewingUp_RA, ah_bSlewingUp_DE);
                            LOG_INFO(
                                "Autohome phase 2: start slewing, waiting for motors to stop");
                        }
                        else
                        {
                            LOG_INFO("Autohome phase 2: nothing to do");
                        }
                        AutohomeState = AUTO_HOME_WAIT_PHASE2;
                    }
                    else
                    {
                        LOG_DEBUG("Autohome phase 1: Waiting for motors to stop");
                    }
                    break;
                case AUTO_HOME_WAIT_PHASE2:
                    if (!(mount->IsRARunning()) && !(mount->IsDERunning()))
                    {
                        LOG_INFO("Autohome phase 2: end");
                        LOG_INFO("AutoHome phase 3: resetting home position indexes");
                        if (ah_bIndexChanged_RA)
                        {
                            uint32_t raindex = mount->GetlastreadRAIndexer();
                            mount->ResetRAIndexer();
                            mount->GetRAIndexer();
                            LOGF_INFO(
                                "AutoHome phase 3: resetting RA home index: 0x%x (was 0x%x)",
                                mount->GetlastreadRAIndexer(), raindex);
                        }
                        if (ah_bIndexChanged_DE)
                        {
                            uint32_t deindex = mount->GetlastreadDEIndexer();
                            mount->ResetDEIndexer();
                            mount->GetDEIndexer();
                            LOGF_INFO(
                                "AutoHome phase 3: resetting DE home index: 0x%x (was 0x%x)",
                                mount->GetlastreadDEIndexer(), deindex);
                        }
                        LOG_INFO(
                            "AutoHome phase 3: reading home position indexes to update directions");
                        if (ah_bIndexChanged_RA)
                        {
                            mount->GetRAIndexer();
                            if (mount->GetlastreadRAIndexer() == 0)
                                ah_bSlewingUp_RA = false;
                            else
                                ah_bSlewingUp_RA = true;
                            LOGF_INFO(
                                "AutoHome phase 3: reading RA home position index: RA=0x%x up=%c",
                                mount->GetlastreadRAIndexer(), (ah_bSlewingUp_RA ? '1' : '0'));
                        }
                        if (ah_bIndexChanged_DE)
                        {
                            mount->GetDEIndexer();
                            if (mount->GetlastreadDEIndexer() == 0)
                                ah_bSlewingUp_DE = false;
                            else
                                ah_bSlewingUp_DE = true;
                            LOGF_INFO(
                                "AutoHome phase 3: reading DE home position index: DE=0x%x up=%c",
                                mount->GetlastreadDEIndexer(), (ah_bSlewingUp_DE ? '1' : '0'));
                        }

                        if (!ah_bSlewingUp_RA)
                        {
                            LOG_INFO(
                                "AutoHome phase 3: starting RA negative slewing, waiting RA home indexer");
                            ah_waitRA = -1;
                            mount->SlewRA(-800.0);
                        }
                        if (!ah_bSlewingUp_DE)
                        {
                            LOG_INFO(
                                "AutoHome phase 3: starting DE negative slewing, waiting DE home indexer");
                            ah_waitDE = -1;
                            mount->SlewDE(-800.0);
                        }
                        AutohomeState = AUTO_HOME_WAIT_PHASE3;
                    }
                    else
                    {
                        LOG_DEBUG("Autohome phase 2: Waiting for motors to stop");
                    }
                    break;
                case AUTO_HOME_WAIT_PHASE3:
                    if (mount->IsRARunning())
                    {
                        if (ah_waitRA < 0)
                        {
                            mount->GetRAIndexer();
                            if ((indexRA = mount->GetlastreadRAIndexer()) != 0xFFFFFF)
                            {
                                ah_waitRA = 3000 / getCurrentPollingPeriod();
                                LOGF_INFO(
                                    "Autohome phase 3: detected RA Index changed, waiting %d poll periods",
                                    ah_waitRA);
                            }
                        }
                        else
                            ah_waitRA -= 1;
                        if (ah_waitRA == 0)
                        {
                            LOG_INFO("Autohome phase 3: stopping RA");
                            mount->StopRA();
                        }
                    }
                    if (mount->IsDERunning())
                    {
                        if (ah_waitDE < 0)
                        {
                            mount->GetDEIndexer();
                            if ((indexDE = mount->GetlastreadDEIndexer()) != 0xFFFFFF)
                            {
                                ah_waitDE = 3000 / getCurrentPollingPeriod();
                                LOGF_INFO(
                                    "Autohome phase 3: detected DE Index changed, waiting %d poll periods",
                                    ah_waitDE);
                            }
                        }
                        else
                            ah_waitDE -= 1;
                        if (ah_waitDE == 0)
                        {
                            LOG_INFO("Autohome phase 3: stopping DE");
                            mount->StopDE();
                        }
                    }
                    if (!(mount->IsRARunning()) && !(mount->IsDERunning()))
                    {
                        if (!ah_bSlewingUp_RA)
                        {
                            mount->ResetRAIndexer();
                            mount->GetRAIndexer();
                            LOGF_INFO(
                                "AutoHome phase 3: resetting RA home index: 0x%x (was 0x%x)",
                                mount->GetlastreadRAIndexer(), indexRA);
                            ah_bSlewingUp_RA = true;
                        }
                        if (!ah_bSlewingUp_DE)
                        {
                            mount->ResetDEIndexer();
                            mount->GetDEIndexer();
                            LOGF_INFO(
                                "AutoHome phase 3: resetting DE home index: 0x%x (was 0x%x)",
                                mount->GetlastreadDEIndexer(), indexDE);
                            ah_bSlewingUp_DE = true;
                        }
                        LOG_INFO("Autohome phase 3: end");
                        LOG_INFO("Autohome phase 4: *** find the home position index ***");
                        LOG_INFO(
                            "AutoHome phase 4: starting RA positive slewing, waiting RA home indexer");
                        ah_waitRA           = -1;
                        ah_bIndexChanged_RA = false;
                        mount->SlewRA(400.0);

                        LOG_INFO(
                            "AutoHome phase 4: starting DE positive slewing, waiting DE home indexer");
                        ah_waitDE = -1;
                        mount->SlewDE(400.0);
                        ah_bIndexChanged_DE = false;
                        AutohomeState       = AUTO_HOME_WAIT_PHASE4;
                    }
                    break;
                case AUTO_HOME_WAIT_PHASE4:
                    if (!ah_bIndexChanged_RA)
                    {
                        mount->GetRAIndexer();
                        ah_iPosition_RA = mount->GetlastreadRAIndexer();
                        if (ah_iPosition_RA != 0)
                        {
                            ah_bIndexChanged_RA      = true;
                            ah_sHomeIndexPosition_RA = ah_iPosition_RA;
                            LOGF_INFO(
                                "Autohome phase 4: detected RA Home index: 0x%x, stopping motor", ah_iPosition_RA);
                            mount->StopRA();
                        }
                    }
                    if (!ah_bIndexChanged_DE)
                    {
                        mount->GetDEIndexer();
                        ah_iPosition_DE = mount->GetlastreadDEIndexer();
                        if (ah_iPosition_DE != 0)
                        {
                            ah_bIndexChanged_DE      = true;
                            ah_sHomeIndexPosition_DE = ah_iPosition_DE;
                            LOGF_INFO(
                                "Autohome phase 4: detected DE Home index: 0x%x, stopping motor", ah_iPosition_DE);
                            mount->StopDE();
                        }
                    }
                    if (!(mount->IsRARunning()) && !(mount->IsDERunning()))
                    {
                        LOG_INFO("Autohome phase 4: end");
                        LOG_INFO("Autohome phase 5: Moving back 10 deg.");
                        ah_iChanges     = (10 * mount->GetRAEncoderTotal()) / 360;
                        ah_iPosition_RA = ah_iPosition_RA - ah_iChanges;
                        ah_iChanges     = (10 * mount->GetDEEncoderTotal()) / 360;
                        ah_iPosition_DE = ah_iPosition_DE - ah_iChanges;
                        LOGF_INFO(
                            "AutoHome phase 5: slewing to RA=0x%x (up=%c) DE=0x%x (up=%c)", ah_iPosition_RA, '0',
                            ah_iPosition_DE, '0');
                        mount->AbsSlewTo(ah_iPosition_RA, ah_iPosition_DE, false, false);
                        AutohomeState = AUTO_HOME_WAIT_PHASE5;
                    }
                    break;
                case AUTO_HOME_WAIT_PHASE5:
                    if (!(mount->IsRARunning()) && !(mount->IsDERunning()))
                    {
                        LOG_INFO("Autohome phase 5: end");
                        LOG_INFO("Autohome phase 6: Goto Home Position");
                        LOGF_INFO(
                            "AutoHome phase 6: slewing to RA=0x%x (up=%c) DE=0x%x (up=%c)", ah_sHomeIndexPosition_RA,
                            '1', ah_sHomeIndexPosition_DE, '1');
                        mount->AbsSlewTo(ah_sHomeIndexPosition_RA, ah_sHomeIndexPosition_DE, true, true);
                        AutohomeState = AUTO_HOME_WAIT_PHASE6;
                    }
                    else
                    {
                        LOG_DEBUG("Autohome phase 5: Waiting for motors to stop");
                    }
                    break;
                case AUTO_HOME_WAIT_PHASE6:
                    if (!(mount->IsRARunning()) && !(mount->IsDERunning()))
                    {
                        LOG_INFO("Autohome phase 6: end");
                        LOGF_INFO("AutoHome phase 6: Mount at RA=0x%x DE=0x%x",
                                  mount->GetRAEncoder(), mount->GetDEEncoder());
                        LOGF_INFO(
                            "Autohome: Mount at Home Position, setting encoders RA=0x%x DE=0X%x",
                            mount->GetRAEncoderHome(), mount->GetDEEncoderHome());
                        mount->SetRAAxisPosition(mount->GetRAEncoderHome());
                        mount->SetDEAxisPosition(mount->GetDEEncoderHome());
                        TrackState    = SCOPE_IDLE;
                        RememberTrackState = TrackState;
                        AutohomeState = AUTO_HOME_IDLE;
                        AutoHomeSP->s = IPS_IDLE;
                        IUResetSwitch(AutoHomeSP);
                        IDSetSwitch(AutoHomeSP, nullptr);
                        LOG_INFO("Autohome: end");
                    }
                    else
                    {
                        LOG_DEBUG("Autohome phase 6: Waiting for motors to stop");
                    }
                    break;
                default:
                    LOGF_WARN("Unknown Autohome status %d: aborting", AutohomeState);
                    Abort();
                    break;
            }
        }
    }
    catch (EQModError &e)
    {
        return (e.DefaultHandleException(this));
    }

    // This should be kept last so that any TRACK_STATE
    // change are reflected in EQNP property in INDI::Telescope

    NewRaDec(alignedRA, alignedDEC);
    return true;
}

void EQMod::EncodersToRADec(uint32_t rastep, uint32_t destep, double lst, double *ra, double *de, double *ha,
                            TelescopePierSide *pierSide)
{
    double RACurrent = 0.0, DECurrent = 0.0, HACurrent = 0.0;
    TelescopePierSide p;
    HACurrent = EncoderToHours(rastep, zeroRAEncoder, totalRAEncoder, Hemisphere);
    RACurrent = HACurrent + lst;
    DECurrent = EncoderToDegrees(destep, zeroDEEncoder, totalDEEncoder, Hemisphere);
    //IDLog("EncodersToRADec: destep=%6X zeroDEncoder=%6X totalDEEncoder=%6x DECurrent=%f\n", destep, zeroDEEncoder , totalDEEncoder, DECurrent);
    if (Hemisphere == NORTH)
    {
        if ((DECurrent > 90.0) && (DECurrent <= 270.0))
        {
            RACurrent = RACurrent - 12.0;
            p = PIER_EAST;
        }
        else
            p = PIER_WEST;
    }
    else if ((DECurrent <= 90.0) || (DECurrent > 270.0))
    {
        RACurrent = RACurrent + 12.0;
        //currentPierSide = EAST;
        p = PIER_EAST;
    }
    else
        p = PIER_WEST;
    //currentPierSide = WEST;
    HACurrent = rangeHA(HACurrent);
    RACurrent = range24(RACurrent);
    DECurrent = rangeDec(DECurrent);
    *ra       = RACurrent;
    *de       = DECurrent;
    if (ha)
        *ha = HACurrent;
    if (pierSide)
        *pierSide = p;
}

double EQMod::EncoderToHours(uint32_t step, uint32_t initstep, uint32_t totalstep, enum Hemisphere h)
{
    double result = 0.0;
    if (step > initstep)
    {
        result = (static_cast<double>(step - initstep) / totalstep) * 24.0;
        result = 24.0 - result;
    }
    else
    {
        result = (static_cast<double>(initstep - step) / totalstep) * 24.0;
    }

    if (h == NORTH)
        result = range24(result + 6.0);
    else
        result = range24((24 - result) + 6.0);
    return result;
}

double EQMod::EncoderToDegrees(uint32_t step, uint32_t initstep, uint32_t totalstep, enum Hemisphere h)
{
    double result = 0.0;
    if (step > initstep)
    {
        result = (static_cast<double>(step - initstep) / totalstep) * 360.0;
    }
    else
    {
        result = (static_cast<double>(initstep - step) / totalstep) * 360.0;
        result = 360.0 - result;
    }
    //IDLog("EncodersToDegrees: step=%6X initstep=%6x result=%f hemisphere %s \n", step, initstep, result, (h==NORTH?"North":"South"));
    if (h == NORTH)
        result = range360(result);
    else
        result = range360(360.0 - result);
    //IDLog("EncodersToDegrees: returning result=%f\n", result);

    return result;
}

double EQMod::EncoderFromHour(double hour, uint32_t initstep, uint32_t totalstep, enum Hemisphere h)
{
    double shifthour = 0.0;
    shifthour        = range24(hour - 6);
    if (h == NORTH)
        if (shifthour < 12.0)
            return round(initstep - ((shifthour / 24.0) * totalstep));
        else
            return round(initstep + (((24.0 - shifthour) / 24.0) * totalstep));
    else if (shifthour < 12.0)
        return round(initstep + ((shifthour / 24.0) * totalstep));
    else
        return round(initstep - (((24.0 - shifthour) / 24.0) * totalstep));
}

double EQMod::EncoderFromRA(double ratarget, TelescopePierSide p, double lst, uint32_t initstep,
                            uint32_t totalstep, enum Hemisphere h)
{
    double ha = 0.0;
    ha        = ratarget - lst;

    //    if ((h == NORTH && p == PIER_EAST) || (h == SOUTH && p == PIER_WEST))
    if (p == PIER_EAST)
        ha = ha + 12.0;

    ha = range24(ha);
    return EncoderFromHour(ha, initstep, totalstep, h);
}

double EQMod::EncoderFromDegree(double degree, uint32_t initstep, uint32_t totalstep, enum Hemisphere h)
{
    double target = 0.0;
    target        = range360(degree);
    if (h == SOUTH)
        target = 360.0 - target;
    if (target > 270.0)
        target -= 360.0;
    return round(initstep + ((target / 360.0) * totalstep));
}

double EQMod::EncoderFromDec(double detarget, TelescopePierSide p, uint32_t initstep, uint32_t totalstep,
                             enum Hemisphere h)
{
    if ((h == NORTH && p == PIER_EAST) || (h == SOUTH && p == PIER_WEST))
        detarget = 180.0 - detarget;
    return EncoderFromDegree(detarget, initstep, totalstep, h);
}

void EQMod::SetSouthernHemisphere(bool southern)
{
    const char *hemispherenames[] = { "NORTH", "SOUTH" };
    ISState hemispherevalues[2];
    LOGF_DEBUG("Set southern %s", (southern ? "true" : "false"));
    if (southern)
        Hemisphere = SOUTH;
    else
        Hemisphere = NORTH;
    RAInverted = (Hemisphere == SOUTH);
    UpdateDEInverted();
    if (Hemisphere == NORTH)
    {
        hemispherevalues[0] = ISS_ON;
        hemispherevalues[1] = ISS_OFF;
        IUUpdateSwitch(HemisphereSP, hemispherevalues, (char **)hemispherenames, 2);
    }
    else
    {
        hemispherevalues[0] = ISS_OFF;
        hemispherevalues[1] = ISS_ON;
        IUUpdateSwitch(HemisphereSP, hemispherevalues, (char **)hemispherenames, 2);
    }
    HemisphereSP->s = IPS_IDLE;
    IDSetSwitch(HemisphereSP, nullptr);
}

void EQMod::UpdateDEInverted()
{
    bool prev = DEInverted;
    DEInverted = (Hemisphere == SOUTH) ^ (ReverseDECSP->sp[0].s == ISS_ON);
    if (DEInverted != prev)
        LOGF_DEBUG("Set DEInverted %s", DEInverted ? "true" : "false");
}

void EQMod::EncoderTarget(GotoParams *g)
{
    double r, d;
    double ha = 0.0;
    double juliandate;
    double lst;
    uint32_t targetraencoder = 0, targetdecencoder = 0;
    bool outsidelimits = false;
    r                  = g->ratarget;
    d                  = g->detarget;

    juliandate = getJulianDate();
    lst        = getLst(juliandate, getLongitude());

    if (g->pier_side == PIER_UNKNOWN)
    {
        // decide pier side and keep it consistent in iterative calls
        ha = rangeHA(r - lst);
        if (ha < 0.0)
        {
            // target WEST
            g->pier_side = PIER_EAST;
        }
        else
        {
            g->pier_side = PIER_WEST;
        }
    }

    targetraencoder  = EncoderFromRA(r, g->pier_side, lst, zeroRAEncoder, totalRAEncoder, Hemisphere);
    targetdecencoder = EncoderFromDec(d, g->pier_side, zeroDEEncoder, totalDEEncoder, Hemisphere);

    if (g->checklimits)
    {
        if (Hemisphere == NORTH)
        {
            assert(g->limiteast <= g->limitwest);
            if ((targetraencoder < g->limiteast) || (targetraencoder > g->limitwest))
                outsidelimits = true;
        }
        else
        {
            assert(g->limiteast >= g->limitwest);
            if ((targetraencoder > g->limiteast) || (targetraencoder < g->limitwest))
                outsidelimits = true;
        }
    }
    g->outsidelimits   = outsidelimits;
    g->ratargetencoder = targetraencoder;
    g->detargetencoder = targetdecencoder;
}

double EQMod::GetRATrackRate()
{
    double rate = 0.0;
    ISwitch *sw;
    sw = IUFindOnSwitch(&TrackModeSP);
    if (!sw)
        return 0.0;
    if (!strcmp(sw->name, "TRACK_SIDEREAL"))
    {
        rate = TRACKRATE_SIDEREAL;
    }
    else if (!strcmp(sw->name, "TRACK_LUNAR"))
    {
        rate = TRACKRATE_LUNAR;
    }
    else if (!strcmp(sw->name, "TRACK_SOLAR"))
    {
        rate = TRACKRATE_SOLAR;
    }
    else if (!strcmp(sw->name, "TRACK_CUSTOM"))
    {
        rate = IUFindNumber(&TrackRateNP, "TRACK_RATE_RA")->value;
    }
    else
        return 0.0;
    if (RAInverted)
        rate = -rate;
    return rate;
}

double EQMod::GetDETrackRate()
{
    double rate = 0.0;
    ISwitch *sw;
    sw = IUFindOnSwitch(&TrackModeSP);
    if (!sw)
        return 0.0;
    if (!strcmp(sw->name, "TRACK_SIDEREAL"))
    {
        rate = 0.0;
    }
    else if (!strcmp(sw->name, "TRACK_LUNAR"))
    {
        rate = 0.0;
    }
    else if (!strcmp(sw->name, "TRACK_SOLAR"))
    {
        rate = 0.0;
    }
    else if (!strcmp(sw->name, "TRACK_CUSTOM"))
    {
        rate = IUFindNumber(&TrackRateNP, "TRACK_RATE_DE")->value;
    }
    else
        return 0.0;
    if (DEInverted)
        rate = -rate;
    return rate;
}

double EQMod::GetDefaultRATrackRate()
{
    double rate = 0.0;
    ISwitch *sw;
    sw = IUFindOnSwitch(TrackDefaultSP);
    if (!sw)
        return 0.0;
    if (!strcmp(sw->name, "TRACK_SIDEREAL"))
    {
        rate = TRACKRATE_SIDEREAL;
    }
    else if (!strcmp(sw->name, "TRACK_LUNAR"))
    {
        rate = TRACKRATE_LUNAR;
    }
    else if (!strcmp(sw->name, "TRACK_SOLAR"))
    {
        rate = TRACKRATE_SOLAR;
    }
    else if (!strcmp(sw->name, "TRACK_CUSTOM"))
    {
        rate = IUFindNumber(&TrackRateNP, "TRACK_RATE_RA")->value;
    }
    else
        return 0.0;
    if (RAInverted)
        rate = -rate;
    return rate;
}

double EQMod::GetDefaultDETrackRate()
{
    double rate = 0.0;
    ISwitch *sw;
    sw = IUFindOnSwitch(TrackDefaultSP);
    if (!sw)
        return 0.0;
    if (!strcmp(sw->name, "TRACK_SIDEREAL"))
    {
        rate = 0.0;
    }
    else if (!strcmp(sw->name, "TRACK_LUNAR"))
    {
        rate = 0.0;
    }
    else if (!strcmp(sw->name, "TRACK_SOLAR"))
    {
        rate = 0.0;
    }
    else if (!strcmp(sw->name, "TRACK_CUSTOM"))
    {
        rate = IUFindNumber(&TrackRateNP, "TRACK_RATE_DE")->value;
    }
    else
        return 0.0;
    if (DEInverted)
        rate = -rate;
    return rate;
}

bool EQMod::gotoInProgress()
{
    return (!gotoparams.completed);
}

bool EQMod::Goto(double r, double d)
{
    double juliandate;
#ifdef WITH_SCOPE_LIMITS
    INDI::IEquatorialCoordinates gotoradec;
    INDI::IHorizontalCoordinates gotoaltaz;
    double gotoaz;
    double gotoalt;
#endif

    if ((TrackState == SCOPE_SLEWING) || (TrackState == SCOPE_PARKING) || (TrackState == SCOPE_PARKED))
    {
        LOG_WARN("Can not perform goto while goto/park in progress, or scope parked.");
        //        EqNP.s = IPS_IDLE;
        //        IDSetNumber(&EqNP, nullptr);
        //        return true;
        return false;
    }

    juliandate = getJulianDate();

#ifdef WITH_SCOPE_LIMITS
    gotoradec.rightascension  = r;
    gotoradec.declination = d;
    INDI::EquatorialToHorizontal(&gotoradec, &m_Location, juliandate, &gotoaltaz);
    gotoaz  = gotoaltaz.azimuth;
    gotoalt = gotoaltaz.altitude;
    if (horizon)
    {
        if (!horizon->inGotoLimits(gotoaz, gotoalt))
        {
            LOG_WARN("Goto outside Horizon Limits.");
            //            EqNP.s = IPS_IDLE;
            //            IDSetNumber(&EqNP, nullptr);
            //            return true;
            return false;
        }
    }
#endif

    LOGF_INFO("Starting Goto RA=%g DE=%g (current RA=%g DE=%g)", r, d, currentRA, currentDEC);
    targetRA  = r;
    targetDEC = d;
    char RAStr[64], DecStr[64];

    // Compute encoder targets and check RA limits if forced
    bzero(&gotoparams, sizeof(gotoparams));
    gotoparams.ratarget  = r;
    gotoparams.detarget  = d;
    gotoparams.racurrent = currentRA;
    gotoparams.decurrent = currentDEC;
    bool aligned         = false;
#ifdef WITH_ALIGN_GEEHALEL
    double ghratarget = r, ghdetarget = d;
    if (AlignMethodSP.sp[0].s == ISS_ON)
    {
        aligned = true;
        if (align)
        {
            align->AlignGoto(syncdata, juliandate, &m_Location, &ghratarget, &ghdetarget);
            LOGF_INFO("Aligned Eqmod Goto RA=%g DE=%g (target RA=%g DE=%g)", ghratarget, ghdetarget,
                      r, d);
        }
        else
        {
            if (syncdata.lst != 0.0)
            {
                ghratarget = gotoparams.ratarget - syncdata.deltaRA;
                ghdetarget = gotoparams.detarget - syncdata.deltaDEC;
                LOGF_INFO("Failed Eqmod Goto RA=%g DE=%g (target RA=%g DE=%g)", ghratarget,
                          ghdetarget, r, d);
            }
        }
    }
#endif
#ifdef WITH_ALIGN
    if (AlignMethodSP.sp[1].s == ISS_ON)
    {
        TelescopeDirectionVector TDV;
        aligned = true;
        if (!TransformCelestialToTelescope(r, d, 0.0, TDV))
        {
            DEBUGF(INDI::AlignmentSubsystem::DBG_ALIGNMENT,
                   "Failed TransformCelestialToTelescope:  RA=%lf DE=%lf, Goto RA=%lf DE=%lf", r, d, gotoparams.ratarget,
                   gotoparams.detarget);
            if (syncdata.lst != 0.0)
            {
                gotoparams.ratarget -= syncdata.deltaRA;
                gotoparams.detarget -= syncdata.deltaDEC;
            }
        }
        else
        {
            INDI::IEquatorialCoordinates RaDec;
            EquatorialCoordinatesFromTelescopeDirectionVector(TDV, RaDec);
            DEBUGF(INDI::AlignmentSubsystem::DBG_ALIGNMENT,
                   "TransformCelestialToTelescope: RA=%lf DE=%lf, TDV (x :%lf, y: %lf, z: %lf), local hour RA %lf DEC %lf",
                   r, d, TDV.x, TDV.y, TDV.z, RaDec.rightascension, RaDec.declination);
            gotoparams.ratarget = RaDec.rightascension;
            gotoparams.detarget = RaDec.declination;
            DEBUGF(INDI::AlignmentSubsystem::DBG_ALIGNMENT,
                   "TransformCelestialToTelescope: RA=%lf DE=%lf, Goto RA=%lf DE=%lf", r, d, gotoparams.ratarget,
                   gotoparams.detarget);
        }
    }
#endif

    if (!aligned && (syncdata.lst != 0.0))
    {
        gotoparams.ratarget -= syncdata.deltaRA;
        gotoparams.detarget -= syncdata.deltaDEC;
    }

#if defined WITH_ALIGN_GEEHALEL && !defined WITH_ALIGN
    if (aligned)
    {
        gotoparams.ratarget = ghratarget;
        gotoparams.detarget = ghdetarget;
    }
#endif
#if defined WITH_ALIGN_GEEHALEL && defined WITH_ALIGN
    if (aligned && (AlignMethodSP.sp[0].s == ISS_ON))
    {
        LOGF_INFO("Setting Eqmod Goto RA=%g DE=%g (target RA=%g DE=%g)", ghratarget, ghdetarget,
                  r, d);
        gotoparams.ratarget = ghratarget;
        gotoparams.detarget = ghdetarget;
    }
#endif

    gotoparams.racurrentencoder = currentRAEncoder;
    gotoparams.decurrentencoder = currentDEEncoder;
    gotoparams.completed        = false;
    gotoparams.checklimits      = true;
    gotoparams.pier_side        = TargetPier;
    gotoparams.outsidelimits    = false;
    if (Hemisphere == NORTH)
    {
        gotoparams.limiteast        = zeroRAEncoder - (totalRAEncoder / 4) - (totalRAEncoder / 24); // 13h
        gotoparams.limitwest        = zeroRAEncoder + (totalRAEncoder / 4) + (totalRAEncoder / 24); // 23h
    }
    else
    {
        gotoparams.limiteast        = zeroRAEncoder + (totalRAEncoder / 4) + (totalRAEncoder / 24); // ??
        gotoparams.limitwest        = zeroRAEncoder - (totalRAEncoder / 4) - (totalRAEncoder / 24); // ??
    }

    if (gotoparams.pier_side != PIER_UNKNOWN)
    {
        LOG_WARN("Enforcing the pier side prevents a meridian flip and may lead to collisions of the telescope with obstacles.");
    }

    EncoderTarget(&gotoparams);

    if (gotoparams.outsidelimits)
    {
        LOGF_INFO("Target is unreachable, aborting (target encoders %u %u)", gotoparams.ratargetencoder,
                  gotoparams.detargetencoder);
        Abort();
        return false;
    }

    try
    {
        // stop motor
        mount->StopRA();
        mount->StopDE();
        // Start slewing
        LOGF_INFO("Slewing mount: RA increment = %d, DE increment = %d",
                  static_cast<int>(gotoparams.ratargetencoder - gotoparams.racurrentencoder),
                  static_cast<int>(gotoparams.detargetencoder - gotoparams.decurrentencoder));
        mount->SlewTo(static_cast<int>(gotoparams.ratargetencoder - gotoparams.racurrentencoder),
                      static_cast<int>(gotoparams.detargetencoder - gotoparams.decurrentencoder));
    }
    catch (EQModError &e)
    {
        return (e.DefaultHandleException(this));
    }

    fs_sexa(RAStr, targetRA, 2, 3600);
    fs_sexa(DecStr, targetDEC, 2, 3600);

    // This is already set before Goto in INDI::Telescope
    //RememberTrackState = TrackState;

    TrackState         = SCOPE_SLEWING;

    //EqREqNP.s = IPS_BUSY;
    //EqNP.s = IPS_BUSY;

#if 0
    // 2017-08-01 Jasem: We should set TrackState to IPS_IDLE instead here?
    TrackModeSP->s = IPS_IDLE;
    IDSetSwitch(TrackModeSP, nullptr);
#endif

    LOGF_INFO("Slewing to RA: %s - DEC: %s", RAStr, DecStr);
    return true;
}

bool EQMod::Park()
{
    if (!isParked())
    {
        if (TrackState == SCOPE_SLEWING)
        {
            LOG_INFO("Can not park while slewing...");
            ParkSP.s = IPS_ALERT;
            IDSetSwitch(&ParkSP, nullptr);
            return false;
        }

        try
        {
            // stop motor
            mount->StopRA();
            mount->StopDE();
            currentRAEncoder = mount->GetRAEncoder();
            currentDEEncoder = mount->GetDEEncoder();
            parkRAEncoder    = GetAxis1Park();
            parkDEEncoder    = GetAxis2Park();
            // Start slewing
            LOGF_INFO("Parking mount: RA increment = %d, DE increment = %d",
                      static_cast<int32_t>(parkRAEncoder - currentRAEncoder), static_cast<int32_t>(parkDEEncoder - currentDEEncoder));
            mount->SlewTo(static_cast<int32_t>(parkRAEncoder - currentRAEncoder),
                          static_cast<int32_t>(parkDEEncoder - currentDEEncoder));
        }
        catch (EQModError e)
        {
            return (e.DefaultHandleException(this));
        }
        //TrackModeSP->s = IPS_IDLE;
        //IDSetSwitch(TrackModeSP, nullptr);
        TrackState = SCOPE_PARKING;
        //        ParkSP.s   = IPS_BUSY;
        //        IDSetSwitch(&ParkSP, nullptr);
        LOG_INFO("Mount park in progress...");

        return true;
    }

    return false;
}

bool EQMod::UnPark()
{
    SetParked(false);
    return true;
}

bool EQMod::Sync(double ra, double dec)
{
    double juliandate;
    double lst;
    SyncData tmpsyncdata;
    double ha;
    TelescopePierSide pier_side;

    // get current mount position asap
    tmpsyncdata.telescopeRAEncoder  = mount->GetRAEncoder();
    tmpsyncdata.telescopeDECEncoder = mount->GetDEEncoder();

    juliandate = getJulianDate();
    lst        = getLst(juliandate, getLongitude());

    if (TrackState != SCOPE_TRACKING)
    {
        //        EqNP.s = IPS_ALERT;
        //        IDSetNumber(&EqNP, nullptr);
        LOG_WARN("Syncs are allowed only when Tracking");
        return false;
    }
    /* remember the two last syncs to compute Polar alignment */

    tmpsyncdata.lst       = lst;
    tmpsyncdata.jd        = juliandate;
    tmpsyncdata.targetRA  = ra;
    tmpsyncdata.targetDEC = dec;

    if (TargetPier == PIER_UNKNOWN)
    {
        ha = rangeHA(ra - lst);
        if (ha < 0.0)
        {
            // target WEST
            pier_side = PIER_EAST;
        }
        else
        {
            pier_side = PIER_WEST;
        }
    }
    else
    {
        pier_side = TargetPier;
    }
    tmpsyncdata.targetRAEncoder  = EncoderFromRA(ra, pier_side, lst, zeroRAEncoder, totalRAEncoder, Hemisphere);
    tmpsyncdata.targetDECEncoder = EncoderFromDec(dec, pier_side, zeroDEEncoder, totalDEEncoder, Hemisphere);

    try
    {
        EncodersToRADec(tmpsyncdata.telescopeRAEncoder, tmpsyncdata.telescopeDECEncoder, lst, &tmpsyncdata.telescopeRA,
                        &tmpsyncdata.telescopeDEC, nullptr, nullptr);
    }
    catch (EQModError e)
    {
        return (e.DefaultHandleException(this));
    }

    tmpsyncdata.deltaRA         = tmpsyncdata.targetRA - tmpsyncdata.telescopeRA;
    tmpsyncdata.deltaDEC        = tmpsyncdata.targetDEC - tmpsyncdata.telescopeDEC;
    tmpsyncdata.deltaRAEncoder  = static_cast<int>(tmpsyncdata.targetRAEncoder - tmpsyncdata.telescopeRAEncoder);
    tmpsyncdata.deltaDECEncoder = static_cast<int>(tmpsyncdata.targetDECEncoder - tmpsyncdata.telescopeDECEncoder);
#ifdef WITH_ALIGN_GEEHALEL
    if (align && !isStandardSync())
    {
        align->AlignSync(syncdata, tmpsyncdata);
        //return true;
    }
#endif
#ifdef WITH_ALIGN
    if (!isStandardSync())
    {
        AlignmentDatabaseEntry NewEntry;
        INDI::IEquatorialCoordinates RaDec;
        RaDec.rightascension  = tmpsyncdata.telescopeRA;
        RaDec.declination = tmpsyncdata.telescopeDEC;
        //NewEntry.ObservationJulianDate = ln_get_julian_from_sys();
        NewEntry.ObservationJulianDate = juliandate;
        NewEntry.RightAscension        = ra;
        NewEntry.Declination           = dec;
        NewEntry.TelescopeDirection    = TelescopeDirectionVectorFromEquatorialCoordinates(RaDec);
        NewEntry.PrivateDataSize       = 0;
        DEBUGF(INDI::AlignmentSubsystem::DBG_ALIGNMENT, "New sync point Date %lf RA %lf DEC %lf TDV(x %lf y %lf z %lf)",
               NewEntry.ObservationJulianDate, NewEntry.RightAscension, NewEntry.Declination,
               NewEntry.TelescopeDirection.x, NewEntry.TelescopeDirection.y, NewEntry.TelescopeDirection.z);
        if (!CheckForDuplicateSyncPoint(NewEntry, 0.01))
        {
            GetAlignmentDatabase().push_back(NewEntry);

            // Tell the client about size change
            UpdateSize();

            // Tell the math plugin to reinitialise
            Initialise(this);

        }
    }
#endif
#if defined WITH_ALIGN_GEEHALEL || defined WITH_ALIGN
    if (isStandardSync())
#endif
    {
#ifdef WITH_ALIGN_GEEHALEL
        if (align && isStandardSync())
            align->AlignStandardSync(syncdata, &tmpsyncdata, &m_Location);
#endif
        syncdata2 = syncdata;
        syncdata  = tmpsyncdata;

        IUFindNumber(StandardSyncNP, "STANDARDSYNC_RA")->value = syncdata.deltaRA;
        IUFindNumber(StandardSyncNP, "STANDARDSYNC_DE")->value = syncdata.deltaDEC;
        IDSetNumber(StandardSyncNP, nullptr);
        IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_JD")->value           = juliandate;
        IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_SYNCTIME")->value     = lst;
        IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_CELESTIAL_RA")->value = syncdata.targetRA;
        IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_CELESTIAL_DE")->value = syncdata.targetDEC;
        IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_TELESCOPE_RA")->value = syncdata.telescopeRA;
        IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_TELESCOPE_DE")->value = syncdata.telescopeDEC;
        IDSetNumber(StandardSyncPointNP, nullptr);

        LOGF_INFO("Mount Synced (deltaRA = %.6f deltaDEC = %.6f)", syncdata.deltaRA, syncdata.deltaDEC);
        if (syncdata2.lst != 0.0)
        {
            computePolarAlign(syncdata2, syncdata, getLatitude(), &tpa_alt, &tpa_az);
            IUFindNumber(SyncPolarAlignNP, "SYNCPOLARALIGN_ALT")->value = tpa_alt;
            IUFindNumber(SyncPolarAlignNP, "SYNCPOLARALIGN_AZ")->value  = tpa_az;
            IDSetNumber(SyncPolarAlignNP, nullptr);
            IDLog("computePolarAlign: Telescope Polar Axis: alt = %g, az = %g\n", tpa_alt, tpa_az);
        }
    }
    return true;
}

IPState EQMod::GuideNorth(uint32_t ms)
{
    if (ms < MinPulseN->value)
    {
        return IPS_IDLE;
    }

    double rateshift = TRACKRATE_SIDEREAL * IUFindNumber(GuideRateNP, "GUIDE_RATE_NS")->value;
    LOGF_DEBUG("Timed guide North %d ms at rate %g %s", ms, rateshift, DEInverted ? "(Inverted)" : "");

    IPState pulseState = IPS_BUSY;

    if (DEInverted)
        rateshift = -rateshift;
    try
    {
        if (ms >= MinPulseTimerN->value)
        {
            pulseInProgress |= 1;
            GuideTimerNS = IEAddTimer(ms, (IE_TCF *)timedguideNSCallback, this);
            mount->StartDETracking(GetDETrackRate() + rateshift);
        }
        else
        {
            // We should be done once the synchronous guide is complete
            pulseState = IPS_IDLE;

            struct timespec starttime, endtime;
            clock_gettime(CLOCK_MONOTONIC, &starttime);
            mount->StartDETracking(GetDETrackRate() + rateshift);
            clock_gettime(CLOCK_MONOTONIC, &endtime);
            double elapsed =
                (endtime.tv_sec - starttime.tv_sec) * 1000.0 + ((endtime.tv_nsec - starttime.tv_nsec) / 1000000.0);
            if (elapsed < ms)
            {
                uint32_t left = ms - elapsed;
                usleep(left * 1000);
            }
            try
            {
                mount->StartDETracking(GetDETrackRate());
            }
            catch (EQModError e)
            {
                if (!(e.DefaultHandleException(this)))
                {
                    DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_WARNING,
                                "Timed guide North/South Error: can not restart tracking");
                }
            }
            GuideComplete(AXIS_DE);
            DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_DEBUG, "End Timed guide North/South");
        }
    }
    catch (EQModError e)
    {
        e.DefaultHandleException(this);
        return IPS_ALERT;
    }

    return pulseState;
}

IPState EQMod::GuideSouth(uint32_t ms)
{
    if (ms < MinPulseN->value)
    {
        return IPS_IDLE;
    }

    double rateshift = 0.0;
    rateshift        = TRACKRATE_SIDEREAL * IUFindNumber(GuideRateNP, "GUIDE_RATE_NS")->value;
    LOGF_DEBUG("Timed guide South %d ms at rate %g %s", ms, rateshift, DEInverted ? "(Inverted)" : "");

    IPState pulseState = IPS_BUSY;

    if (DEInverted)
        rateshift = -rateshift;
    try
    {
        if (ms >= MinPulseTimerN->value)
        {
            pulseInProgress |= 1;
            GuideTimerNS = IEAddTimer(ms, (IE_TCF *)timedguideNSCallback, this);
            mount->StartDETracking(GetDETrackRate() - rateshift);
        }
        else
        {
            // We should be done once the synchronous guide is complete
            pulseState = IPS_IDLE;

            struct timespec starttime, endtime;
            clock_gettime(CLOCK_MONOTONIC, &starttime);
            mount->StartDETracking(GetDETrackRate() - rateshift);
            clock_gettime(CLOCK_MONOTONIC, &endtime);
            double elapsed =
                (endtime.tv_sec - starttime.tv_sec) * 1000.0 + ((endtime.tv_nsec - starttime.tv_nsec) / 1000000.0);
            if (elapsed < ms)
            {
                uint32_t left = ms - elapsed;
                usleep(left * 1000);
            }
            try
            {
                mount->StartDETracking(GetDETrackRate());
            }
            catch (EQModError e)
            {
                if (!(e.DefaultHandleException(this)))
                {
                    DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_WARNING,
                                "Timed guide North/South Error: can not restart tracking");
                }
            }
            GuideComplete(AXIS_DE);
            DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_DEBUG, "End Timed guide North/South");
        }
    }
    catch (EQModError e)
    {
        e.DefaultHandleException(this);
        return IPS_ALERT;
    }
    return pulseState;
}

IPState EQMod::GuideEast(uint32_t ms)
{
    if (ms < MinPulseN->value)
    {
        return IPS_IDLE;
    }

    double rateshift = 0.0;
    rateshift        = TRACKRATE_SIDEREAL * IUFindNumber(GuideRateNP, "GUIDE_RATE_WE")->value;
    LOGF_DEBUG("Timed guide East %d ms at rate %g %s", ms, rateshift, RAInverted ? "(Inverted)" : "");

    IPState pulseState = IPS_BUSY;

    if (RAInverted)
        rateshift = -rateshift;
    try
    {
        if (mount->HasPPEC())
        {
            restartguidePPEC = false;
            if (PPECSP->s == IPS_BUSY)
            {
                restartguidePPEC = true;
                LOG_INFO("Turning PPEC off while guiding.");
                mount->TurnPPEC(false);
            }
        }
        if (ms >= MinPulseTimerN->value)
        {
            pulseInProgress |= 2;
            GuideTimerWE = IEAddTimer(ms, (IE_TCF *)timedguideWECallback, this);
            mount->StartRATracking(GetRATrackRate() - rateshift);
        }
        else
        {
            // We should be done once the synchronous guide is complete
            pulseState = IPS_IDLE;

            struct timespec starttime, endtime;
            clock_gettime(CLOCK_MONOTONIC, &starttime);
            mount->StartRATracking(GetRATrackRate() - rateshift);
            clock_gettime(CLOCK_MONOTONIC, &endtime);
            double elapsed =
                (endtime.tv_sec - starttime.tv_sec) * 1000.0 + ((endtime.tv_nsec - starttime.tv_nsec) / 1000000.0);
            if (elapsed < ms)
            {
                uint32_t left = ms - elapsed;
                usleep(left * 1000);
            }
            try
            {
                if (mount->HasPPEC())
                {
                    if (restartguidePPEC)
                    {
                        restartguidePPEC = false;
                        DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_SESSION, "Turning PPEC on after guiding.");
                        mount->TurnPPEC(true);
                    }
                }
                mount->StartRATracking(GetRATrackRate());
            }
            catch (EQModError e)
            {
                if (!(e.DefaultHandleException(this)))
                {
                    DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_WARNING,
                                "Timed guide West/East Error: can not restart tracking");
                }
            }
            GuideComplete(AXIS_RA);
            DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_DEBUG, "End Timed guide West/East");
        }
    }
    catch (EQModError e)
    {
        e.DefaultHandleException(this);
        return IPS_ALERT;
    }

    return pulseState;
}

IPState EQMod::GuideWest(uint32_t ms)
{
    if (ms < MinPulseN->value)
    {
        return IPS_IDLE;
    }

    double rateshift = 0.0;
    rateshift        = TRACKRATE_SIDEREAL * IUFindNumber(GuideRateNP, "GUIDE_RATE_WE")->value;
    LOGF_DEBUG("Timed guide West %d ms at rate %g %s", ms, rateshift, RAInverted ? "(Inverted)" : "");

    IPState pulseState = IPS_BUSY;

    if (RAInverted)
        rateshift = -rateshift;
    try
    {
        if (mount->HasPPEC())
        {
            restartguidePPEC = false;
            if (PPECSP->s == IPS_BUSY)
            {
                restartguidePPEC = true;
                LOG_INFO("Turning PPEC off while guiding.");
                mount->TurnPPEC(false);
            }
        }
        if (ms >= MinPulseTimerN->value)
        {
            pulseInProgress |= 2;
            GuideTimerWE = IEAddTimer(ms, (IE_TCF *)timedguideWECallback, this);
            mount->StartRATracking(GetRATrackRate() + rateshift);
        }
        else
        {
            // We should be done once the synchronous guide is complete
            pulseState = IPS_IDLE;

            struct timespec starttime, endtime;
            clock_gettime(CLOCK_MONOTONIC, &starttime);
            mount->StartRATracking(GetRATrackRate() + rateshift);
            clock_gettime(CLOCK_MONOTONIC, &endtime);
            double elapsed =
                (endtime.tv_sec - starttime.tv_sec) * 1000.0 + ((endtime.tv_nsec - starttime.tv_nsec) / 1000000.0);
            if (elapsed < ms)
            {
                uint32_t left = ms - elapsed;
                usleep(left * 1000);
            }
            try
            {
                if (mount->HasPPEC())
                {
                    if (restartguidePPEC)
                    {
                        restartguidePPEC = false;
                        DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_SESSION, "Turning PPEC on after guiding.");
                        mount->TurnPPEC(true);
                    }
                }
                mount->StartRATracking(GetRATrackRate());
            }
            catch (EQModError e)
            {
                if (!(e.DefaultHandleException(this)))
                {
                    DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_WARNING,
                                "Timed guide West/East Error: can not restart tracking");
                }
            }
            GuideComplete(AXIS_RA);
            DEBUGDEVICE(getDeviceName(), INDI::Logger::DBG_DEBUG, "End Timed guide West/East");
        }
    }
    catch (EQModError e)
    {
        e.DefaultHandleException(this);
        return IPS_ALERT;
    }

    return pulseState;
}

bool EQMod::ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
{
    bool compose = true;
    //  first check if it's for our device
    if (strcmp(dev, getDeviceName()) == 0)
    {
        //  This is for our device
        //  Now lets see if it's something we process here

        if (strcmp(name, "SLEWSPEEDS") == 0)
        {
            /* TODO: don't change speed in gotos gotoparams.inprogress... */
            if (TrackState != SCOPE_TRACKING)
            {
                try
                {
                    for (int i = 0; i < n; i++)
                    {
                        if (strcmp(names[i], "RASLEW") == 0)
                            mount->SetRARate(values[i]);
                        else if (strcmp(names[i], "DESLEW") == 0)
                            mount->SetDERate(values[i]);
                    }
                }
                catch (EQModError e)
                {
                    return (e.DefaultHandleException(this));
                }
            }
            IUUpdateNumber(SlewSpeedsNP, values, names, n);
            SlewSpeedsNP->s = IPS_OK;
            IDSetNumber(SlewSpeedsNP, nullptr);
            LOGF_INFO("Setting Slew rates - RA=%.2fx DE=%.2fx",
                      IUFindNumber(SlewSpeedsNP, "RASLEW")->value, IUFindNumber(SlewSpeedsNP, "DESLEW")->value);
            return true;
        }

        // Guider interface
        if (!strcmp(name, GuideNSNP.name) || !strcmp(name, GuideWENP.name))
        {
            // Unless we're in track mode, we don't obey guide commands.
            if (TrackState != SCOPE_TRACKING)
            {
                GuideNSNP.s = IPS_IDLE;
                IDSetNumber(&GuideNSNP, nullptr);
                GuideWENP.s = IPS_IDLE;
                IDSetNumber(&GuideWENP, nullptr);
                LOG_WARN("Can not guide if not tracking.");
                return true;
            }

            processGuiderProperties(name, values, names, n);

            return true;
        }
        if (strcmp(name, GuideRateNP->name) == 0)
        {
            IUUpdateNumber(GuideRateNP, values, names, n);
            GuideRateNP->s = IPS_OK;
            IDSetNumber(GuideRateNP, nullptr);
            LOGF_INFO("Setting Custom Tracking Rates - RA=%1.1f arcsec/s DE=%1.1f arcsec/s",
                      IUFindNumber(GuideRateNP, "GUIDE_RATE_WE")->value,
                      IUFindNumber(GuideRateNP, "GUIDE_RATE_NS")->value);
            return true;
        }

        if (strcmp(name, PulseLimitsNP->name) == 0)
        {
            IUUpdateNumber(PulseLimitsNP, values, names, n);
            PulseLimitsNP->s = IPS_OK;
            IDSetNumber(PulseLimitsNP, nullptr);
            LOGF_INFO("Setting pulse limits: minimum pulse %3.0f ms, minimum timer pulse %4.0f ms", MinPulseN->value,
                      MinPulseTimerN->value);
            return true;
        }

        if (strcmp(name, "BACKLASH") == 0)
        {
            IUUpdateNumber(BacklashNP, values, names, n);
            BacklashNP->s = IPS_OK;
            IDSetNumber(BacklashNP, nullptr);
            mount->SetBacklashRA((uint32_t)(IUFindNumber(BacklashNP, "BACKLASHRA")->value));
            mount->SetBacklashDE((uint32_t)(IUFindNumber(BacklashNP, "BACKLASHDE")->value));
            LOGF_INFO("Setting Backlash compensation - RA=%.0f microsteps DE=%.0f microsteps",
                      IUFindNumber(BacklashNP, "BACKLASHRA")->value, IUFindNumber(BacklashNP, "BACKLASHDE")->value);
            return true;
        }

        if (mount->HasPolarLed())
        {
            if (strcmp(name, "LED_BRIGHTNESS") == 0)
            {
                IUUpdateNumber(LEDBrightnessNP, values, names, n);
                LEDBrightnessNP->s = IPS_OK;
                IDSetNumber(LEDBrightnessNP, nullptr);
                mount->SetLEDBrightness(static_cast<uint8_t>(values[0]));
                LOGF_INFO("Setting LED brightness to %.f", values[0]);
                return true;
            }
        }

        if (strcmp(name, "STANDARDSYNCPOINT") == 0)
        {
            syncdata2 = syncdata;
            bzero(&syncdata, sizeof(syncdata));
            IUUpdateNumber(StandardSyncPointNP, values, names, n);
            StandardSyncPointNP->s = IPS_OK;

            syncdata.jd           = IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_JD")->value;
            syncdata.lst          = IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_SYNCTIME")->value;
            syncdata.targetRA     = IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_CELESTIAL_RA")->value;
            syncdata.targetDEC    = IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_CELESTIAL_DE")->value;
            syncdata.telescopeRA  = IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_TELESCOPE_RA")->value;
            syncdata.telescopeDEC = IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_TELESCOPE_DE")->value;
            syncdata.deltaRA      = syncdata.targetRA - syncdata.telescopeRA;
            syncdata.deltaDEC     = syncdata.targetDEC - syncdata.telescopeDEC;
            IDSetNumber(StandardSyncPointNP, nullptr);
            IUFindNumber(StandardSyncNP, "STANDARDSYNC_RA")->value = syncdata.deltaRA;
            IUFindNumber(StandardSyncNP, "STANDARDSYNC_DE")->value = syncdata.deltaDEC;
            IDSetNumber(StandardSyncNP, nullptr);

            LOGF_INFO("Mount manually Synced (deltaRA = %.6f deltaDEC = %.6f)",
                      syncdata.deltaRA, syncdata.deltaDEC);
            //IDLog("Mount Synced (deltaRA = %.6f deltaDEC = %.6f)\n", syncdata.deltaRA, syncdata.deltaDEC);
            if (syncdata2.lst != 0.0)
            {
                computePolarAlign(syncdata2, syncdata, getLatitude(), &tpa_alt, &tpa_az);
                IUFindNumber(SyncPolarAlignNP, "SYNCPOLARALIGN_ALT")->value = tpa_alt;
                IUFindNumber(SyncPolarAlignNP, "SYNCPOLARALIGN_AZ")->value  = tpa_az;
                IDSetNumber(SyncPolarAlignNP, nullptr);
                IDLog("computePolarAlign: Telescope Polar Axis: alt = %g, az = %g\n", tpa_alt, tpa_az);
            }

            return true;
        }
    }

#ifdef WITH_ALIGN_GEEHALEL
    if (align)
    {
        compose = align->ISNewNumber(dev, name, values, names, n);
        if (compose)
            return true;
    }
#endif

    if (simulator)
    {
        compose = simulator->ISNewNumber(dev, name, values, names, n);
        if (compose)
            return true;
    }

#ifdef WITH_SCOPE_LIMITS
    if (horizon)
    {
        compose = horizon->ISNewNumber(dev, name, values, names, n);
        if (compose)
            return true;
    }
#endif

#ifdef WITH_ALIGN
    ProcessAlignmentNumberProperties(this, name, values, names, n);
#endif
    //  if we didn't process it, continue up the chain, let somebody else
    //  give it a shot
    return INDI::Telescope::ISNewNumber(dev, name, values, names, n);
}

bool EQMod::ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
{
    bool compose = true;
    if (strcmp(dev, getDeviceName()) == 0)
    {
        if (!strcmp(name, "SIMULATION"))
        {
            ISwitchVectorProperty *svp = getSwitch(name);

            IUUpdateSwitch(svp, states, names, n);
            ISwitch *sp = IUFindOnSwitch(svp);
            if (!sp)
                return false;

            if (isConnected())
            {
                DEBUG(INDI::Logger::DBG_WARNING,
                      "Mount must be disconnected before you can change simulation settings.");
                svp->s = IPS_ALERT;
                IDSetSwitch(svp, nullptr);
                return false;
            }

            if (!strcmp(sp->name, "ENABLE"))
                setStepperSimulation(true);
            else
                setStepperSimulation(false);
            return true;
        }

        if (strcmp(name, "USEBACKLASH") == 0)
        {
            IUUpdateSwitch(UseBacklashSP, states, names, n);
            mount->SetBacklashUseRA((IUFindSwitch(UseBacklashSP, "USEBACKLASHRA")->s == ISS_ON ? true : false));
            mount->SetBacklashUseDE((IUFindSwitch(UseBacklashSP, "USEBACKLASHDE")->s == ISS_ON ? true : false));
            LOGF_INFO("Use Backlash :  RA: %s, DE: %s",
                      IUFindSwitch(UseBacklashSP, "USEBACKLASHRA")->s == ISS_ON ? "True" : "False",
                      IUFindSwitch(UseBacklashSP, "USEBACKLASHDE")->s == ISS_ON ? "True" : "False");
            UseBacklashSP->s = IPS_IDLE;
            IDSetSwitch(UseBacklashSP, nullptr);
            return true;
        }

        if (strcmp(name, "TRACKDEFAULT") == 0)
        {
            ISwitch *swbefore, *swafter;
            swbefore = IUFindOnSwitch(TrackDefaultSP);
            IUUpdateSwitch(TrackDefaultSP, states, names, n);
            swafter = IUFindOnSwitch(TrackDefaultSP);
            if (swbefore != swafter)
            {
                TrackDefaultSP->s = IPS_IDLE;
                IDSetSwitch(TrackDefaultSP, nullptr);
                LOGF_INFO("Changed Track Default (from %s to %s).", swbefore->name,
                          swafter->name);
            }
            return true;
        }

        if (strcmp(name, "ST4_GUIDE_RATE_WE") == 0)
        {
            ISwitch *swbefore, *swafter;
            swbefore = IUFindOnSwitch(ST4GuideRateWESP);
            IUUpdateSwitch(ST4GuideRateWESP, states, names, n);
            swafter = IUFindOnSwitch(ST4GuideRateWESP);
            if (swbefore != swafter)
            {
                unsigned char rate = '0' + (unsigned char)IUFindOnSwitchIndex(ST4GuideRateWESP);
                mount->SetST4RAGuideRate(rate);
                ST4GuideRateWESP->s = IPS_IDLE;
                IDSetSwitch(ST4GuideRateWESP, nullptr);
                LOGF_INFO("Changed ST4 Guide rate WE (from %s to %s).", swbefore->label,
                          swafter->label);
            }
            return true;
        }

        if (strcmp(name, "ST4_GUIDE_RATE_NS") == 0)
        {
            ISwitch *swbefore, *swafter;
            swbefore = IUFindOnSwitch(ST4GuideRateNSSP);
            IUUpdateSwitch(ST4GuideRateNSSP, states, names, n);
            swafter = IUFindOnSwitch(ST4GuideRateNSSP);
            if (swbefore != swafter)
            {
                unsigned char rate = '0' + (unsigned char)IUFindOnSwitchIndex(ST4GuideRateNSSP);
                mount->SetST4DEGuideRate(rate);
                ST4GuideRateNSSP->s = IPS_IDLE;
                IDSetSwitch(ST4GuideRateNSSP, nullptr);
                LOGF_INFO("Changed ST4 Guide rate NS (from %s to %s).", swbefore->label,
                          swafter->label);
            }
            return true;
        }

        if (!strcmp(name, "SYNCMANAGE"))
        {
            ISwitchVectorProperty *svp = getSwitch(name);
            IUUpdateSwitch(svp, states, names, n);
            ISwitch *sp = IUFindOnSwitch(svp);
            if (!sp)
                return false;
            IDSetSwitch(svp, nullptr);

            if (!strcmp(sp->name, "SYNCCLEARDELTA"))
            {
                bzero(&syncdata, sizeof(syncdata));
                bzero(&syncdata2, sizeof(syncdata2));
                IUFindNumber(StandardSyncNP, "STANDARDSYNC_RA")->value = syncdata.deltaRA;
                IUFindNumber(StandardSyncNP, "STANDARDSYNC_DE")->value = syncdata.deltaDEC;
                IDSetNumber(StandardSyncNP, nullptr);
                IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_JD")->value           = syncdata.jd;
                IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_SYNCTIME")->value     = syncdata.lst;
                IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_CELESTIAL_RA")->value = syncdata.targetRA;
                ;
                IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_CELESTIAL_DE")->value = syncdata.targetDEC;
                ;
                IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_TELESCOPE_RA")->value = syncdata.telescopeRA;
                ;
                IUFindNumber(StandardSyncPointNP, "STANDARDSYNCPOINT_TELESCOPE_DE")->value = syncdata.telescopeDEC;
                ;
                IDSetNumber(StandardSyncPointNP, nullptr);
                LOG_INFO("Cleared current Sync Data");
                tpa_alt                                                     = 0.0;
                tpa_az                                                      = 0.0;
                IUFindNumber(SyncPolarAlignNP, "SYNCPOLARALIGN_ALT")->value = tpa_alt;
                IUFindNumber(SyncPolarAlignNP, "SYNCPOLARALIGN_AZ")->value  = tpa_az;
                IDSetNumber(SyncPolarAlignNP, nullptr);
                return true;
            }
        }

        if (!strcmp(name, "REVERSEDEC"))
        {
            IUUpdateSwitch(ReverseDECSP, states, names, n);

            ReverseDECSP->s = IPS_OK;

            UpdateDEInverted();

            LOG_INFO("Inverting Declination Axis.");

            IDSetSwitch(ReverseDECSP, nullptr);
        }

        if (!strcmp(name, "TARGETPIERSIDE"))
        {
            IUUpdateSwitch(TargetPierSideSP, states, names, n);

            TargetPierSideSP->s = IPS_OK;

            TargetPier = PIER_UNKNOWN;
            if (IUFindSwitch(TargetPierSideSP, "PIER_EAST")->s == ISS_ON)
            {
                TargetPier = PIER_EAST;
                LOG_INFO("Target pier side set to EAST");
            }
            else if (IUFindSwitch(TargetPierSideSP, "PIER_WEST")->s == ISS_ON)
            {
                TargetPier = PIER_WEST;
                LOG_INFO("Target pier side set to WEST");
            }

            IDSetSwitch(TargetPierSideSP, nullptr);
        }

        //if (MountInformationTP && MountInformationTP->tp && (!strcmp(MountInformationTP->tp[0].text, "EQ8") || !strcmp(MountInformationTP->tp[0].text, "AZEQ6"))) {
        if (mount->HasHomeIndexers())
        {
            if (AutoHomeSP && strcmp(name, AutoHomeSP->name) == 0)
            {
                if ((TrackState != SCOPE_IDLE) && (TrackState != SCOPE_AUTOHOMING))
                {
                    if (TrackState != SCOPE_AUTOHOMING)
                    {
                        AutoHomeSP->s = IPS_IDLE;
                        IUResetSwitch(AutoHomeSP);
                        IDSetSwitch(AutoHomeSP, nullptr);
                    }
                    LOG_WARN("Can not start AutoHome. Scope not idle");
                    return true;
                }

                if (TrackState == SCOPE_AUTOHOMING)
                {
                    AutoHomeSP->s = IPS_IDLE;
                    IUResetSwitch(AutoHomeSP);
                    IDSetSwitch(AutoHomeSP, nullptr);
                    LOG_WARN("Aborting AutoHome.");
                    Abort();
                    return true;
                }

                if (AutohomeState == AUTO_HOME_IDLE)
                {
                    AutoHomeSP->s = IPS_OK;
                    IUResetSwitch(AutoHomeSP);
                    IDSetSwitch(AutoHomeSP, nullptr);
                    LOG_WARN("*** AutoHome NOT TESTED. Press PERFORM AGAIN TO CONFIRM. ***");
                    AutohomeState      = AUTO_HOME_CONFIRM;
                    ah_confirm_timeout = 10;
                    return true;
                }
                if (AutohomeState == AUTO_HOME_CONFIRM)
                {
                    IUUpdateSwitch(AutoHomeSP, states, names, n);
                    AutoHomeSP->s = IPS_BUSY;
                    LOG_INFO("Starting Autohome.");
                    IDSetSwitch(AutoHomeSP, nullptr);
                    TrackState = SCOPE_AUTOHOMING;
                    try
                    {
                        LOG_INFO("AutoHome phase 1: turning off aux encoders");
                        mount->TurnRAEncoder(false);
                        mount->TurnDEEncoder(false);
                        LOG_INFO("AutoHome phase 1: resetting home position indexes");
                        mount->ResetRAIndexer();
                        mount->ResetDEIndexer();
                        LOG_INFO(
                            "AutoHome phase 1: reading home position indexes to set directions");
                        mount->GetRAIndexer();
                        mount->GetDEIndexer();
                        LOGF_INFO(
                            "AutoHome phase 1: read home position indexes: RA=0x%x DE=0x%x",
                            mount->GetlastreadRAIndexer(), mount->GetlastreadDEIndexer());
                        if (mount->GetlastreadRAIndexer() == 0)
                            ah_bSlewingUp_RA = true;
                        else
                            ah_bSlewingUp_RA = false;
                        if (mount->GetlastreadDEIndexer() == 0)
                            ah_bSlewingUp_DE = true;
                        else
                            ah_bSlewingUp_DE = false;
                        ah_iPosition_RA = mount->GetRAEncoder();
                        ah_iPosition_DE = mount->GetDEEncoder();
                        ah_iChanges     = (5 * mount->GetRAEncoderTotal()) / 360;
                        if (ah_bSlewingUp_RA)
                            ah_iPosition_RA = ah_iPosition_RA - ah_iChanges;
                        else
                            ah_iPosition_RA = ah_iPosition_RA + ah_iChanges;
                        ah_iChanges = (5 * mount->GetDEEncoderTotal()) / 360;
                        if (ah_bSlewingUp_DE)
                            ah_iPosition_DE = ah_iPosition_DE - ah_iChanges;
                        else
                            ah_iPosition_DE = ah_iPosition_DE + ah_iChanges;
                        LOG_INFO(
                            "AutoHome phase 1: trying to move further away from home position");
                        LOGF_INFO(
                            "AutoHome phase 1: slewing to RA=0x%x (up=%c) DE=0x%x (up=%c)", ah_iPosition_RA,
                            (ah_bSlewingUp_RA ? '1' : '0'), ah_iPosition_DE, (ah_bSlewingUp_DE ? '1' : '0'));
                        mount->AbsSlewTo(ah_iPosition_RA, ah_iPosition_DE, ah_bSlewingUp_RA, ah_bSlewingUp_DE);
                        AutohomeState = AUTO_HOME_WAIT_PHASE1;
                    }
                    catch (EQModError e)
                    {
                        AutoHomeSP->s = IPS_ALERT;
                        IUResetSwitch(AutoHomeSP);
                        IDSetSwitch(AutoHomeSP, nullptr);
                        AutohomeState = AUTO_HOME_IDLE;
                        TrackState    = SCOPE_IDLE;
                        RememberTrackState = TrackState;
                        return (e.DefaultHandleException(this));
                    }
                }
            }
        }

        if (mount->HasAuxEncoders())
        {
            if (AuxEncoderSP && strcmp(name, AuxEncoderSP->name) == 0)
            {
                IUUpdateSwitch(AuxEncoderSP, states, names, n);
                if (AuxEncoderSP->sp[1].s == ISS_ON)
                {
                    AuxEncoderSP->s = IPS_OK;
                    LOG_DEBUG("Turning auxiliary encoders on.");
                    mount->TurnRAEncoder(true);
                    mount->TurnDEEncoder(true);
                }
                else
                {
                    AuxEncoderSP->s = IPS_IDLE;
                    LOG_DEBUG("Turning auxiliary encoders off.");
                    mount->TurnRAEncoder(false);
                    mount->TurnDEEncoder(false);
                }
                IDSetSwitch(AuxEncoderSP, nullptr);
            }
        }

        if (mount->HasPPEC())
        {
            if (PPECTrainingSP && strcmp(name, PPECTrainingSP->name) == 0)
            {
                IUUpdateSwitch(PPECTrainingSP, states, names, n);
                if (PPECTrainingSP->sp[1].s == ISS_ON)
                {
                    if (TrackState != SCOPE_TRACKING)
                    {
                        PPECTrainingSP->s = IPS_IDLE;
                        LOG_WARN("Can not start PPEC Training. Scope not tracking");
                        IUResetSwitch(PPECTrainingSP);
                        PPECTrainingSP->sp[0].s = ISS_ON;
                        PPECTrainingSP->sp[1].s = ISS_OFF;
                    }
                    else
                    {
                        PPECTrainingSP->s = IPS_BUSY;
                        LOG_INFO("Turning PPEC Training on.");
                        try
                        {
                            mount->TurnPPECTraining(true);
                        }
                        catch (EQModError e)
                        {
                            LOG_WARN("Unable to start PPEC Training.");
                            PPECTrainingSP->s       = IPS_ALERT;
                            PPECTrainingSP->sp[0].s = ISS_ON;
                            PPECTrainingSP->sp[1].s = ISS_OFF;
                        }
                    }
                }
                else
                {
                    PPECTrainingSP->s = IPS_IDLE;
                    LOG_INFO("Turning PPEC Training off.");
                    mount->TurnPPECTraining(false);
                }
                IDSetSwitch(PPECTrainingSP, nullptr);
                return true;
            }
            if (PPECSP && strcmp(name, PPECSP->name) == 0)
            {
                IUUpdateSwitch(PPECSP, states, names, n);
                if (PPECSP->sp[1].s == ISS_ON)
                {
                    PPECSP->s = IPS_BUSY;
                    LOG_INFO("Turning PPEC on.");
                    mount->TurnPPEC(true);
                }
                else
                {
                    PPECSP->s = IPS_IDLE;
                    LOG_INFO("Turning PPEC off.");
                    mount->TurnPPEC(false);
                }
                IDSetSwitch(PPECSP, nullptr);
                return true;
            }
        }

        if (mount->HasSnapPort1())
        {
            if (SNAPPORT1SP && strcmp(name, SNAPPORT1SP->name) == 0)
            {
                IUUpdateSwitch(SNAPPORT1SP, states, names, n);
                if (SNAPPORT1SP->sp[1].s == ISS_ON)
                {
                    SNAPPORT1SP->s = IPS_OK;
                    DEBUG(INDI::Logger::DBG_DEBUG, "Turning snap port 1 on.");
                    mount->TurnSnapPort1(true);
                }
                else
                {
                    SNAPPORT1SP->s = IPS_IDLE;
                    DEBUG(INDI::Logger::DBG_DEBUG, "Turning snap port 1 off.");
                    mount->TurnSnapPort1(false);
                }
                IDSetSwitch(SNAPPORT1SP, nullptr);
                return true;
            }
        }

        if (mount->HasSnapPort2())
        {
            if (SNAPPORT2SP && strcmp(name, SNAPPORT2SP->name) == 0)
            {
                IUUpdateSwitch(SNAPPORT2SP, states, names, n);
                if (SNAPPORT2SP->sp[1].s == ISS_ON)
                {
                    SNAPPORT2SP->s = IPS_OK;
                    DEBUG(INDI::Logger::DBG_DEBUG, "Turning snap port 2 on.");
                    mount->TurnSnapPort2(true);
                }
                else
                {
                    SNAPPORT2SP->s = IPS_IDLE;
                    DEBUG(INDI::Logger::DBG_DEBUG, "Turning snap port 2 off.");
                    mount->TurnSnapPort2(false);
                }
                IDSetSwitch(SNAPPORT2SP, nullptr);
                return true;
            }
        }



#if defined WITH_ALIGN || defined WITH_ALIGN_GEEHALEL
        if (AlignSyncModeSP && strcmp(name, AlignSyncModeSP->name) == 0)
        {
            ISwitch *sw;
            AlignSyncModeSP->s = IPS_OK;
            IUUpdateSwitch(AlignSyncModeSP, states, names, n);
            //for (int i=0; i < n; i++)
            //  IDLog("AlignSyncMode Switch %s %d\n", names[i], states[i]);
            sw = IUFindOnSwitch(AlignSyncModeSP);
            IDSetSwitch(AlignSyncModeSP, "Sync mode set to %s", sw->label);
            return true;
        }
#endif

#if defined WITH_ALIGN_GEEHALEL && defined WITH_ALIGN
        if (strcmp(name, AlignMethodSP.name) == 0)
        {
            ISwitch *sw;
            AlignMethodSP.s = IPS_OK;
            IUUpdateSwitch(&AlignMethodSP, states, names, n);
            //for (int i=0; i < n; i++)
            //  IDLog("AlignSyncMode Switch %s %d\n", names[i], states[i]);
            sw = IUFindOnSwitch(&AlignMethodSP);
            IDSetSwitch(&AlignMethodSP, "Align method set to %s", sw->label);
            return true;
        }
#endif
    }
#ifdef WITH_ALIGN_GEEHALEL
    if (align)
    {
        compose = align->ISNewSwitch(dev, name, states, names, n);
        if (compose)
            return true;
    }
#endif

    if (simulator)
    {
        compose = simulator->ISNewSwitch(dev, name, states, names, n);
        if (compose)
            return true;
    }
#ifdef WITH_SCOPE_LIMITS
    if (horizon)
    {
        compose = horizon->ISNewSwitch(dev, name, states, names, n);
        if (compose)
            return true;
    }
#endif
#ifdef WITH_ALIGN
    ProcessAlignmentSwitchProperties(this, name, states, names, n);
#endif

    INDI::Logger::ISNewSwitch(dev, name, states, names, n);

    //  Nobody has claimed this, so, ignore it
    return INDI::Telescope::ISNewSwitch(dev, name, states, names, n);
}

bool EQMod::ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
{
    bool compose;
#ifdef WITH_ALIGN_GEEHALEL
    if (align)
    {
        compose = align->ISNewText(dev, name, texts, names, n);
        if (compose)
            return true;
    }
#endif
    if (simulator)
    {
        compose = simulator->ISNewText(dev, name, texts, names, n);
        if (compose)
            return true;
    }
#ifdef WITH_SCOPE_LIMITS
    if (horizon)
    {
        compose = horizon->ISNewText(dev, name, texts, names, n);
        if (compose)
            return true;
    }
#endif
#ifdef WITH_ALIGN
    ProcessAlignmentTextProperties(this, name, texts, names, n);
#endif
    //  Nobody has claimed this, so, ignore it
    return INDI::Telescope::ISNewText(dev, name, texts, names, n);
}

#ifdef WITH_ALIGN
bool EQMod::ISNewBLOB(const char *dev, const char *name, int sizes[], int blobsizes[], char *blobs[], char *formats[],
                      char *names[], int n)
{
    if (strcmp(dev, getDeviceName()) == 0)
    {
        // Process alignment properties
        ProcessAlignmentBLOBProperties(this, name, sizes, blobsizes, blobs, formats, names, n);
    }
    // Pass it up the chain
    return INDI::Telescope::ISNewBLOB(dev, name, sizes, blobsizes, blobs, formats, names, n);
}
#endif

bool EQMod::updateTime(ln_date *lndate_utc, double utc_offset)
{
    char utc_time[32];
    lndate.seconds = lndate_utc->seconds;
    lndate.minutes = lndate_utc->minutes;
    lndate.hours   = lndate_utc->hours;
    lndate.days    = lndate_utc->days;
    lndate.months  = lndate_utc->months;
    lndate.years   = lndate_utc->years;

    utc.tm_sec  = lndate.seconds;
    utc.tm_min  = lndate.minutes;
    utc.tm_hour = lndate.hours;
    utc.tm_mday = lndate.days;
    utc.tm_mon  = lndate.months - 1;
    utc.tm_year = lndate.years - 1900;

    gettimeofday(&lasttimeupdate, nullptr);
    get_utc_time(&lastclockupdate);

    strftime(utc_time, 32, "%Y-%m-%dT%H:%M:%S", &utc);

    LOGF_INFO("Setting UTC Time to %s, Offset %g", utc_time, utc_offset);

    return true;
}

double EQMod::GetRASlew()
{
    ISwitch *sw;
    double rate = 1.0;
    sw          = IUFindOnSwitch(&SlewRateSP);
    if (!strcmp(sw->name, "SLEWCUSTOM"))
        rate = IUFindNumber(SlewSpeedsNP, "RASLEW")->value;
    else
        rate = *((double *)sw->aux);
    return rate;
}

double EQMod::GetDESlew()
{
    ISwitch *sw;
    double rate = 1.0;
    sw          = IUFindOnSwitch(&SlewRateSP);
    if (!strcmp(sw->name, "SLEWCUSTOM"))
        rate = IUFindNumber(SlewSpeedsNP, "DESLEW")->value;
    else
        rate = *((double *)sw->aux);
    return rate;
}

bool EQMod::MoveNS(INDI_DIR_NS dir, TelescopeMotionCommand command)
{
    const char *dirStr = (dir == DIRECTION_NORTH) ? "North" : "South";
    double rate        = (dir == DIRECTION_NORTH) ? GetDESlew() : GetDESlew() * -1;

    try
    {
        switch (command)
        {
            case MOTION_START:
                if (gotoInProgress() || (TrackState == SCOPE_PARKING) || (TrackState == SCOPE_PARKED))
                {
                    LOG_WARN("Can not slew while goto/park in progress, or scope parked.");
                    return false;
                }

                LOGF_INFO("Starting %s slew.", dirStr);
                if (DEInverted)
                    rate = -rate;
                mount->SlewDE(rate);
                //TrackState = SCOPE_SLEWING;
                break;

            case MOTION_STOP:
                LOGF_INFO("%s Slew stopped", dirStr);
                mount->StopDE();
                //if (TrackModeSP->s == IPS_BUSY)
                if (RememberTrackState == SCOPE_TRACKING)
                {
                    LOG_INFO("Restarting DE Tracking...");
                    TrackState = SCOPE_TRACKING;
                    mount->StartDETracking(GetDETrackRate());
                }
                else
                    TrackState = SCOPE_IDLE;

                RememberTrackState = TrackState;

                break;
        }
    }
    catch (EQModError e)
    {
        return e.DefaultHandleException(this);
    }
    return true;
}

bool EQMod::MoveWE(INDI_DIR_WE dir, TelescopeMotionCommand command)
{
    const char *dirStr = (dir == DIRECTION_WEST) ? "West" : "East";
    double rate        = (dir == DIRECTION_WEST) ? GetRASlew() : GetRASlew() * -1;

    try
    {
        switch (command)
        {
            case MOTION_START:
                if (gotoInProgress() || (TrackState == SCOPE_PARKING) || (TrackState == SCOPE_PARKED))
                {
                    LOG_WARN("Can not slew while goto/park in progress, or scope parked.");
                    return false;
                }

                LOGF_INFO("Starting %s slew.", dirStr);
                if (RAInverted)
                    rate = -rate;
                mount->SlewRA(rate);
                //TrackState = SCOPE_SLEWING;
                break;

            case MOTION_STOP:
                LOGF_INFO("%s Slew stopped", dirStr);
                mount->StopRA();
                //if (TrackModeSP->s == IPS_BUSY)
                if (RememberTrackState == SCOPE_TRACKING)
                {
                    LOG_INFO("Restarting RA Tracking...");
                    TrackState = SCOPE_TRACKING;
                    mount->StartRATracking(GetRATrackRate());
                }
                else
                    TrackState = SCOPE_IDLE;

                RememberTrackState = TrackState;

                break;
        }
    }
    catch (EQModError e)
    {
        return e.DefaultHandleException(this);
    }
    return true;
}

bool EQMod::Abort()
{
    try
    {
        mount->StopRA();
    }
    catch (EQModError e)
    {
        if (!(e.DefaultHandleException(this)))
        {
            LOG_WARN("Abort: error while stopping RA motor");
        }
    }
    try
    {
        mount->StopDE();
    }
    catch (EQModError e)
    {
        if (!(e.DefaultHandleException(this)))
        {
            LOG_WARN("Abort: error while stopping DE motor");
        }
    }

    GuideNSNP.s = IPS_IDLE;
    IDSetNumber(&GuideNSNP, nullptr);
    GuideWENP.s = IPS_IDLE;
    IDSetNumber(&GuideWENP, nullptr);
#if 0
    TrackModeSP->s = IPS_IDLE;
    IUResetSwitch(TrackModeSP);
    IDSetSwitch(TrackModeSP, nullptr);
#endif
    AutohomeState = AUTO_HOME_IDLE;
    AutoHomeSP->s = IPS_IDLE;
    IUResetSwitch(AutoHomeSP);
    IDSetSwitch(AutoHomeSP, nullptr);
    TrackState = SCOPE_IDLE;
    RememberTrackState = TrackState;
    if (gotoparams.completed == false)
        gotoparams.completed = true;

    return true;
}

void EQMod::timedguideNSCallback(void *userpointer)
{
    EQMod *p = ((EQMod *)userpointer);
    p->pulseInProgress &= ~1;

    try
    {
        p->mount->StartDETracking(p->GetDETrackRate());
    }
    catch (EQModError e)
    {
        if (!(e.DefaultHandleException(p)))
        {
            DEBUGDEVICE(p->getDeviceName(), INDI::Logger::DBG_WARNING,
                        "Timed guide North/South Error: can not restart tracking");
        }
    }
    p->GuideComplete(AXIS_DE);
    DEBUGDEVICE(p->getDeviceName(), INDI::Logger::DBG_DEBUG, "End Timed guide North/South");
    IERmTimer(p->GuideTimerNS);
}

void EQMod::timedguideWECallback(void *userpointer)
{
    EQMod *p = ((EQMod *)userpointer);
    p->pulseInProgress &= ~2;

    try
    {
        if (p->mount->HasPPEC())
        {
            if (p->restartguidePPEC)
            {
                p->restartguidePPEC = false;
                DEBUGDEVICE(p->getDeviceName(), INDI::Logger::DBG_SESSION, "Turning PPEC on after guiding.");
                p->mount->TurnPPEC(true);
            }
        }
        p->mount->StartRATracking(p->GetRATrackRate());
    }
    catch (EQModError e)
    {
        if (!(e.DefaultHandleException(p)))
        {
            DEBUGDEVICE(p->getDeviceName(), INDI::Logger::DBG_WARNING,
                        "Timed guide West/East Error: can not restart tracking");
        }
    }
    p->GuideComplete(AXIS_RA);
    DEBUGDEVICE(p->getDeviceName(), INDI::Logger::DBG_DEBUG, "End Timed guide West/East");
    IERmTimer(p->GuideTimerWE);
}

void EQMod::computePolarAlign(SyncData s1, SyncData s2, double lat, double *tpaalt, double *tpaaz)
/*
From // // http://www.whim.org/nebula/math/pdf/twostar.pdf
 */
{
    double delta1 = 0, alpha1 = 0, delta2 = 0, alpha2 = 0;
    double d1 = 0, d2 = 0; /* corrected delta1/delta2 */
    double cdelta1 = 0, calpha1 = 0, cdelta2 = 0, calpha2 = 0;
    double Delta = 0;
    double cosDelta1 = 0, cosDelta2 = 0;
    double cosd2pd1 = 0, d2pd1 = 0;
    double tpadelta = 0, tpaalpha = 0;
    double sintpadelta = 0, costpaalpha = 0, sintpaalpha = 0;
    double cosama1 = 0, cosama2 = 0;
    double cosaz = 0, sinaz = 0;
    double beta = 0;

    // Star s2 polar align
    double s2tra = 0, s2tdec = 0;
    char s2trasexa[13], s2tdecsexa[13];
    char s2rasexa[13], s2decsexa[13];

    alpha1  = DEG_TO_RAD((s1.telescopeRA - s1.lst) * 360.0 / 24.0);
    delta1  = DEG_TO_RAD(s1.telescopeDEC);
    alpha2  = DEG_TO_RAD((s2.telescopeRA - s2.lst) * 360.0 / 24.0);
    delta2  = DEG_TO_RAD(s2.telescopeDEC);
    calpha1 = DEG_TO_RAD((s1.targetRA - s1.lst) * 360.0 / 24.0);
    cdelta1 = DEG_TO_RAD(s1.targetDEC);
    calpha2 = DEG_TO_RAD((s2.targetRA - s2.lst) * 360.0 / 24.0);
    cdelta2 = DEG_TO_RAD(s2.targetDEC);

    if ((calpha2 == calpha1) || (alpha1 == alpha2))
        return;

    cosDelta1 = sin(cdelta1) * sin(cdelta2) + (cos(cdelta1) * cos(cdelta2) * cos(calpha2 - calpha1));
    cosDelta2 = sin(delta1) * sin(delta2) + (cos(delta1) * cos(delta2) * cos(alpha2 - alpha1));

    if (cosDelta1 != cosDelta2)
        LOGF_DEBUG(
            "PolarAlign -- Telescope axes are not perpendicular. Angular distances are:celestial=%g telescope=%g",
            acos(cosDelta1), acos(cosDelta2));
    Delta = acos(cosDelta1);
    LOGF_DEBUG("Angular distance of the two stars is %g", Delta);

    //cosd2md1 = sin(delta1) * sin(delta2) + cos(delta1) * cos(delta2);
    cosd2pd1 = ((cos(delta2 - delta1) * (1 + cos(alpha2 - alpha1))) - (2.0 * cosDelta2)) / (1 - cos(alpha2 - alpha1));
    d2pd1    = acos(cosd2pd1);
    if (delta2 * delta1 > 0.0)
    {
        /* same sign */
        if (delta1 < 0.0)
            d2pd1 = -d2pd1;
    }
    else
    {
        if (fabs(delta1) > fabs(delta2))
        {
            if (delta1 < 0.0)
                d2pd1 = -d2pd1;
        }
        else
        {
            if (delta2 < 0.0)
                d2pd1 = -d2pd1;
        }
    }

    d2 = (d2pd1 + delta2 - delta1) / 2.0;
    d1 = d2pd1 - d2;
    LOGF_DEBUG("Computed delta1 = %g (%g) delta2 = %g (%g)", d1, delta1, d2, delta2);

    delta1 = d1;
    delta2 = d2;

    sintpadelta =
        (sin(delta1) * sin(cdelta1)) + (sin(delta2) * sin(cdelta2)) -
        cosDelta1 * ((sin(delta1) * sin(cdelta2)) + (sin(cdelta1) * sin(delta2))) +
        (cos(delta1) * cos(delta2) * sin(alpha2 - alpha1) * cos(cdelta1) * cos(cdelta2) * sin(calpha2 - calpha1));
    sintpadelta = sintpadelta / (sin(Delta) * sin(Delta));
    tpadelta    = asin(sintpadelta);
    cosama1     = (sin(delta1) - (sin(cdelta1) * sintpadelta)) / (cos(cdelta1) * cos(tpadelta));
    cosama2     = (sin(delta2) - (sin(cdelta2) * sintpadelta)) / (cos(cdelta2) * cos(tpadelta));

    costpaalpha = (sin(calpha2) * cosama1 - sin(calpha1) * cosama2) / sin(calpha2 - calpha1);
    sintpaalpha = (cos(calpha1) * cosama2 - cos(calpha2) * cosama1) / sin(calpha2 - calpha1);
    //tpaalpha = acos(costpaalpha);
    //if (sintpaalpha < 0) tpaalpha = 2 * M_PI - tpaalpha;
    // tpadelta and tpaaplha are very near M_PI / 2 d: DON'T USE  atan2
    //tpaalpha=atan2(sintpaalpha, costpaalpha);
    tpaalpha = 2 * atan2(sintpaalpha, (1.0 + costpaalpha));
    LOGF_DEBUG("Computed Telescope polar alignment (rad): delta(dec) = %g alpha(ha) = %g",
               tpadelta, tpaalpha);

    beta    = DEG_TO_RAD(lat);
    *tpaalt = asin(sin(tpadelta) * sin(beta) + (cos(tpadelta) * cos(beta) * cos(tpaalpha)));
    cosaz   = (sin(tpadelta) - (sin(*tpaalt) * sin(beta))) / (cos(*tpaalt) * cos(beta));
    sinaz   = (cos(tpadelta) * sin(tpaalpha)) / cos(*tpaalt);
    //*tpaaz = acos(cosaz);
    //if (sinaz < 0) *tpaaz = 2 * M_PI - *tpaaz;
    *tpaaz  = atan2(sinaz, cosaz);
    *tpaalt = RAD_TO_DEG(*tpaalt);
    *tpaaz  = RAD_TO_DEG(*tpaaz);
    LOGF_DEBUG("Computed Telescope polar alignment (deg): alt = %g az = %g", *tpaalt, *tpaaz);

    starPolarAlign(s2.lst, s2.targetRA, s2.targetDEC, (M_PI / 2) - tpaalpha, (M_PI / 2) - tpadelta, &s2tra, &s2tdec);
    fs_sexa(s2trasexa, s2tra, 2, 3600);
    fs_sexa(s2tdecsexa, s2tdec, 3, 3600);
    fs_sexa(s2rasexa, s2.targetRA, 2, 3600);
    fs_sexa(s2decsexa, s2.targetDEC, 3, 3600);
    LOGF_INFO("Star (RA=%s DEC=%s) Polar Align Coords: RA=%s DEC=%s", s2rasexa, s2decsexa,
              s2trasexa, s2tdecsexa);
    s2tra  = s2.targetRA + (s2.targetRA - s2tra);
    s2tdec = s2.targetDEC + (s2.targetDEC - s2tdec);
    fs_sexa(s2trasexa, s2tra, 2, 3600);
    fs_sexa(s2tdecsexa, s2tdec, 3, 3600);
    fs_sexa(s2rasexa, s2.targetRA, 2, 3600);
    fs_sexa(s2decsexa, s2.targetDEC, 3, 3600);

    LOGF_INFO("Star (RA=%s DEC=%s) Polar Align Goto: RA=%s DEC=%s", s2rasexa, s2decsexa,
              s2trasexa, s2tdecsexa);
}

void EQMod::starPolarAlign(double lst, double ra, double dec, double theta, double gamma, double *tra, double *tdec)
{
    double rotz[3][3];
    double rotx[3][3];
    double mat[3][3];

    double H;
    double Lc, Mc, Nc;

    double mra, mdec;
    double L, M, N;
    int i, j, k;

    H   = (lst - ra) * M_PI / 12.0;
    dec = dec * M_PI / 180.0;

    rotz[0][0] = cos(theta);
    rotz[0][1] = -sin(theta);
    rotz[0][2] = 0.0;
    rotz[1][0] = sin(theta);
    rotz[1][1] = cos(theta);
    rotz[1][2] = 0.0;
    rotz[2][0] = 0.0;
    rotz[2][1] = 0.0;
    rotz[2][2] = 1.0;

    rotx[0][0] = 1.0;
    rotx[0][1] = 0.0;
    rotx[0][2] = 0.0;
    rotx[1][0] = 0.0;
    rotx[1][1] = cos(gamma);
    rotx[1][2] = -sin(gamma);
    rotx[2][0] = 0.0;
    rotx[2][1] = sin(gamma);
    rotx[2][2] = cos(gamma);

    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            mat[i][j] = 0.0;
            for (k = 0; k < 3; k++)
                mat[i][j] += rotx[i][k] * rotz[k][j];
        }
    }

    Lc = cos(dec) * cos(-H);
    Mc = cos(dec) * sin(-H);
    Nc = sin(dec);

    L = mat[0][0] * Lc + mat[0][1] * Mc + mat[0][2] * Nc;
    M = mat[1][0] * Lc + mat[1][1] * Mc + mat[1][2] * Nc;
    N = mat[2][0] * Lc + mat[2][1] * Mc + mat[2][2] * Nc;

    mra = atan2(M, L) * 12.0 / M_PI;
    //mra=atan(M/L) * 12.0 / M_PI;
    //printf("atan(M/L) %g L=%g M=%g N=%g\n", mra, L, M, N);
    //if (L < 0.0) mra = 12.0 + mra;
    mra += lst;
    while (mra < 0.0)
        mra += 24.0;
    while (mra > 24.0)
        mra -= 24.0;
    mdec  = asin(N) * 180.0 / M_PI;
    *tra  = mra;
    *tdec = mdec;
}

bool EQMod::updateLocation(double latitude, double longitude, double elevation)
{
    m_Location.longitude = longitude;
    m_Location.latitude  = latitude;
    m_Location.elevation = elevation;

    if (latitude < 0.0)
        SetSouthernHemisphere(true);
    else
        SetSouthernHemisphere(false);
#ifdef WITH_ALIGN
    INDI::AlignmentSubsystem::AlignmentSubsystemForDrivers::UpdateLocation(latitude, longitude, elevation);
    // Set this according to mount type
    SetApproximateMountAlignmentFromMountType(EQUATORIAL);
#endif
    // Make display longitude to be in the standard 0 to +180 East, and 0 to -180 West.
    // No need to confuse new users with INDI format.
    char lat_str[MAXINDIFORMAT] = {0}, lng_str[MAXINDIFORMAT] = {0};
    double display_longitude = longitude > 180 ? longitude - 360 : longitude;
    fs_sexa(lat_str, m_Location.latitude, 2, 36000);
    fs_sexa(lng_str, display_longitude, 2, 36000);
    // Choose WGS 84, also known as EPSG:4326 for latitude/longitude ordering
    LOGF_INFO("Observer location updated: Latitude %.12s (%.2f) Longitude %.12s (%.2f)", lat_str, m_Location.latitude, lng_str,
              display_longitude);
    return true;
}

void EQMod::saveInitialParkPosition()
{
    // If there is no initial park data. We assume the default parking position
    // Looking at celestial pole with weights down
    SetDefaultPark();
    WriteParkData();
}

bool EQMod::SetCurrentPark()
{
    parkRAEncoder = currentRAEncoder;
    parkDEEncoder = currentDEEncoder;
    SetAxis1Park(parkRAEncoder);
    SetAxis2Park(parkDEEncoder);
    LOGF_INFO("Setting Park Position to current RA Encoder=%ld DE Encoder=%ld",
              static_cast<long>(parkRAEncoder), static_cast<long>(parkDEEncoder));

    return true;
}

bool EQMod::SetDefaultPark()
{
    parkRAEncoder = GetAxis1ParkDefault();
    parkDEEncoder = GetAxis2ParkDefault();
    SetAxis1Park(parkRAEncoder);
    SetAxis2Park(parkDEEncoder);
    LOGF_INFO("Setting Park Position to default RA Encoder=%ld DE Encoder=%ld",
              static_cast<long>(parkRAEncoder), static_cast<long>(parkDEEncoder));

    return true;
}

bool EQMod::saveConfigItems(FILE *fp)
{
    INDI::Telescope::saveConfigItems(fp);

    if (BacklashNP)
        IUSaveConfigNumber(fp, BacklashNP);
    if (UseBacklashSP)
        IUSaveConfigSwitch(fp, UseBacklashSP);
    if (GuideRateNP)
        IUSaveConfigNumber(fp, GuideRateNP);
    if (PulseLimitsNP)
        IUSaveConfigNumber(fp, PulseLimitsNP);
    if (SlewSpeedsNP)
        IUSaveConfigNumber(fp, SlewSpeedsNP);
    if (ReverseDECSP)
        IUSaveConfigSwitch(fp, ReverseDECSP);
    if (LEDBrightnessNP)
        IUSaveConfigNumber(fp, LEDBrightnessNP);
    if (HasPECState())
        IUSaveConfigSwitch(fp, PPECSP);

#ifdef WITH_ALIGN_GEEHALEL
    if (align)
        align->saveConfigItems(fp);
#endif
#ifdef WITH_SCOPE_LIMITS
    if (horizon)
        horizon->saveConfigItems(fp);
#endif
    return true;
}

bool EQMod::SetTrackRate(double raRate, double deRate)
{
    try
    {
        mount->SetRARate(raRate / SKYWATCHER_STELLAR_SPEED);
        mount->SetDERate(deRate / SKYWATCHER_STELLAR_SPEED);
    }
    catch (EQModError e)
    {
        return (e.DefaultHandleException(this));
    }

    LOGF_INFO("Setting Custom Tracking Rates - RA=%.6f  DE=%.6f arcsec/s", raRate, deRate);

    return true;
}

bool EQMod::SetTrackMode(uint8_t mode)
{
    // GetRATrackRate..etc al already check TrackModeSP to obtain the appropiate tracking rate, so no need for mode here.
    INDI_UNUSED(mode);

    try
    {
        mount->StartRATracking(GetRATrackRate());
        mount->StartDETracking(GetDETrackRate());
    }
    catch (EQModError e)
    {
        return (e.DefaultHandleException(this));
    }

    return true;
}

bool EQMod::SetTrackEnabled(bool enabled)
{
    try
    {
        if (enabled)
        {
            LOGF_INFO("Start Tracking (%s).", IUFindOnSwitch(&TrackModeSP)->label);
            TrackState     = SCOPE_TRACKING;
            RememberTrackState = TrackState;
            mount->StartRATracking(GetRATrackRate());
            mount->StartDETracking(GetDETrackRate());
        }
        else if (enabled == false)
        {
            LOGF_WARN("Stopping Tracking (%s).", IUFindOnSwitch(&TrackModeSP)->label);
            TrackState     = SCOPE_IDLE;
            RememberTrackState = TrackState;
            mount->StopRA();
            mount->StopDE();
        }
    }
    catch (EQModError e)
    {
        return (e.DefaultHandleException(this));
    }

    return true;
}