File: dotter.cpp

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


/*
   DOTTER - Sequence-sequence dotplot in a pixel background image

   Memory requirements:
   The pixelmap + (alphabetsize+4) x qlen + 2 x slen

          Pending (this is an old list - may be out of date):

          change filqueryopen to filqueryeditopen (.dotter) when getting new code.

          Fix revcomp when zooming in.

          Add to alignment tool the extent and score of the current window.

          (Raise initial cutoffs when compressed. ?)

          HSP drawing bugged for reverse matches and for reversed scale
          (Huge job to fix ... do only if really necessary)

          Score matrix for DNA w/ transversions/transitions...? literature?

-------------------------------------------------------------------------------- */

/* CPU usage profiling on SGI:

   cc dotter.c, no optimization
   pixie -o dotter.pixie dotter
   dotter.pixie -wD -b t seq seq
   prof -pixie -h -only calcWindow dotter dotter.Addrs dotter.Counts
*/

#include <seqtoolsUtils/version.hpp>
#include <seqtoolsUtils/utilities.hpp>
#include <dotterApp/dotter_.hpp>
#include <dotterApp/seqtoolsExonView.hpp>
#include <gbtools/gbtools.hpp>
#include <gdk/gdkkeysyms.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <algorithm>

using namespace std;


/* tint stuff used to be in graph.h, now local - rd 960524
   NB colours as Erik liked them before Jean tinkered!
   could rename #define's more sensibly now
*/

//#define TINT_WHITE      0x00
//#define TINT_HIGHLIGHT1 0x01  /* highest priority, dna highlighting */
//#define TINT_HIGHLIGHT2 0x02  /* highlight friends */
//#define TINT_RED        0x04 
//#define TINT_LIGHTGRAY  0x08 
//#define TINT_MAGENTA    0x10 
//#define TINT_CYAN       0x20 
//#define TINT_LIGHTGREEN 0x40 
//#define TINT_YELLOW     0x80 

//static int tints[8] = { LIGHTRED, MIDBLUE, RED, LIGHTGRAY, 
//                      MAGENTA, CYAN, LIGHTGREEN, YELLOW } ;

#define MAX_WINDOW_WIDTH_FRACTION             0.8 /* max init width of dotter window as fraction of screen size */
#define MAX_WINDOW_HEIGHT_FRACTION            0.8 /* max init height of dotter window as fraction of screen size */
#define MAIN_WINDOW_NAME                      "DotterMainWindow"

#define DOCK_WINDOWS_DEFAULT TRUE
#define MINIMISE_GREYRAMP_DEFAULT TRUE

//class GeneDataStruct
//{
//public:
//  GeneDataStruct() : name(NULL), start(0), end(0), strand(0), 
//                     msp_start(NULL), msp_end(NULL), y_pos(0.0) {};
//
//  const char *name ;
//  int start, end ;
//  char strand ;
//  MSP *msp_start, *msp_end ;
//  float y_pos ;
//};
//typedef GeneDataStruct, *GeneData ;
//
//typedef struct
//{
//  GList *forward_genes ;
//  GList *reverse_genes ;
//  char strand  ;
//} GeneStrandStruct, *GeneStrand ;
//


/* Struct containing properties for a dotter window */
class DotterProperties
{
public:
  GtkWidget *widget;
  GtkWidget *greyrampTool;                  /* the greyramp tool */
  GtkWidget *greyrampWindow;                /* the window containing the greyramp too when undocked */
  GtkWidget *greyrampContainer;             /* the container containing the greyramp tool when docked */
  GtkWidget *greyrampToolMinimised;         /* the minimised version of the greyramp tool */
  GtkWidget *alignmentTool;                 /* the alignment tool */
  GtkWidget *alignmentWindow;               /* the window containing the alignment tool when undocked */
  GtkWidget *alignmentContainer;            /* the container containing the alignment tool when docked */
  GtkWidget *dotplot;                       /* the dotplot drawing area */
  
  gboolean windowsDocked;                   /* if true, all tools are docked into a single window */
  DotterWindowContext *dotterWinCtx;
  const char *exportFileName;
};


/* Local function declarations */

static void showSettingsDialog(GtkWidget *dotterWindow);
static void readmtx(int mtx[24][24], char *mtxfile);
static void mtxcpy(int mtx[24][24], int BLOSUM62[24][24]);
static void DNAmatrix(int mtx[24][24]);
//static void drawAllFeatures(MSP *msp) ;
//static void drawGenes(MSP *msp, float forward_y, float reverse_y, float depth) ;
//gint compareMSPs(gconstpointer a, gconstpointer b) ;
//static void getGenePositionsCB(gpointer data, gpointer user_data) ;
//gint compareGenes(gconstpointer a, gconstpointer b) ;
//static void setYoffsets(GList *first, float min_offset, float max_offset) ;
//static void drawGenesCB(gpointer data, gpointer user_data) ;
//static void drawMSPGene(MSP *msp, float y_offset) ;
//static int gArrayGetLen(GArray *array);

static void                   showHideGreyrampTool(GtkWidget *dotterWindow, const gboolean show);
static void                   showHideAlignmentTool(GtkWidget *dotterWindow, const gboolean show);
static GtkWidget*             createDotterWindow(DotterContext *dc, DotterWindowContext *dwc, const DotterHspMode hspMode, GtkWidget *dotplot, GtkWidget *dotplotContainer, GtkWidget *greyrampContainer, GtkWidget *alignmentContainer, GtkWidget *greyrampTool, GtkWidget *alignmentTool, GtkWidget *greyrampToolMinimised, const char *exportFileName, char *windowColor);
static DotterContext*         dotterGetContext(GtkWidget *dotterWindow);
static void                   redrawAll(GtkWidget *dotterWindow, gpointer data);
static void                   refreshAll(GtkWidget *dotterWindow, gpointer data);
static gboolean               onKeyPressDotter(GtkWidget *widget, GdkEventKey *event, gpointer data);
static gboolean               negateDisplayCoord(DotterContext *dc, const gboolean horizontal);
static gboolean               setStartCoord(GtkWidget *dotterWindow, DotterWindowContext *dwc, const gboolean horizontal, const int newValue);
static gboolean               setEndCoord(GtkWidget *dotterWindow, DotterWindowContext *dwc, const gboolean horizontal, const int newValue);
static void                   printDotterWindow(GtkWidget *dotterWindow);
static DotterProperties*      dotterGetProperties(GtkWidget *dotterWindow);

static GtkWidget* createDotterInstance(DotterContext *dotterCtx,
                                       DotterWindowContext *dotterWinCtx,
                                       const char *loadFileName,
                                       const char *saveFileName,
                                       const char *exportFileName,
                                       const gboolean hspsOn,
                                       const gboolean breaklinesOn,
                                       const char* winsizeIn,
                                       const int pixelFacIn,
                                       const int zoomFacIn,
                                       const int qcenter,
                                       const int scenter,
                                       const gboolean greyramSwap,
                                       char *windowColor);

static void                       onQuitMenu(GtkAction *action, gpointer data);
static void                       onCloseMenu(GtkAction *action, gpointer data);
static void                       onSavePlotMenu(GtkAction *action, gpointer data);
static void                       onExportPlotMenu(GtkAction *action, gpointer data);
static void                       onPrintMenu(GtkAction *action, gpointer data);
static void                       onSettingsMenu(GtkAction *action, gpointer data);
static void                       onShowHideGreyrampMenu(GtkAction *action, gpointer data);
static void                       onShowHideAlignmentMenu(GtkAction *action, gpointer data);
static void                       onToggleCrosshairMenu(GtkAction *action, gpointer data);
static void                       onToggleCoordsMenu(GtkAction *action, gpointer data);
static void                       onToggleFullscreenMenu(GtkAction *action, gpointer data);
static void                       onTogglePixelmapMenu(GtkAction *action, gpointer data);
static void                       onToggleGridMenu(GtkAction *action, gpointer data);
static void                       onHelpMenu(GtkAction *action, gpointer data);
static void                       onAboutMenu(GtkAction *action, gpointer data);
static void                       onMaximiseGreyrampMenu(GtkAction *action, gpointer data);
static void                       onMinimiseGreyrampMenu(GtkAction *action, gpointer data);
static void                       onToggleUsePrintColorsMenu(GtkAction *action, gpointer data);
static void                       onToggleBumpExonsMenu(GtkAction *action, gpointer data);
static void                       onToggleDockWindowsMenu(GtkAction *action, gpointer data);
static void                       onPrintColorsChanged(GtkWidget *dotterWindow);
static void                       onCloseAlignmentMenu(GtkAction *action, gpointer data);
static void                       onPrintAlignmentMenu(GtkAction *action, gpointer data);
static void                       onCopyHCoordMenu(GtkAction *action, gpointer data);
static void                       onCopyVCoordMenu(GtkAction *action, gpointer data);
static void                       onCopySelnMenu(GtkAction *action, gpointer data);
static void                       onCopySelnCoordsMenu(GtkAction *action, gpointer data);
static void                       onClearSelnMenu(GtkAction *action, gpointer data);


/* Menu builders: the action entry list lists menu actions for all menus */
static const GtkActionEntry menuEntries[] = {
{ "FileMenuAction",   NULL, "_File"},
{ "EditMenuAction",   NULL, "_Edit"},
{ "ViewMenuAction",   NULL, "_View"},
{ "HelpMenuAction",   NULL, "_Help"},

{ "Quit",           GTK_STOCK_QUIT,         "_Quit all dotters",      "<control>Q", "Quit all dotters",           G_CALLBACK(onQuitMenu)},
{ "Close",          GTK_STOCK_CLOSE,        "_Close this dotter",     "<control>W", "Close this dotter",          G_CALLBACK(onCloseMenu)},
{ "SavePlot",       GTK_STOCK_SAVE,         "_Save plot",             NULL,         "Save plot",                  G_CALLBACK(onSavePlotMenu)},
{ "ExportPlot",     NULL,                   "_Export plot",           NULL,         "Export plot",                G_CALLBACK(onExportPlotMenu)},
{ "Print",          GTK_STOCK_PRINT,        "_Print...",              "<control>P", "Print",                      G_CALLBACK(onPrintMenu)},
{ "Settings",       GTK_STOCK_PREFERENCES,  "Settings",               "<control>S", "Set dotter parameters",      G_CALLBACK(onSettingsMenu)},
{ "Help",           GTK_STOCK_HELP,         "_Help",                  "<control>H", "Dotter Help",                G_CALLBACK(onHelpMenu)},
{ "About",          GTK_STOCK_ABOUT,        "_About",                 NULL,         "About Dotter",               G_CALLBACK(onAboutMenu)},

{ "MaximiseGreyramp", NULL,                 "_Maximise greyramp",     "<control>G", "Maximise the greyramp tool", G_CALLBACK(onMaximiseGreyrampMenu)},
{ "MinimiseGreyramp", NULL,                 "M_inimise greyramp",     "<control>G", "Minimise the greyramp tool", G_CALLBACK(onMinimiseGreyrampMenu)},

{ "CloseAlignment", NULL, "_Close tool",              "<control>A",       "Close the alignment tool",                                            G_CALLBACK(onCloseAlignmentMenu)},
{ "PrintAlignment", NULL, "_Print alignment...",      NULL,               "Print the alignment tool window",                                     G_CALLBACK(onPrintAlignmentMenu)},
{ "CopyHCoord",     NULL, "Copy _horizontal coord",   NULL,               "Copy the current horizontal sequence coord to the clipboard",         G_CALLBACK(onCopyHCoordMenu)},
{ "CopyVCoord",     NULL, "Copy _vertical coord",     NULL,               "Copy the current vertical sequence coord to the clipboard",           G_CALLBACK(onCopyVCoordMenu)},
{ "CopySeln",       NULL, "Copy selectio_n",          "<control>C",       "Copy the current selection to the clipboard",                         G_CALLBACK(onCopySelnMenu)},
{ "ClearSeln",      NULL, "C_lear current selection", "Escape","Clear the current selection",                                                    G_CALLBACK(onClearSelnMenu)},
{ "CopySelnCoords", NULL, "Copy selection coor_ds",   "<shift><control>C","Copy the start/end coords of the current selection to the clipboard", G_CALLBACK(onCopySelnCoordsMenu)}

};

/* Toggle-able menu entries are listed here: */
static GtkToggleActionEntry toggleMenuEntries[] = {
{ "TogglePixmap",     NULL, "Pixelmap",              NULL,  "Show the pixelmap",              G_CALLBACK(onTogglePixelmapMenu),        TRUE},
{ "ToggleGrid",       NULL, "Gridlines",             NULL,  "Show grid lines",                G_CALLBACK(onToggleGridMenu),            FALSE},
{ "ToggleCrosshair",  NULL, "Crosshair",             NULL,  "Show the crosshair",             G_CALLBACK(onToggleCrosshairMenu),       TRUE},
{ "ToggleCoords",     NULL, "Crosshair label",       NULL,  "Show the crosshair label",       G_CALLBACK(onToggleCoordsMenu),          TRUE},
{ "ToggleFullscreen", NULL, "Crosshair fullscreen",  NULL,  "Show the crosshair full screen", G_CALLBACK(onToggleFullscreenMenu),      TRUE},
{ "TogglePrintColors",NULL, "Use print colors",      NULL,  "Use print _colors",              G_CALLBACK(onToggleUsePrintColorsMenu),  FALSE},
{ "ToggleBumpExons",  NULL, "Bump exons",            "B",   "_Bump exons",                    G_CALLBACK(onToggleBumpExonsMenu),       FALSE},
{ "ToggleGreyramp",   NULL, "_Greyramp tool",        "<control>G", "Maximise/minimise the greyramp tool",G_CALLBACK(onShowHideGreyrampMenu),   TRUE},
{ "ToggleAlignment",  NULL, "_Alignment tool",       "<control>A", "Show/hide the alignment tool",G_CALLBACK(onShowHideAlignmentMenu), TRUE},
{ "DockWindows",      NULL, "Dock windows",          "<control>K", "_Dock windows",           G_CALLBACK(onToggleDockWindowsMenu),     DOCK_WINDOWS_DEFAULT}
};

/* Radio-button menu entries are listed here: */
static const GtkRadioActionEntry radioMenuEntries[] = {
{ "HspsOff",    NULL, "HSPs off",                     NULL,  "Hide Blast HSPs",                                    DOTTER_HSPS_OFF},
{ "HspsGrey",   NULL, "Draw HSPs (greyramp)",         NULL,  "Draw Blast HSPs as greyramp",                        DOTTER_HSPS_GREYSCALE},
{ "HspsLine",   NULL, "Draw HSPs (red lines)",        NULL,  "Draw Blast HSPs as solid red lines",                 DOTTER_HSPS_LINE},
{ "HspsFunc",   NULL, "Draw HSPs (color = f(score))", NULL,  "Draw Blast HSPs with color as a function of score",  DOTTER_HSPS_FUNC}
};



/* Menu UI descriptions */
static const char mainMenuDescription[] =
"<ui>"
"  <menubar name='MenuBar'>"
"    <menu action='FileMenuAction'>"
"      <menuitem action='SavePlot'/>"
"      <menuitem action='ExportPlot'/>"
"      <separator/>"
"      <menuitem action='Print'/>"
"      <menuitem action='TogglePrintColors'/>"
"      <separator/>"
"      <menuitem action='Close'/>"
"      <menuitem action='Quit'/>"
"    </menu>"
"    <menu action='EditMenuAction'>"
"      <menuitem action='CopyHCoord'/>"
"      <menuitem action='CopyVCoord'/>"
"      <menuitem action='CopySeln'/>"
"      <menuitem action='CopySelnCoords'/>"
"      <menuitem action='ClearSeln'/>"
"      <separator/>"
"      <menuitem action='Settings'/>"
"    </menu>"
"    <menu action='ViewMenuAction'>"
"      <menuitem action='ToggleGreyramp'/>"
"      <menuitem action='ToggleAlignment'/>"
"      <menuitem action='DockWindows'/>"
"      <separator/>"
"      <menuitem action='ToggleCrosshair'/>"
"      <menuitem action='ToggleCoords'/>"
"      <menuitem action='ToggleFullscreen'/>"
"      <separator/>"
"      <menuitem action='TogglePixmap'/>"
"      <menuitem action='ToggleGrid'/>"
"      <separator/>"
"      <menuitem action='HspsOff'/>"
"      <menuitem action='HspsGrey'/>"
"      <menuitem action='HspsLine'/>"
"      <menuitem action='HspsFunc'/>"
"     <separator/>"
"      <menuitem action='ToggleBumpExons'/>"
"    </menu>"
"    <menu action='HelpMenuAction'>"
"      <menuitem action='Help'/>"
"      <menuitem action='About'/>"
"    </menu>"
"  </menubar>"
"  <popup name='ContextMenu' accelerators='true'>"
"    <menuitem action='Close'/>"
"    <menuitem action='Quit'/>"
"    <menuitem action='Help'/>"
"    <menuitem action='SavePlot'/>"
"    <menuitem action='Print'/>"
"    <separator/>"
"    <menuitem action='Settings'/>"
"    <separator/>"
"    <menuitem action='ToggleGreyramp'/>"
"    <menuitem action='ToggleAlignment'/>"
"    <menuitem action='DockWindows'/>"
"    <separator/>"
"    <menu action='ViewMenuAction'>"
"      <separator/>"
"      <menuitem action='ToggleCrosshair'/>"
"      <menuitem action='ToggleCoords'/>"
"      <menuitem action='ToggleFullscreen'/>"
"      <separator/>"
"      <menuitem action='TogglePixmap'/>"
"      <menuitem action='ToggleGrid'/>"
"      <separator/>"
"      <menuitem action='HspsOff'/>"
"      <menuitem action='HspsGrey'/>"
"      <menuitem action='HspsLine'/>"
"      <menuitem action='HspsFunc'/>"
"    </menu>"
"  </popup>"
"  <popup name='MinimisedGreyrampContextMenu' accelerators='true'>"
"    <menuitem action='MaximiseGreyramp'/>"
"  </popup>"
"  <popup name='MaximisedGreyrampContextMenu' accelerators='true'>"
"    <menuitem action='MinimiseGreyramp'/>"
"  </popup>"
"  <popup name='AlignmentContextMenu' accelerators='true'>"
"      <menuitem action='CopyHCoord'/>"
"      <menuitem action='CopyVCoord'/>"
"      <menuitem action='CopySeln'/>"
"      <menuitem action='CopySelnCoords'/>"
"      <menuitem action='ClearSeln'/>"
"      <separator/>"
"      <menuitem action='CloseAlignment'/>"
"      <menuitem action='Print'/>"
"  </popup>"
"</ui>";



/* Global variables */

static int    MATRIX[24][24];
//              MSPoffset,      /* Difference between real MSP coord and coord stored in MSP */
//              HSPgaps = 0.
//              fsBoxStart,
//              fsRightOn = 1,
//              fsBottomOn = 1,
//              fsAnnRightOn = 1,
//              fsAnnBottomOn = 1,
//              fsEndLinesOn = 0;

//static Graph  fsGraph=0;

#define MAXALIGNLEN 501

//static char fsPlotHeighttx[10];

       float fsPlotHeight=2.0;  /* The height of feature series XY plots */
//static MSP   *msp;

/*  BLOSUM62 930809

     A   R   N   D   C   Q   E   G   H   I   L   K   M   F   P   S   T   W   Y   V   B   Z   X  \* */ 
int BLOSUM62[24][24] = {
  {  4, -1, -2, -2,  0, -1, -1,  0, -2, -1, -1, -1, -1, -2, -1,  1,  0, -3, -2,  0, -2, -1,  0, -4 },
  { -1,  5,  0, -2, -3,  1,  0, -2,  0, -3, -2,  2, -1, -3, -2, -1, -1, -3, -2, -3, -1,  0, -1, -4 },
  { -2,  0,  6,  1, -3,  0,  0,  0,  1, -3, -3,  0, -2, -3, -2,  1,  0, -4, -2, -3,  3,  0, -1, -4 },
  { -2, -2,  1,  6, -3,  0,  2, -1, -1, -3, -4, -1, -3, -3, -1,  0, -1, -4, -3, -3,  4,  1, -1, -4 },
  {  0, -3, -3, -3,  9, -3, -4, -3, -3, -1, -1, -3, -1, -2, -3, -1, -1, -2, -2, -1, -3, -3, -2, -4 },
  { -1,  1,  0,  0, -3,  5,  2, -2,  0, -3, -2,  1,  0, -3, -1,  0, -1, -2, -1, -2,  0,  3, -1, -4 },
  { -1,  0,  0,  2, -4,  2,  5, -2,  0, -3, -3,  1, -2, -3, -1,  0, -1, -3, -2, -2,  1,  4, -1, -4 },
  { 0, -2,  0, -1, -3, -2, -2,  6, -2, -4, -4, -2, -3, -3, -2,  0, -2, -2, -3, -3, -1, -2, -1, -4 },
  { -2,  0,  1, -1, -3,  0,  0, -2,  8, -3, -3, -1, -2, -1, -2, -1, -2, -2,  2, -3,  0,  0, -1, -4 },
  { -1, -3, -3, -3, -1, -3, -3, -4, -3,  4,  2, -3,  1,  0, -3, -2, -1, -3, -1,  3, -3, -3, -1, -4 },
  { -1, -2, -3, -4, -1, -2, -3, -4, -3,  2,  4, -2,  2,  0, -3, -2, -1, -2, -1,  1, -4, -3, -1, -4 },
  { -1,  2,  0, -1, -3,  1,  1, -2, -1, -3, -2,  5, -1, -3, -1,  0, -1, -3, -2, -2,  0,  1, -1, -4 },
  { -1, -1, -2, -3, -1,  0, -2, -3, -2,  1,  2, -1,  5,  0, -2, -1, -1, -1, -1,  1, -3, -1, -1, -4 },
  { -2, -3, -3, -3, -2, -3, -3, -3, -1,  0,  0, -3,  0,  6, -4, -2, -2,  1,  3, -1, -3, -3, -1, -4 },
  { -1, -2, -2, -1, -3, -1, -1, -2, -2, -3, -3, -1, -2, -4,  7, -1, -1, -4, -3, -2, -2, -1, -2, -4 },
  { 1, -1,  1,  0, -1,  0,  0,  0, -1, -2, -2,  0, -1, -2, -1,  4,  1, -3, -2, -2,  0,  0,  0, -4 },
  { 0, -1,  0, -1, -1, -1, -1, -2, -2, -1, -1, -1, -1, -2, -1,  1,  5, -2, -2,  0, -1, -1,  0, -4 },
  { -3, -3, -4, -4, -2, -2, -3, -2, -2, -3, -2, -3, -1,  1, -4, -3, -2, 11,  2, -3, -4, -3, -2, -4 },
  { -2, -2, -2, -3, -2, -1, -2, -3,  2, -1, -1, -2, -1,  3, -3, -2, -2,  2,  7, -1, -3, -2, -1, -4 },
  { 0, -3, -3, -3, -1, -2, -2, -3, -3,  3,  1, -2,  1, -1, -2, -2,  0, -3, -1,  4, -3, -2, -1, -4 },
  { -2, -1,  3,  4, -3,  0,  1, -1,  0, -3, -4,  0, -3, -3, -2,  0, -1, -4, -3, -3,  4,  1, -1, -4 },
  { -1,  0,  0,  1, -3,  3,  4, -2,  0, -3, -3,  1, -1, -3, -1,  0, -1, -3, -2, -2,  1,  4, -1, -4 },
  { 0, -1, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2,  0,  0, -2, -1, -1, -1, -1, -1, -4 },
  { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -1 }
 };


//GArray *fsArr = NULL;  /* Stores Feature Series - t he actual segments are stored
//                         as MSPs, using these fields:
//                         msp->sframe  = [1..2] sequence
//                         msp->qstart = segment start
//                         msp->qend   = segment end
//                         msp->fs     = Ordinal number of series that this MSP belongs to.
//                         msp->fsColor  = color
//                         msp->desc   = annotation
//                         */


/***********************************************************
 *                       Properties                        *
 ***********************************************************/

/* free memory used by color structs */
static void destroyDotterColors(DotterContext *dc)
{
  if (!dc || !dc->defaultColors)
    return;

  int i = DOTCOLOR_MIN + 1;
  
  for ( ; i < DOTCOLOR_NUM_COLORS; ++i)
    {
      BlxColor *blxColor = &g_array_index(dc->defaultColors, BlxColor, i);
      destroyBlxColor(blxColor);
    }

  g_array_free(dc->defaultColors, FALSE);
  dc->defaultColors = NULL;
}


/* Create the colors that Dotter will use for various specific purposes */
static void createDotterColors(DotterContext *dc)
{
  /* Initialise the array with empty BlxColor structs */
  dc->defaultColors = g_array_sized_new(FALSE, FALSE, sizeof(BlxColor), DOTCOLOR_NUM_COLORS);
  int i = DOTCOLOR_MIN + 1;
  
  for ( ; i < DOTCOLOR_NUM_COLORS; ++i)
    {
      BlxColor *blxColor = new BlxColor;
      blxColor->name = NULL;
      blxColor->desc = NULL;
      g_array_append_val(dc->defaultColors, *blxColor);
    }

  /* Get the default background color of our widgets (i.e. that inherited from the theme).
   * Convert it to a string so we can use the same creation function as the other colors */
  GtkWidget *tmp = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  char *defaultBgColorStr = convertColorToString(&tmp->style->bg[GTK_STATE_NORMAL]);
  createBlxColor(dc->defaultColors, DOTCOLOR_BACKGROUND, "Background", "Background color", defaultBgColorStr, BLX_WHITE, "#bdbdbd", NULL);
  g_free(defaultBgColorStr);
  gtk_widget_destroy(tmp);
  
  /* matches */
  createBlxColor(dc->defaultColors, DOTCOLOR_MATCH, "Exact match", "Exact match", BLX_LIGHT_CYAN, BLX_LIGHT_CYAN, BLX_CYAN, BLX_CYAN);
  createBlxColor(dc->defaultColors, DOTCOLOR_CONS, "Conserved match", "Conserved match", BLX_VIOLET, BLX_VIOLET, BLX_DARK_VIOLET, BLX_DARK_VIOLET);
  createBlxColor(dc->defaultColors, DOTCOLOR_MISMATCH, "Mismatch", "Mismatch", "#cacaca", BLX_WHITE, "#cacaca", BLX_WHITE);
  
  /* exons */
  createBlxColor(dc->defaultColors, DOTCOLOR_EXON_FILL, "Exon fill color", "Exon fill color", BLX_YELLOW, BLX_YELLOW, NULL, NULL);
  createBlxColor(dc->defaultColors, DOTCOLOR_EXON_LINE, "Exon line color", "Exon outline color", BLX_BLUE, BLX_BLUE, NULL, NULL);
  createBlxColor(dc->defaultColors, DOTCOLOR_CDS_FILL, "CDS fill color", "Coding section fill color", BLX_LIGHT_GREEN, BLX_LIGHT_GREEN, NULL, NULL);
  createBlxColor(dc->defaultColors, DOTCOLOR_CDS_LINE, "CDS line color", "Coding section outline color", BLX_DARK_GREEN, BLX_DARK_GREEN, BLX_VERY_DARK_GREEN, BLX_VERY_DARK_GREEN);
  createBlxColor(dc->defaultColors, DOTCOLOR_UTR_FILL, "UTR fill color", "Untranslated region fill color", BLX_LIGHT_RED, BLX_LIGHT_RED, NULL, NULL);
  createBlxColor(dc->defaultColors, DOTCOLOR_UTR_LINE, "UTR line color", "Untranslated region outline color", BLX_DARK_RED, BLX_DARK_RED, BLX_VERY_DARK_RED, BLX_VERY_DARK_RED);

  /* dot plot */
  createBlxColor(dc->defaultColors, DOTCOLOR_CROSSHAIR, "Crosshair", "Color of the crosshair on the dot plot", BLX_BLUE, BLX_BLUE, NULL, NULL);
  createBlxColor(dc->defaultColors, DOTCOLOR_GRID, "Grid", "Line color of the grid on the dot plot", BLX_LIGHT_RED, BLX_LIGHT_RED, NULL, NULL);
  createBlxColor(dc->defaultColors, DOTCOLOR_BORDER, "Grid", "Highlight color for the border where the alignment cannot be calculated", "#ffeeee", "#bbbbbb", NULL, NULL);

  /* greyramp */
  createBlxColor(dc->defaultColors, DOTCOLOR_THRESHOLD_MARKER, "Greyramp threshold marker color", "Outline color of the threshold marker on the greyramp tool", BLX_RED, BLX_RED, BLX_GREEN, BLX_GREEN);
  createBlxColor(dc->defaultColors, DOTCOLOR_MARKER_LINE, "Greyramp marker outline color", "Outline color of the triangle markers on the greyramp tool", BLX_BLACK, BLX_BLACK, BLX_GREEN, BLX_GREEN);
  createBlxColor(dc->defaultColors, DOTCOLOR_MARKER_FILL, "Greyramp marker fill color", "Fill color of the triangle markers on the greyramp tool", BLX_WHITE, BLX_WHITE, NULL, NULL);

  /* misc */
  createBlxColor(dc->defaultColors, DOTCOLOR_BREAKLINE, "Breakline color", "Color of the separator lines between sequences, if there were multiple sequences in the input file", BLX_GREEN, BLX_GREEN, NULL, NULL);
  createBlxColor(dc->defaultColors, DOTCOLOR_CANONICAL, "Canonical", "Canonical splice sites", BLX_GREEN, BLX_GREEN, NULL, NULL);
  createBlxColor(dc->defaultColors, DOTCOLOR_NON_CANONICAL, "Non-canonical", "Non-canonical splice sites", BLX_RED, BLX_RED, NULL, NULL);
}


/* Get the initial zoom factor, calculating it if the passed-in zoom is 0 */
static gdouble getInitZoomFactor(DotterContext *dc, const gdouble zoomFacIn, const int qLen, const int sLen)
{
  DEBUG_ENTER("getInitZoomFactor");

  gdouble result = zoomFacIn;
  
  if (result <= 0)
    {
      if (dc->memoryLimit)
        {
          result = (int)sqrt((qLen / dc->numFrames / 1e6 * sLen - 1e-6) / dc->memoryLimit) + 1;
        }
      else
        {
          g_error("Cannot calculate zoom; division by 0 (memory limit is 0).\n");
        }
    }
  
  DEBUG_EXIT("getInitZoomFactor returning %f", result);
  return result;
}


static DotterContext* createDotterContext(DotterOptions *options,
                                          BlxBlastMode blastMode, 
                                          const gboolean showWindow,
                                          const BlxStrand refSeqStrand,
                                          const BlxStrand matchSeqStrand,
                                          MSP *mspList,
                                          GList *seqList,
                                          int matrix[24][24],
                                          char *matrixName)
{
  DEBUG_ENTER("createDotterContext");

  DotterContext *result = new DotterContext;
  
  result->blastMode = blastMode;
  result->displaySeqType = (blastMode == BLXMODE_BLASTN) ? BLXSEQ_DNA : BLXSEQ_PEPTIDE;
  result->numFrames = (blastMode == BLXMODE_BLASTX) ? 3 : 1;
  result->geneticCode = stdcode1;
  mtxcpy(result->matrix, matrix);
  result->matrixName = matrixName;
  result->mspList = mspList;
  result->seqList = seqList;
  result->windowList = NULL;
  result->abbrevTitle = options->abbrevTitle;
  
  result->watsonOnly = options->watsonOnly;
  result->crickOnly = options->crickOnly;
  
  /* Set the fixed-width font (not applicable in batch mode) */
  if (showWindow)
    {
      GtkWidget *tmp = gtk_window_new(GTK_WINDOW_TOPLEVEL);
      const char *fontFamily = findFixedWidthFont(tmp);
      result->fontDesc = pango_font_description_from_string(fontFamily);
      pango_font_description_set_size(result->fontDesc, pango_font_description_get_size(tmp->style->font_desc));
      getFontCharSize(tmp, result->fontDesc, &result->charWidth, &result->charHeight);
      gtk_widget_destroy(tmp);
    }
  else
    {
      result->fontDesc = NULL;
    }
  
  result->refSeqName = g_strdup(options->qname);
  result->refSeq = options->qseq; /* take ownership of passed-in seq */
  result->refSeqRev = NULL;
  result->refSeqType = (blastMode == BLXMODE_BLASTP ? BLXSEQ_PEPTIDE : BLXSEQ_DNA);
  
  /* for dna ref sequences, reverse-complement the ref seq */
  if (result->refSeqType == BLXSEQ_DNA && result->refSeq)
    {
      result->refSeqRev = (char*)g_malloc(strlen(result->refSeq) + 1);
      revComplement(result->refSeqRev, result->refSeq);
    }
  else if (result->refSeq)
    {
      /* Just reverse it */
      result->refSeqRev = g_strdup(result->refSeq);
      g_strreverse(result->refSeqRev);
    }
  
  result->refSeqStrand = refSeqStrand;

  result->matchSeqName = g_strdup(options->sname);
  result->matchSeq = options->sseq; /* take ownership of passed-in seq */
  result->matchSeqRev = NULL;
  result->matchSeqType = (blastMode == BLXMODE_BLASTN ? BLXSEQ_DNA : BLXSEQ_PEPTIDE);
  result->matchSeqStrand = matchSeqStrand;
  
  result->refSeqFullRange.set(options->qoffset + 1, options->qoffset + strlen(options->qseq));
  result->matchSeqFullRange.set(options->soffset + 1, options->soffset + strlen(options->sseq));
  
  result->hozScaleRev = options->hozScaleRev;
  result->vertScaleRev = options->vertScaleRev;
  result->negateCoords = options->negateCoords;
  
  result->displayMirror = options->mirrorImage;
  
  result->memoryLimit = options->memoryLimit;
  
  result->defaultColors = NULL;
  
  
  /* Reverse/comp match seq if applicable */
  if (result->matchSeqType == BLXSEQ_DNA && result->matchSeqStrand == BLXSTRAND_REVERSE && result->matchSeq)
    {
      result->matchSeqRev = (char*)g_malloc(strlen(result->matchSeq) + 1);
      revComplement(result->matchSeqRev, result->matchSeq);
    }
  else if (result->matchSeqStrand == BLXSTRAND_REVERSE && result->matchSeq)
    {
      /* Peptide sequence. Just reverse */
      result->matchSeqRev = g_strdup(result->matchSeq);
      g_strreverse(result->matchSeqRev);
    }
  
  int i = 0;
  for ( ; i < result->numFrames; ++i)
    {
      result->peptideSeqs[i] = NULL;
    }
  
  if (result->blastMode == BLXMODE_BLASTX) 
    {
      /* Create the 3 frame translations (for the strand we're interested in only). */
      const gboolean rev = (result->hozScaleRev);
      char *refSeqToUse = (rev ? result->refSeqRev : result->refSeq);
      
      int i = 0;
      for (i = 0; i < result->numFrames; i++)
        {
          /* Get the start coord at this index and calculate which reading frame it really is
           * (because the first coord in the sequence might not be base 1 in frame 1). */
          const int startCoord = rev ? result->refSeqFullRange.max() - i : result->refSeqFullRange.min() + i;
        
          int frame = UNSET_INT;
          convertToDisplayIdx(startCoord, TRUE, result, 1, &frame);

          result->peptideSeqs[frame - 1] = blxTranslate(refSeqToUse + i, result->geneticCode);

          DEBUG_OUT("Frame %d starts at coord %d for hoz seq strand = %d.\n", frame, startCoord, result->refSeqStrand);
        }
      
      /* Check all of the frames got set */
      for (i = 0; i < result->numFrames; ++i)
        {
          if (result->peptideSeqs[i] == NULL)
            {
              g_error("Error calculating translated sequence for reading frame %d.\n", i + 1);
            }
        }
    }
  
  if (showWindow)
    { 
      createDotterColors(result);
    }
  
  /* Calculate the height and width of the horizontal and vertical scales */
  const int leftBorderChars = max(numDigitsInInt(result->matchSeqFullRange.min()), numDigitsInInt(result->matchSeqFullRange.max())) + 1;
  result->scaleWidth = DEFAULT_MAJOR_TICK_HEIGHT * 2 + (roundNearest)((gdouble)leftBorderChars * result->charWidth) + SCALE_LINE_WIDTH;
  result->scaleHeight = DEFAULT_MAJOR_TICK_HEIGHT + roundNearest(result->charHeight) + SCALE_LINE_WIDTH;
  
  result->msgData = &options->msgData;
  
  DEBUG_EXIT("createDotterContext returning");
  return result;
}


static void destroyDotterContext(DotterContext **dc)
{
  DEBUG_ENTER("destroyDotterContext");

  if ((*dc))
    {
    if ((*dc)->blastMode == BLXMODE_BLASTX)
      {
        int i = 0;
        for ( ; i < (*dc)->numFrames; i++)
          {
            if ((*dc)->peptideSeqs && (*dc)->peptideSeqs[i])
              {
                g_free((*dc)->peptideSeqs[i]);
                (*dc)->peptideSeqs[i] = NULL;
              }
          }
      }
    
    /* destroy the msps, sequence structs and colors */
    destroyMspList(&(*dc)->mspList);
    destroyBlxSequenceList(&(*dc)->seqList);
    destroyDotterColors((*dc));

    /* Free stuff allocated in calling routine (usually dotterMain) */
    g_free((*dc)->refSeq);
    (*dc)->refSeq = NULL;
    
    g_free((*dc)->refSeqName);
    (*dc)->refSeqName = NULL;
    
    g_free((*dc)->matchSeq);
    (*dc)->matchSeq = NULL;
    
    g_free((*dc)->matchSeqName);
    (*dc)->matchSeqName = NULL;

      if ((*dc)->matrixName)
        {
          g_free((*dc)->matrixName);
          (*dc)->matrixName = NULL;
        }
    }  

  /* free the context struct itself */
  delete *dc;
  *dc = NULL;
  
  DEBUG_EXIT("destroyDotterContext returning ");
}

static void destroyDotterWindowContext(DotterWindowContext **dwc)
{
  DEBUG_ENTER("destroyDotterWindowContext");

  if ((*dwc)->printSettings)
    g_object_unref((*dwc)->printSettings);
  
  delete *dwc;
  *dwc = NULL;
  
  DEBUG_EXIT("destroyDotterWindowContext returning ");
}

static DotterProperties* dotterGetProperties(GtkWidget *dotterWindow)
{
  return dotterWindow ? (DotterProperties*)(g_object_get_data(G_OBJECT(dotterWindow), "DotterProperties")) : NULL;
}

static void onDestroyDotterWindow(GtkWidget *dotterWindow)
{
  DEBUG_ENTER("onDestroyDotterWindow");

  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  if (properties)
    {
      if (properties->dotterWinCtx)
        {
          DotterContext *dc = properties->dotterWinCtx->dotterCtx;

          g_object_unref(properties->dotterWinCtx->uiManager);
          properties->dotterWinCtx->uiManager = NULL;

          /* free the context for this window */
          destroyDotterWindowContext(&properties->dotterWinCtx);

          /* if it's the last window, then we also need to destroy the main context
           * and quit the program */
          if (dc && dc->windowList)
            {
              dc->windowList = g_slist_remove(dc->windowList, dotterWindow);

              if (g_slist_length(dc->windowList) < 1)
                {
                  g_slist_free(dc->windowList);
                  dc->windowList = NULL;
                  destroyDotterContext(&dc);
                  gtk_main_quit();
                }
            }
        }

      delete properties;
      properties = NULL;
      g_object_set_data(G_OBJECT(dotterWindow), "DotterProperties", NULL);
    }
  
  DEBUG_EXIT("onDestroyDotterWindow returning ");
}


/* Close all windows associated with the given dotter context */
static void dotterContextCloseAllWindows(DotterContext *dc)
{
  if (!dc || !dc->windowList)
    return;

  /* Can't loop through the list because pointers are removed from it when we destroy the
   * windows. Also, when the last window is destroyed, dc will be destroyed. So: loop while we
   * still have more than one entry in the list. We know we must quit after the last entry. */
  int len = g_slist_length(dc->windowList);
  
  while (len > 0)
    {
      GtkWidget *window = GTK_WIDGET(dc->windowList->data);
      gtk_widget_destroy(window);
      
      if (len == 1) /* just processed the last one so break */
        break;
      else
        len = g_slist_length(dc->windowList);
    }
}

/* "Close" the given window. Only really closes it if it's the main window;
 * for other windows, return false to indicate we haven't handled it. */
static gboolean closeWindow(GtkWidget *widget)
{
  gboolean handled = FALSE;
  const char *name = gtk_widget_get_name(widget);
  
  if (name && strcmp(name, MAIN_WINDOW_NAME) == 0)
    {
      handled = TRUE;
      gtk_widget_destroy(widget);
    }

  return handled;
}


/* Convert a dna index to display (dna or peptide) index, if applicable. If horizontal is true
 * we have the horizontal (reference) sequence, otherwise the vertical (match) sequence. */
int convertToDisplayIdx(const int dnaIdx, const gboolean horizontal, DotterContext *dc, const int frameIn, int *baseNum)
{
  //DEBUG_ENTER("convertToDisplayIdx(dnaIdx=%d, hoz=%d, frameIn=%d)", dnaIdx, horizontal, frameIn);

  int result = dnaIdx;
  
  if (baseNum)
    *baseNum = 1;
  
  /* Match seq coords are always in display coords already, so only do anything if this is the
   * ref seq. Also, we only need to convert if it's peptide-nucleotide match. */
  if (horizontal && dc->blastMode == BLXMODE_BLASTX)
    {
      /* If the strand is reversed, the frame will be inverted; un-invert it first */
      const gboolean rev = (horizontal && dc->hozScaleRev) || (!horizontal && dc->vertScaleRev);
      int frame = frameIn;
      
      double fraction = 0.0;
      
      if (rev)
        fraction = (double)(dnaIdx + frame - 1) / (double)dc->numFrames;
      else
        fraction = (double)(dnaIdx - frame + 1) / (double)dc->numFrames;
      
      DEBUG_OUT("frame=%d, fraction=%f\n", frame, fraction);

      /* Round to the higher value so that 0.3, 0.6 and 1.0 all round
       * to the same value. If values are negative this still works; 0, -0.3
       * and -0.6 will all round to 0.
       *
       * To illustrate (the top section shows nucleotide coords, reading 
       * from top-to-bottom then left-to-right): 
       * 
       *              Display forwards        Display reversed
       * Frame1:         -5 -2  1  4             6  3  0 -3
       * Frame2:         -4 -1  2  5             5  2 -1 -4
       * Frame3:         -3  0  3  6             4  1 -2 -5
       * 
       * Peptide coord:  -1  0  1  2             2  1  0 -1
       *
       * */
      result = ceil(fraction);
    
      /* We want base 1 in the requested reading frame. */
      if (baseNum)
        {
          *baseNum = (dnaIdx - frame + 1) % dc->numFrames;
        
          /* If we have a negative base number, adding 3 shifts it to the
           * correct base number. (This also fixes the fact that mod3 gives 0
           * for base 3.) */
          if (*baseNum < 1)
            *baseNum += dc->numFrames;

          /* invert base number order when the sequence is reversed, i.e. if the mod3 of
           * the coords gives base numbers 123123123 etc then change these to 321321321 etc */
          if (rev)
            {
              *baseNum = dc->numFrames - *baseNum + 1;
            }
        }
    }
  
  //DEBUG_EXIT("convertToDisplayIdx returning %d", result);
  return result;
}


/* Convert a display index (dna or peptide) to a dna index (original sequence coord),
 * if applicable. If horizontal is true we have the horizontal (reference) sequence, 
 * otherwise the vertical (match) sequence. */
int convertToDnaIdx(const int displayIdx, 
                    const gboolean horizontal, 
                    DotterContext *dc, 
                    const int frame, 
                    int baseNum)
{
  DEBUG_ENTER("convertToDnaIdx(displayIdx=%d, hoz=%d, frame=%d, base=%d)", displayIdx, horizontal, frame, baseNum);

  int result = displayIdx;
  
  /* Match seq coords are always in display coords already, so only do anything if this is the
   * ref seq. Also, we only need to convert if it's peptide-nucleotide match. */
  if (horizontal && dc->blastMode == BLXMODE_BLASTX)
    {
      if (dc->hozScaleRev)
        result = (displayIdx * dc->numFrames) - dc->numFrames - frame + baseNum + 1;
      else
        result = (displayIdx * dc->numFrames) - dc->numFrames + frame + baseNum - 1;
      
      DEBUG_OUT("dnaIdx=%d\n", result);
    }
  
  DEBUG_EXIT("convertToDnaIdx returning %d", result);
  return result;
}


static DotterWindowContext* createDotterWindowContext(DotterContext *dotterCtx,
                                                      const IntRange* const refSeqRange,
                                                      const IntRange* const matchSeqRange,
                                                      const gdouble zoomFacIn,
						      const gboolean showWindow)
{
  DEBUG_ENTER("createDotterWindowContext");

  DotterWindowContext *result = new DotterWindowContext;
  
  result->dotterCtx = dotterCtx;
  
  result->refSeqRange.set(refSeqRange);
  result->matchSeqRange.set(matchSeqRange);

  result->refCoord = UNSET_INT;
  result->matchCoord = UNSET_INT;
  
  result->zoomFactor = getInitZoomFactor(dotterCtx, zoomFacIn, refSeqRange->length(), matchSeqRange->length());

  /* See if we're comparing the same portion of sequence against itself */
  result->selfComp = (refSeqRange->min() == matchSeqRange->min() && 
                      refSeqRange->max() == matchSeqRange->max() &&
                      stringsEqual(dotterCtx->refSeq, dotterCtx->matchSeq, FALSE));

  result->usePrintColors = FALSE;

  if (showWindow) 
    {
      result->pageSetup = gtk_page_setup_new();
      gtk_page_setup_set_orientation(result->pageSetup, GTK_PAGE_ORIENTATION_LANDSCAPE);
      
      result->printSettings = gtk_print_settings_new();
      gtk_print_settings_set_orientation(result->printSettings, GTK_PAGE_ORIENTATION_LANDSCAPE);
      gtk_print_settings_set_quality(result->printSettings, GTK_PRINT_QUALITY_HIGH);
      gtk_print_settings_set_resolution(result->printSettings, DEFAULT_PRINT_RESOLUTION);
    }
  else 
    {
      result->pageSetup = NULL;
      result->printSettings = NULL;
    }

  /* Null out all the entries in the dialogs list */
  int dialogId = 0;
  for ( ; dialogId < DOTDIALOG_NUM_DIALOGS; ++dialogId)
    {
      result->dialogList[dialogId] = NULL;
    }
  
  DEBUG_EXIT("createDotterWindowContext returning");
  return result;
}

/* properties specific to a particular dotter window */
static void dotterCreateProperties(GtkWidget *dotterWindow, 
                                   GtkWidget *greyrampTool, 
                                   GtkWidget *greyrampWindow,
                                   GtkWidget *greyrampContainer,
                                   GtkWidget *greyrampToolMinimised,
                                   GtkWidget *alignmentTool,
                                   GtkWidget *alignmentWindow,
                                   GtkWidget *alignmentContainer,
                                   GtkWidget *dotplot,
                                   DotterWindowContext *dotterWinCtx,
                                   const char *exportFileName)
{
  DEBUG_ENTER("dotterCreateProperties");

  if (dotterWindow)
    {
      DotterProperties *properties = new DotterProperties;

      properties->widget = dotterWindow;
      properties->greyrampTool = greyrampTool;
      properties->greyrampWindow = greyrampWindow;
      properties->greyrampContainer = greyrampContainer;
      properties->greyrampToolMinimised = greyrampToolMinimised;
      properties->alignmentTool = alignmentTool;
      properties->alignmentWindow = alignmentWindow;
      properties->alignmentContainer = alignmentContainer;
      properties->dotplot = dotplot;
      properties->windowsDocked = DOCK_WINDOWS_DEFAULT;
      properties->dotterWinCtx = dotterWinCtx;
      properties->exportFileName = exportFileName;
      
      g_object_set_data(G_OBJECT(dotterWindow), "DotterProperties", properties);
      g_signal_connect(G_OBJECT(dotterWindow), "destroy", G_CALLBACK(onDestroyDotterWindow), NULL); 
    }
  
  DEBUG_EXIT("dotterCreateProperties returning ");
}


/* Utility to extract the dotter context from the dotter window properties */
static DotterContext* dotterGetContext(GtkWidget *dotterWindow)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  return properties ? properties->dotterWinCtx->dotterCtx : NULL;
}


/* Perform required updates following a change to the currently-selected coords */
static void updateOnSelectedCoordsChanged(GtkWidget *dotterWindow)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  /* Make sure the coords are in range */
  boundsLimitValue(&properties->dotterWinCtx->refCoord, &properties->dotterWinCtx->refSeqRange);
  boundsLimitValue(&properties->dotterWinCtx->matchCoord, &properties->dotterWinCtx->matchSeqRange);
  
  /* Update the alignment view and dotplot */
  updateAlignmentRange(properties->alignmentTool, properties->dotterWinCtx);
  alignmentToolRedrawAll(properties->alignmentTool);
  
  /* Need to clear cached drawables for the alignment tool but can just refresh the dotplot */
  widgetClearCachedDrawable(properties->alignmentTool, NULL);
  refreshDotplot(properties->dotplot);
}


/* Set the initial currently-selected ref seq and match seq coords (i.e. the coords 
 * where the crosshair is centred) */
static void setInitSelectedCoords(GtkWidget *dotterWindow, const int refCoord, const int matchCoord)
{
  DEBUG_ENTER("setInitSelectedCoords");

  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  
  if (valueWithinRange(refCoord, &dwc->refSeqRange))
    dwc->refCoord = refCoord;
  else
    dwc->refCoord = dwc->refSeqRange.centre();

  if (valueWithinRange(matchCoord, &dwc->matchSeqRange))
    dwc->matchCoord = matchCoord;
  else
    dwc->matchCoord = dwc->matchSeqRange.centre();
  
  updateOnSelectedCoordsChanged(dotterWindow);
  
  DEBUG_EXIT("setInitSelectedCoords returning ");
}


/***********************************************************
 *                    External routines                    *
 ***********************************************************/



void dotter (const BlxBlastMode blastMode,
             DotterOptions *options,
             const BlxStrand refSeqStrand,
             const BlxStrand matchSeqStrand,
              int   qcenter,
              int   scenter,
              MSP  *mspList,
              GList *seqList,
             int   MSPoff)
{
  DEBUG_ENTER("dotter(mode=%d, qname=%s, qoff=%d, qstrand=%d, sname=%s, soff=%d, sstrand=%d)",
              blastMode, options->qname, options->qoffset, refSeqStrand, options->sname, options->soffset, matchSeqStrand);
  
  const int qlen = strlen(options->qseq);
  const int slen = strlen(options->sseq);
  
  if (qlen < 1) g_error("queryseq is empty\n");
  if (slen < 1) g_error("subjectseq is empty\n");

  int i = 0;
  for (i = 0; i < qlen; i++) options->qseq[i] = toupper(options->qseq[i]);
  for (i = 0; i < slen; i++) options->sseq[i] = toupper(options->sseq[i]);

  if (!options->memoryLimit) 
    {
      options->memoryLimit = 0.5; /* Mb */
    }

  /* Get score matrix */
  char *matrixName = (char*)g_malloc((MAX_MATRIX_NAME_LENGTH + 1) * sizeof(char));
  
  if (options->mtxfile) 
    {
      readmtx(MATRIX, options->mtxfile);
      strncpy(matrixName, options->mtxfile, MAX_MATRIX_NAME_LENGTH);
    }
  else if (blastMode == BLXMODE_BLASTN) 
    {
      DNAmatrix(MATRIX);
      strcpy(matrixName, "DNA+5/-4");
    }
  else
    {
      mtxcpy(MATRIX, BLOSUM62);
      strcpy(matrixName, "BLOSUM62");
    }

  /* If a save/export file was given, that implies we're in batch mode.
   * We don't display the window in batch mode, unless we're exporting to PDF, in
   * which case we need to create the window so that we have something to print  */
  const gboolean batchMode = (options->savefile || options->exportfile);
  const gboolean createWindow = options->exportfile || !batchMode;
  
  if (batchMode) 
    {
      /* Don't do batch processing if output file can't be opened */
      if (options->savefile && !fopen (options->savefile, "wb"))
        g_error("Failed to open %s\n", options->savefile);

      if (options->exportfile && !fopen (options->exportfile, "wb"))
        g_error("Failed to open %s\n", options->exportfile);
    }
  
  /* Create the main dotter context (shared properties for all dotter windows in this process) */
  DotterContext *dotterCtx = createDotterContext(options, blastMode, createWindow, refSeqStrand, matchSeqStrand, mspList, seqList, MATRIX, matrixName);

  /* Create a context specific to the initial dotter window */
  DotterWindowContext *dotterWinCtx = createDotterWindowContext(dotterCtx, &dotterCtx->refSeqFullRange, &dotterCtx->matchSeqFullRange, options->dotterZoom, createWindow);

  /* Create the widgets */
  createDotterInstance(dotterCtx, 
                       dotterWinCtx,
                       options->loadfile,
                       options->savefile,
                       options->exportfile,
                       options->hspsOnly,
                       options->breaklinesOn,
                       options->winsize,
                       options->pixelFacset,
                       options->dotterZoom,
                       qcenter,
                       scenter,
                       options->swapGreyramp,
                       options->windowColor);

  DEBUG_EXIT("dotter returning");
  return ;
}


/* Create all the widgets for a dotter instance. Uses the existing dotter context. Multiple
 * instances (i.e. multiple dotter windows) can exist that share the same main context but display
 * a different range of coords etc,. This creates the widgets and shows them. */
static GtkWidget* createDotterInstance(DotterContext *dotterCtx,
                                       DotterWindowContext *dotterWinCtx,
                                       const char *loadFileName,
                                       const char *saveFileName,
                                       const char *exportFileName,
                                       const gboolean hspsOn,
                                       const gboolean breaklinesOn,
                                       const char* winsizeIn,
                                       const int pixelFacIn,
                                       const int zoomFacIn,
                                       const int qcenter,
                                       const int scenter,
                                       const gboolean greyrampSwap,
                                       char *windowColor)
{
  DEBUG_ENTER("createDotterInstance");

  GtkWidget *dotterWindow = NULL;

  GtkWidget *dotplot = NULL;
  GtkWidget *dotplotWidget = createDotplot(dotterWinCtx, 
                                           loadFileName,
                                           saveFileName,
                                           exportFileName,
                                           hspsOn,
                                           breaklinesOn,
                                           winsizeIn,
                                           pixelFacIn,
                                           zoomFacIn,
                                           qcenter,
                                           scenter,
                                           &dotplot);
  
  /* Only create the graphical elements if there is a graphical dotplot widget */
  if (dotplotWidget)
    {
      GtkWidget *greyrampContainer = gtk_frame_new(NULL); /* container for when docked */
      gtk_frame_set_shadow_type(GTK_FRAME(greyrampContainer), GTK_SHADOW_NONE);
      GtkWidget *greyrampWindow = NULL; /* container for when undocked */
      GtkWidget *greyrampTool = createGreyrampTool(dotterWinCtx, 40, 100, greyrampSwap, &greyrampWindow);
      GtkWidget *greyrampToolMinimised = createGreyrampToolMinimised(dotterWinCtx, 40, 100);
      registerGreyrampCallback(greyrampTool, dotplot, dotplotUpdateGreymap);
      registerGreyrampCallback(greyrampToolMinimised, dotplot, dotplotUpdateGreymap);
      blxSetWidgetColor(greyrampWindow, windowColor);

      GtkWidget *alignmentContainer = gtk_frame_new(NULL); /* container for when docked */
      gtk_frame_set_shadow_type(GTK_FRAME(alignmentContainer), GTK_SHADOW_NONE);
      GtkWidget *alignmentWindow = NULL; /* container for when undocked */
      GtkWidget *alignmentTool = createAlignmentTool(dotterWinCtx, &alignmentWindow);
      blxSetWidgetColor(alignmentWindow, windowColor);

      if (DOCK_WINDOWS_DEFAULT)
        {
          /* Dock into containers that will go into the main window */
          gtk_container_add(GTK_CONTAINER(alignmentContainer), alignmentTool);
          gtk_container_add(GTK_CONTAINER(greyrampContainer), greyrampTool);
        }
      else
        {
          /* Add to the separate toplevel windows */
          gtk_container_add(GTK_CONTAINER(alignmentWindow), alignmentTool);
          gtk_container_add(GTK_CONTAINER(greyrampWindow), greyrampTool);
        }
  
      const DotterHspMode hspMode = dotplotGetHspMode(dotplot);
      dotterWindow = createDotterWindow(dotterCtx, dotterWinCtx, hspMode, 
                                        dotplot, dotplotWidget, 
                                        greyrampContainer, alignmentContainer, 
                                        greyrampTool, alignmentTool, greyrampToolMinimised,
                                        exportFileName, windowColor);
      
      /* Set the tool windows as transient for the main window and clear them up when the
       * main window is destroyed */
      gtk_window_set_transient_for(GTK_WINDOW(greyrampWindow), GTK_WINDOW(dotterWindow));
      gtk_window_set_transient_for(GTK_WINDOW(alignmentWindow), GTK_WINDOW(dotterWindow));
      gtk_window_set_destroy_with_parent(GTK_WINDOW(greyrampWindow), TRUE);
      gtk_window_set_destroy_with_parent(GTK_WINDOW(alignmentWindow), TRUE);

      /* Set the handlers for the alignment and greyramp tools. Connect them here so we can pass
       * the main window as data. */
      gtk_widget_add_events(alignmentWindow, GDK_KEY_PRESS_MASK);
      gtk_widget_add_events(greyrampWindow, GDK_KEY_PRESS_MASK);
      g_signal_connect(G_OBJECT(alignmentWindow), "key-press-event", G_CALLBACK(onKeyPressDotter), dotterWindow);
      g_signal_connect(G_OBJECT(greyrampWindow), "key-press-event", G_CALLBACK(onKeyPressDotter), dotterWindow);

      /* Keep track of all the windows we create, so that we can destroy the DotterContext when
       * the last one is closed */
      dotterCtx->windowList = g_slist_append(dotterCtx->windowList, dotterWindow);
      
      dotterCreateProperties(dotterWindow, 
                             greyrampTool, greyrampWindow, greyrampContainer, greyrampToolMinimised,
                             alignmentTool, alignmentWindow, alignmentContainer,
                             dotplot, dotterWinCtx, exportFileName);
      DotterProperties *properties = dotterGetProperties(dotterWindow);
      
      setInitSelectedCoords(dotterWindow, qcenter, scenter);
      
      updateGreyMap(properties->greyrampTool);

      if (MINIMISE_GREYRAMP_DEFAULT)
        {
          /* Hide the full greyramp tool (this shows the minimised version instead) */
          setToggleMenuStatus(properties->dotterWinCtx->actionGroup, "ToggleGreyramp", FALSE);
        }
    }
  
  DEBUG_EXIT("createDotterInstance returning ");
  return dotterWindow;
}


/* Open another dotter window, internal to the existing process (i.e. using the same sequences
 * etc. but just displaying a different range). */
void callDotterInternal(DotterContext *dc, 
                        const IntRange* const refSeqRange,
                        const IntRange* const matchSeqRange,
                        const gdouble zoomFactor,
                        const gboolean breaklinesOn)
{
  DotterWindowContext *dwc = createDotterWindowContext(dc, refSeqRange, matchSeqRange, zoomFactor, TRUE);
  createDotterInstance(dc, dwc, NULL, NULL, NULL, FALSE, breaklinesOn, NULL, 0, 0, 0, 0, FALSE, NULL);
}



/***********************************************************
 *                    External routines                    *
 ***********************************************************/

/* RMEXP will subtract the expected score to remove background noise
   due to biased composition. Gos's idea - not explored yet.

static void rmExp(void){}
*/


///* Utility to return the Feature Series that the given MSP belongs to */
//static FeatureSeries* mspGetFeatureSeries(const MSP *msp)
//{
//  return msp->fs;
//}


/* Returns true if this MSP is part of a Feature Series and that feature series is currently displayed */
//static gboolean mspShowFs(const MSP *msp)
//{
//  FeatureSeries *fs = mspGetFeatureSeries(msp);
//  return (fs && fs->on);
//}


/* Return the y position of the lower edge of a feature-series MSP, given its height.
   Calculate it if it is not set yet. Updates the max y coord to be the lower edge of
   this MSP. Returns 0 if the MSP is not in a Feature Series */
//float mspGetFsBottomEdge(MSP *msp, float *maxy, float height)
//{
//  float result = 0;
//  
//  FeatureSeries *fs = mspGetFeatureSeries(msp);
//  
//  if (fs)
//    {
//      result = fs->y;
//
//      if (!result)
//        {
//          *maxy += height;
//          fs->y = *maxy;
//          result = *maxy;
//        }
//    }
//  
//  return result;
//}


/* Return the x position of the rightmost edge of a feature-series MSP, given its height.
   Calculae it if it is not yet set. Updates the max x coord to be the rightmost edge of
   this MSP. Returns 0 if the MSP is not in a FeatureSeries */
//float mspGetFsRightEdge(MSP *msp, float *maxx, float height)
//{
//  float result = 0;
//
//  FeatureSeries *fs = mspGetFeatureSeries(msp);
//
//  if (fs)
//    {
//      result = fs->x;
//      
//      if (!result)
//        {
//          *maxx += height;
//          fs->x = *maxx;
//          result = *maxx;
//        }
//    }
//  
//  return result;
//}


//static float seq2graphX(int pos)
//{
//    float x;
//
//    x = ceil((float)(pos + MSPoffset - qoffset)/zoom/resfac);
//
//    if (reversedScale)
//      x = RightBorder - x;
//    else
//      x += LeftBorder-1;
//
//    return x;
//}
//
//static float seq2graphY(int pos)
//{
//    float y;
//
//    y = ceil((float)(pos - soffset)/zoom);
//    
//    y += TopBorder-1;
//
//    return y;
//}


//static void XdrawSEG(MSP *msp, float offset)
//{
//    /* Horizontal axis */
//
//    float  
//      sx = seq2graphX(mspGetQStart(msp)), 
//      ex = seq2graphX(mspGetQEnd(msp));
//    
//    offset += TopBorder + slen4 -1;
//    oldcolor = graphColor(msp->fsColor); oldLinew = graphLinewidth(.25);
//
//    if (fsEndLinesOn) {
//      graphLine(sx, TopBorder, sx, TopBorder+slen4-2);
//      graphLine(ex, TopBorder, ex, TopBorder+slen4-2);
//    }
//
//    graphFillRectangle(sx, offset, ex, offset - msp->score/100.0 * fonth);
//    graphColor(BLACK);
//    graphRectangle(sx, offset, ex, offset - msp->score/100.0 * fonth);
//
//    graphColor(BLACK);
//    if (fsAnnBottomOn && msp->desc) {
//      graphText(msp->desc, sx, offset);
//    }    
//    graphColor(oldcolor); graphLinewidth(oldLinew);
//}


//static void XdrawSEGxy(MSP *msp, float offset)
//{
//    int i, inNotFilled=0, descShown=0;
//    float  
//      x, y, 
//      xold=0, yold=0;
//
//    offset += TopBorder + slen4 -1;
//    oldcolor = graphColor(msp->fsColor); oldLinew = graphLinewidth(.25);
//
//    for (i = 0; i < qlen; i++)
//      {
//      const int xyVal = g_array_index(msp->xy, int, i);
//
//      if (xyVal == XY_NOT_FILLED)
//        {
//          inNotFilled = 1;
//        }
//      else
//        {
//          x = seq2graphX(i);
//          y = offset-1 - (float)xyVal / 100 * fsPlotHeight * fonth;
//          
//          if (xold && (x != xold || y != yold) && (!inNotFilled || msp->fsShape == BLXCURVE_INTERPOLATE))
//            {
//              graphLine(xold, yold, x, y);
//              
//              if (fsAnnBottomOn && msp->desc && !descShown)
//                {
//                  int linecolor = graphColor(BLACK);
//                  graphText(msp->desc, xold, offset);
//                  graphColor(linecolor);
//                  descShown = 1;
//                }
//            }
//              
//          xold = x;
//          yold = y;
//          inNotFilled = 0;
//        }
//      }
//    
//    graphColor(oldcolor); graphLinewidth(oldLinew);
//}
//
//
//static void YdrawSEG(MSP *msp, float offset)
//{
//    /* Vertical axis */
//
//    float  
//      sx = seq2graphY(mspGetQStart(msp)), 
//      ex = seq2graphY(mspGetQEnd(msp));
//    
//    offset += LeftBorder + qlen4 -1;
//    oldcolor = graphColor(msp->fsColor); oldLinew = graphLinewidth(.25);
//
//    if (fsEndLinesOn) {
//      graphLine(LeftBorder, sx, LeftBorder+qlen4-2, sx);
//      graphLine(LeftBorder, ex, LeftBorder+qlen4-2, ex);
//    }
//
//    graphFillRectangle(offset, sx, offset - msp->score/100.0 * fonth, ex);
//    graphColor(BLACK);
//    graphRectangle    (offset, sx, offset - msp->score/100.0 * fonth, ex);
//
//    graphColor(BLACK);
//    if (fsAnnRightOn && msp->desc) {
//      graphText(msp->desc, offset, sx);
//    }    
//    graphColor(oldcolor); graphLinewidth(oldLinew);
//}
//
//
//static void YdrawSEGxy(MSP *msp, float offset)
//{
//    int i, inNotFilled=0, descShown=0;
//    float  
//      x, y, 
//      xold=0, yold=0;
//
//    offset += LeftBorder + qlen4 -1;
//    oldcolor = graphColor(msp->fsColor); oldLinew = graphLinewidth(.25);
//
//    for (i = 0; i < qlen; i++)
//      {
//      const int xyVal = g_array_index(msp->xy, int, i);
//      
//      if (xyVal == XY_NOT_FILLED)
//        {
//          inNotFilled = 1;
//        }
//      else
//        {
//          x = seq2graphY(i);
//          y = offset-1 - (float)xyVal / 100 * fsPlotHeight * fonth;
//          
//          if (xold && (x != xold || y != yold) && (!inNotFilled || msp->fsShape == BLXCURVE_INTERPOLATE)) 
//            {
//              graphLine(yold, xold, y, x);
//              
//              if (fsAnnRightOn && msp->desc && !descShown) 
//                {
//                  int linecolor = graphColor(BLACK);
//                  graphText(msp->desc, offset, xold);
//                  graphColor(linecolor);
//                  descShown = 1;
//                }
//            }
//
//          xold = x;
//          yold = y;
//          inNotFilled = 0;
//        }
//      }
//    
//    graphColor(oldcolor); graphLinewidth(oldLinew);
//}


//static int isHorizontalMSP(MSP *msp) {
//
//    if (!msp->qname)
//      g_error("No qname set in MSP - I need this to associate it with one of the sequences");
//
//    if (!strcasecmp(msp->qname, qname) || !strcmp(msp->qname, "@1"))
//        return 1;
//    else
//        return 0;
//}
//
//
//static int isVerticalMSP(MSP *msp) {
//
//    if (!msp->qname) 
//      g_error("No qname set in MSP - I need this to associate it with one of the sequences");
//
//    if (!strcasecmp(msp->qname, sname) || !strcmp(msp->qname, "@2"))
//        return 1;
//    else
//        return 0;
//}


//static void drawAllFeatures(MSP *msp)
//{
//  float sx, ex, 
//    y, 
//    height,           /* box height/width */
//    boxHeight=10,
//    textHeight,
//    oldLinew;
//  int i;
//  float posx=0, posy=0;               /* Next series to be drawn */
//
//  int top, bottom ;
//  float feature_boundary, feature_top, feature_bottom, feature_strand ;
//  float forward_y, reverse_y, depth ;
//  float old_line_width ;
//
//
//  /* Set forward/reverse strand gene drawing positions. */
//  graphGetBounds(&top, &bottom) ;
//  feature_boundary = 3.0 ;                                /* Allows for line thickness etc... */
//  feature_top = TopBorder + slen4 ;
//  feature_bottom = bottom ;
//  feature_strand = feature_top + ((feature_bottom - feature_top + 1) / 2) ;
//
//  forward_y = feature_top + feature_boundary ;
//  reverse_y = feature_strand + feature_boundary ;
//  depth = (feature_strand - feature_boundary) - (feature_top + feature_boundary) - fonth ;
//
//
//  /* Draw a strand separator. */
//  old_line_width = graphLinewidth(2) ;
//  graphLine(LeftBorder - 1, feature_strand, LeftBorder - 1 + qlen4, feature_strand) ;
//  graphLinewidth(old_line_width) ;
//
//
//  /* Now draw the genes. */
//  drawGenes(msp, forward_y, reverse_y, depth) ;
//
//
//  if (fsArr)
//    {
//      /* Loop through each feature-series in the feature-series array and set coords to 0 */
//      for (i = 0; i < gArrayGetLen(fsArr); i++)
//      {
//        FeatureSeries *fs = &g_array_index(fsArr, FeatureSeries, i);
//        fs->y = fs->x = 0;
//      }
//    }
//
//  textHeight = fonth;
//  boxHeight = fonth;
//
//  oldLinew = graphLinewidth(1);
//
//  BlxStrand strand = BLXSTRAND_NONE;
//  
//  if (selfcomp || !reversedScale) 
//    strand = BLXSTRAND_FORWARD;
//  else 
//    strand = BLXSTRAND_REVERSE;
//
//
//  for (; msp; msp = msp->next)
//    {    
//      height = boxHeight;
//
//      if (mspHasFs(msp))
//      {
//        sx = seq2graphX(mspGetQStart(msp));
//        ex = seq2graphX(mspGetQEnd(msp));
//
//        if (msp->qStrand != strand)
//          y = reverse_y ;
//        else
//          y = forward_y ;
//
//          if (!mspShowFs(msp))
//          continue;
//
//        /* Adjust height to score */
//        if (msp->score > 0)
//          {
//            height = boxHeight * msp->score / 100.0;
//          }
//
//        if (fsBottomOn && (isHorizontalMSP(msp) || (selfcomp && isVerticalMSP(msp))))
//          {
//            /* HORIZONTAL AXIS (X) */
//                  
//            if (msp->type == BLXMSP_XY_PLOT)
//              {
//                XdrawSEGxy(msp, mspGetFsRightEdge(msp, &posx, fonth*(fsPlotHeight+1)));
//              }
//            else if (msp->type == BLXMSP_FS_SEG)
//              {
//                XdrawSEG(msp, mspGetFsRightEdge(msp, &posx, boxHeight+textHeight));
//              }
//          }
//
//        if (fsRightOn &&  (isVerticalMSP(msp) || (selfcomp && isHorizontalMSP(msp))))
//          {
//            /* VERTICAL AXIS (Y) */
//
//            if (msp->type == BLXMSP_XY_PLOT)
//              {
//                YdrawSEGxy(msp, mspGetFsBottomEdge(msp, &posy, fonth*(fsPlotHeight+1)));
//              }
//            else if (msp->type == BLXMSP_FS_SEG)
//              {
//                YdrawSEG(msp, mspGetFsBottomEdge(msp, &posy, boxHeight+textHeight));
//              }
//          }
//
//        graphColor(oldcolor); 
//        graphLinewidth(oldLinew);
//      }
//    }
//
//  return ;
//}


//static void drawGenes(MSP *msp, float forward_y, float reverse_y, float depth)
//{
//  gboolean bump_genes = FALSE ;                                   /* Make this user settable... */
//
//  float height,               /* box height/width */
//    sy, ey, midy, x, y, oldLinew ;
//
//  height = fonth ;
//
//  oldLinew = graphLinewidth(1);
//
//  BlxStrand strand = BLXSTRAND_NONE;
//  if (selfcomp || !reversedScale) 
//    strand = BLXSTRAND_FORWARD;
//  else 
//    strand = BLXSTRAND_REVERSE;
//
//
//  if (bump_genes)
//    {
//      MSP *gene_msp, *tmp ;
//      GList *exon_intron_list = NULL ;
//      GeneStrandStruct strand_genes = {NULL} ;
//
//      /* MSP's are in any old order and only some are exons/introns, here we make a list of
//       * intron/exon MSP's and then sort that list into transcripts for drawing... */
//
//      /* Sort all introns/exons by gene and position within gene. */
//      gene_msp = tmp = msp ;
//      for ( ; tmp ; tmp = tmp->next)
//      {
//        if (tmp->score < 0)
//          exon_intron_list = g_list_append(exon_intron_list, tmp) ;
//      }
//      exon_intron_list = g_list_sort(exon_intron_list, compareMSPs) ;
//
//
//#ifdef ED_G_NEVER_INCLUDE_THIS_CODE
//      g_list_foreach(exon_intron_list, printMSP, NULL) ;
//#endif /* ED_G_NEVER_INCLUDE_THIS_CODE */
//
//
//      /* Produce two lists, one for each strand, of genes sorted by position from the sorted intron/exon list. */
//      strand_genes.strand = '+' ;
//      g_list_foreach(exon_intron_list, getGenePositionsCB, &strand_genes) ;
//      strand_genes.forward_genes = g_list_sort(strand_genes.forward_genes, compareGenes) ;
//      strand_genes.forward_genes = g_list_first(strand_genes.forward_genes) ;
//
//      strand_genes.strand = '-' ;
//      g_list_foreach(exon_intron_list, getGenePositionsCB, &strand_genes) ;
//      strand_genes.reverse_genes = g_list_sort(strand_genes.reverse_genes, compareGenes) ;
//      strand_genes.reverse_genes = g_list_first(strand_genes.reverse_genes) ;
//
//      /* Set y offsets for forward and reverse stranded genes. */
//      setYoffsets(strand_genes.forward_genes, forward_y, forward_y + depth) ;
//      setYoffsets(strand_genes.reverse_genes, reverse_y, reverse_y + depth) ;
//
//
//#ifdef ED_G_NEVER_INCLUDE_THIS_CODE
//      printf("Forward:\n") ;
//      g_list_foreach(strand_genes.forward_genes, printGene, NULL) ;
//      printf("Reverse:\n") ;
//      g_list_foreach(strand_genes.reverse_genes, printGene, NULL) ;
//      printf("\n") ;
//#endif /* ED_G_NEVER_INCLUDE_THIS_CODE */
//
//      /* Draw the strands. */
//      oldcolor = graphColor(BLUE); 
//      g_list_foreach(strand_genes.forward_genes, drawGenesCB, &strand_genes) ;
//
//      oldcolor = graphColor(MAGENTA); 
//      g_list_foreach(strand_genes.reverse_genes, drawGenesCB, &strand_genes) ;
//
//      graphColor(oldcolor); 
//
//    }
//  else
//    {
//      for (; msp; msp = msp->next)
//      {    
//        if (msp->score < 0)
//          {
//            if (msp->qStrand != strand)
//              y = reverse_y ;
//            else
//              y = forward_y ;
//
//            oldcolor = graphColor(BLUE); 
//            drawMSPGene(msp, y) ;
//
//            if (selfcomp) /* Draw the boxes on vertical axes too */
//              {
//                sy = ceil((float)(mspGetQStart(msp)+MSPoffset - qoffset)/zoom);
//                ey = ceil((float)(mspGetQEnd(msp)+MSPoffset - qoffset)/zoom);
//              
//                sy += TopBorder-1;
//                ey += TopBorder-1;
//              
//                x = LeftBorder + qlen4 + 10;
//                if (msp->qStrand != strand) x += 20;
//              
//                if (msp->score == -1.0) /* EXON */
//                  {
//                    oldcolor = graphColor(BLUE); 
//                    graphRectangle(x, sy, x + height, ey);
//                  }
//                else if (msp->score == -2.0) /* INTRON */
//                  {
//                    oldcolor = graphColor(BLUE); 
//                    midy = 0.5 * (sy + ey) ;
//                    graphLine (x + height/2, sy, x, midy) ;
//                    graphLine (x + height/2, ey, x, midy) ;
//                  }
//              }
//
//            graphColor(oldcolor) ;
//          }
//      }
//    }
//
//  graphLinewidth(oldLinew) ;
//
//  return ;
//}


/* A GCompareFunc() to compare gene MSPs.... */
//gint compareMSPs(gconstpointer a, gconstpointer b)
//{
//  int result = 0 ;
//  MSP *msp_a = (MSP *)a, *msp_b = (MSP *)b ;
//
//  if (!(result = strcmp(msp_a->sname, msp_b->sname)))
//    {
//      if (mspGetSStart(msp_a) < mspGetSStart(msp_b))
//      result = -1 ;
//      else if (mspGetSStart(msp_a) > mspGetSStart(msp_b))
//      result = 1 ;
//      else
//      {
//        /* I actually don't think this should ever happen as it means either there are
//         * duplicates or worse there are overlapping introns/exons within a gene.... */
//        if (mspGetSEnd(msp_a) < mspGetSEnd(msp_b))
//          result = -1 ;
//        else if (mspGetSEnd(msp_a) > mspGetSEnd(msp_b))
//          result = 1 ;
//        else
//          result = 0 ;
//      }
//    }
//
//  return result ;
//}


///* A GFunc() to record start/end of genes. */
//static void getGenePositionsCB(gpointer data, gpointer user_data)
//{
//  MSP *msp = (MSP *)data ;
//  GeneStrand strand_genes = (GeneStrand)user_data ;
//  GList *gene_list ;
//  GeneData gene ;
//
//  /* We need genes added according to strand... */
//  if (msp->qframe[1] == strand_genes->strand)
//    {
//      const char *curr_name = NULL ;
//      int curr_length ;
//
//      if (strand_genes->strand == '+')
//      gene_list = strand_genes->forward_genes ;
//      else
//      gene_list = strand_genes->reverse_genes ;
//
//      if (gene_list)
//      {
//        /* Look at last element, this is the last gene we added. */
//        gene_list = g_list_last(gene_list) ;
//
//        curr_name = (((GeneData)(gene_list->data))->name) ;
//        curr_length = strlen(curr_name) - 1 ;
//      }
//
//      /* If there's no gene or we are starting a new gene then just add to the list,
//       * otherwise record latest msp end position. */
//      if (!gene_list || strncmp(mspGetSName(msp), curr_name, curr_length) != 0)
//      {
//        gene = new GeneDataStruct ;
//        gene->name = mspGetSName(msp) ;
//        gene->start = mspGetSStart(msp) ;
//        gene->end = mspGetSEnd(msp) ;
//        gene->strand = msp->qframe[1] ;
//        gene->msp_start = msp ;
//
//        gene_list = g_list_append(gene_list, gene) ;
//      }
//      else
//      {
//        gene = (GeneData)(gene_list->data) ;
//
//        gene->end = mspGetSEnd(msp) ;
//        gene->msp_end = msp ;
//      }
//
//      if (strand_genes->strand == '+')
//      strand_genes->forward_genes = gene_list ;
//      else
//      strand_genes->reverse_genes = gene_list ;
//    }
//
//  return ;
//}
//
//

/* A GCompareFunc() to compare genes for position.... */
//gint compareGenes(gconstpointer a, gconstpointer b)
//{
//  int result = 0 ;
//  GeneData gene_a = (GeneData)a, gene_b = (GeneData)b ;
//
//  if (gene_a->strand == '+' && gene_b->strand == '-')
//    result = -1 ;
//  else if (gene_a->strand == '-' && gene_b->strand == '+')
//    result = 1 ;
//  else
//    {
//      if (gene_a->start < gene_b->start)
//      result = -1 ;
//      else if (gene_a->start > gene_b->start)
//      result = 1 ;
//      else
//      result = 0 ;
//    }
//
//  return result ;
//}



//static void setYoffsets(GList *gene_list, float min_offset, float max_offset)
//{
//  GList *curr_ptr, *next_ptr ;
//  float curr_y = 0.0, bump_incr = 0.5 ;
//
//
//  /* Go through the gene list comparing, reordering and assigning y offsets to the genes
//   * so they can be drawn without overlapping. */
//  curr_ptr = gene_list ;
//  next_ptr = curr_ptr->next ;
//  curr_y = min_offset - bump_incr ;
//
//  /* Go through all genes. */
//  while (curr_ptr)
//    {
//      GList *list_ptr = g_list_first(gene_list) ;
//
//      /* For each gene look at all the preceding genes and to decide its y offset so it is
//       * bumped correctly. */
//      while (list_ptr)
//      {
//        GeneData list_gene = (GeneData)list_ptr->data ;
//        GeneData curr_gene = (GeneData)curr_ptr->data ;
//
//        if (list_ptr == curr_ptr)
//          {
//            /* This gene overlaps all previous ones and needs a new offset. */
//            curr_y += bump_incr ;
//            if (curr_y > max_offset)
//              curr_y = max_offset ;
//
//            curr_gene->y_pos = curr_y ;
//            break ;
//          }
//        else if (curr_gene->start > list_gene->end)
//          {
//            /* This gene coes not overlap the list gene so give is the same offset. */
//            curr_gene->y_pos = list_gene->y_pos ;
//
//            if (list_ptr->next != curr_ptr)
//              {
//                list_ptr = g_list_remove(list_ptr, curr_gene) ;
//                list_ptr = g_list_insert_before(gene_list, list_ptr->next, curr_gene) ;
//              }
//
//            break ;
//          }
//        else
//          {
//            /* This gene overlaps the list gene so move on to the next one. */
//            list_ptr = g_list_next(list_ptr) ;
//          }
//      }
//
//      /* update curr/next until we get to the end of the list... */
//      if ((curr_ptr = next_ptr))
//      next_ptr = curr_ptr->next ;
//    }
//
//  return ;
//}
//

///* A GFunc() to record start/end of genes. */
//static void drawGenesCB(gpointer data, gpointer user_data_unused)
//{
//  GeneData gene = (GeneData)data ;
//  MSP *msp ;
//
//  msp = gene->msp_start ;
//  do
//    {
//      drawMSPGene(msp, gene->y_pos) ;
//
//      msp = msp->next ;
//    } while (msp && msp != gene->msp_end) ;
//
//  return ;
//}
//
//
//static void drawMSPGene(MSP *msp, float y_offset)
//{
//  float height,               /* box height/width */
//    sx, ex, midx ;
//
//  height = fonth ;
//
//  sx = seq2graphX(mspGetQStart(msp));
//  ex = seq2graphX(mspGetQEnd(msp));
//
//  if (msp->score == -1.0) /* EXON */
//    {
//      graphRectangle(sx, y_offset, ex, y_offset + height);
//    }
//  else if (msp->score == -2.0) /* INTRON */
//    {
//
//      midx = 0.5 * (sx + ex) ;
//      graphLine (sx, y_offset + height/2, midx, y_offset) ;
//      graphLine (ex, y_offset + height/2, midx, y_offset) ;
//    }
//
//  return ;
//}
//

//static void printMSP(gpointer data, gpointer user_data)
//{
//  MSP *msp = (MSP *)data ;
//  
//  printf("%s:\t%d,%d\t->\t%d,%d\n",
//       msp->sname, msp->sstart, msp->send, msp->qstart, msp->qend) ;
//  
//
//  return ;
//}
//

//static void printGene(gpointer data, gpointer user_data)
//{
//  GeneData gene = (GeneData)data ;
//  
//  printf("%s: '%c' %d -> %d   is at position: %f\n",
//       gene->name, gene->strand, gene->start, gene->end, gene->y_pos) ;
//  
//
//  return ;
//}


//static void fsSelAll(void)
//{
//  int i;
//  graphActivate(fsGraph);
//  
//  for (i = 0; i < gArrayGetLen(fsArr); i++) 
//    {
//      FeatureSeries *fs = &g_array_index(fsArr, FeatureSeries, i);
//      fs->on = 1;
//      graphBoxDraw(fsBoxStart+i, WHITE, BLACK);
//    }
//}
//
//static void fsSelNone(void)
//{
//  int i;
//  graphActivate(fsGraph);
//  
//  for (i = 0; i < gArrayGetLen(fsArr); i++) 
//    {
//      FeatureSeries *fs = &g_array_index(fsArr, FeatureSeries, i);
//      fs->on = 0;
//      graphBoxDraw(fsBoxStart+i, BLACK, WHITE);
//    }
//}
//
//static void fsSelNoCurves(void)
//{
//  int i;
//  graphActivate(fsGraph);
//  
//  for (i = 0; i < gArrayGetLen(fsArr); i++) 
//    {
//      FeatureSeries *fs = &g_array_index(fsArr, FeatureSeries, i);
//      
//      if (fs->xy) 
//      {
//        fs->on = 0;
//        graphBoxDraw(fsBoxStart+i, BLACK, WHITE);
//      }
//    }
//}
//
//static void fsSelNoSegments(void)
//{
//  int i;
//  graphActivate(fsGraph);
//  
//  for (i = 0; i < gArrayGetLen(fsArr); i++) 
//    {
//      FeatureSeries *fs = &g_array_index(fsArr, FeatureSeries, i);
//      
//      if (!fs->xy) 
//      {
//        fs->on = 0;
//        graphBoxDraw(fsBoxStart+i, BLACK, WHITE);
//      }
//    }
//}
//
//static void fsToggleBottom(void)
//{
//    fsBottomOn = !fsBottomOn;
//    selectFeatures();
//}
//static void fsToggleRight(void)
//{
//    fsRightOn = !fsRightOn;
//    selectFeatures();
//}
//static void fsToggleAnnBottom(void)
//{
//    fsAnnBottomOn = !fsAnnBottomOn;
//    selectFeatures();
//}
//static void fsToggleAnnRight(void)
//{
//    fsAnnRightOn = !fsAnnRightOn;
//    selectFeatures();
//}
//static void fsToggleEndLines(void)
//{
//    fsEndLinesOn = !fsEndLinesOn;
//    selectFeatures();
//}
//static void fsSel(int box, double x_unused, double y_unused, int modifier_unused)
//{
//    if (box-fsBoxStart < 0 || box-fsBoxStart > gArrayGetLen(fsArr))
//      return;
//    
//    FeatureSeries *fs = &g_array_index(fsArr, FeatureSeries, box - fsBoxStart);
//    int *on = &fs->on;
//
//    graphActivate(fsGraph);
//
//
//    if (*on) {
//      *on = 0;
//      graphBoxDraw(box, BLACK, WHITE);
//    }
//    else {
//      *on = 1;
//      graphBoxDraw(box, WHITE, BLACK);
//    }
//
//}
//static void setfsPlotHeight(char *cp)
//{
//    fsPlotHeight = atof(cp);
//}
//    
//
//void selectFeatures(void)
//{
//  int i, box;
//  float y=1.0;
//
//  if (!graphActivate(fsGraph))
//    {
//      fsGraph = graphCreate (TEXT_SCROLL, "Feature Series Selection Tool", 0, 0, 0.4, 0.6);
//    }
//  graphPop();
//  graphRegister(PICK, fsSel);
//
//  if (1 /* dotterWindow */) {
//
//    box = graphButton("Show bottom series", fsToggleBottom, 1, y);
//    if (!fsBottomOn) graphBoxDraw(box, BLACK, WHITE);
//    else graphBoxDraw(box, WHITE, BLACK);
//    y += 1.5;
//
//    box = graphButton("Show right series", fsToggleRight, 1, y);
//    if (!fsRightOn) graphBoxDraw(box, BLACK, WHITE);
//    else graphBoxDraw(box, WHITE, BLACK);
//    y += 1.5;
//
//    box = graphButton("Show bottom annotations", fsToggleAnnBottom, 1, y);
//    if (!fsAnnBottomOn) graphBoxDraw(box, BLACK, WHITE);
//    else graphBoxDraw(box, WHITE, BLACK);
//    y += 1.5;
//
//    box = graphButton("Show right annotations", fsToggleAnnRight, 1, y);
//    if (!fsAnnRightOn) graphBoxDraw(box, BLACK, WHITE);
//    else graphBoxDraw(box, WHITE, BLACK);
//    y += 1.5;
//
//    box = graphButton("Draw lines at segment ends", fsToggleEndLines, 1, y);
//    if (!fsEndLinesOn) graphBoxDraw(box, BLACK, WHITE);
//    else graphBoxDraw(box, WHITE, BLACK);
//    y += 2;
//  }
//
//  sprintf(fsPlotHeighttx, "%.1f", fsPlotHeight);
//  graphText("Height of curves (XY series):", 1, y);
//  graphTextScrollEntry (fsPlotHeighttx, 6, 4, 31, y, setfsPlotHeight);
//  y += 2;
//
//  graphLinewidth(0.1);
//  graphLine(0, y, 2000, y);
//  y += 0.5;
//
//  graphText("Pick to select/unselect series", 1, y);
//  y += 1.5;
//  graphButton("All", fsSelAll, 1, y);
//  graphButton("No curves", fsSelNoCurves, 13, y);
//  graphButton("No segments", fsSelNoSegments, 24, y);
//  fsBoxStart = 1+graphButton("None", fsSelNone, 6, y);
//  y += 2;
//
//  graphTextBounds(50, gArrayGetLen(fsArr) * 1.5 + y + 5);
//
//  for (i = 0; i < gArrayGetLen(fsArr); i++)
//    {
//      float  margin = 0.1;
//      FeatureSeries *fs = &g_array_index(fsArr, FeatureSeries, i);
//
//      box = graphBoxStart();
//      graphText(fs->name, 1, y);      
//      graphRectangle(1 - margin, y - margin, 1 + margin + strlen(fs->name), y + 1 + margin);
//      graphBoxEnd();
//
//      if (!fs->on) 
//      {
//        graphBoxDraw(box, BLACK, WHITE);
//      }
//      else 
//      {
//        graphBoxDraw(box, WHITE, BLACK);
//      }
//      
//      y += 1.5;
//    }
//
//  graphRedraw();
//
//  return ;
//}
//
//
//float fsTotalHeight(MSP *msplist)
//{
//    int i;
//    float maxy = 0;
//      
//    if (!fsArr || !gArrayGetLen(fsArr))
//      {
//      return 0.0;
//      }
//
//    for (i = 0; i < gArrayGetLen(fsArr); i++) 
//      {
//      FeatureSeries *fs = &g_array_index(fsArr, FeatureSeries, i);
//      fs->y = fs->x = 0;
//      }
//      
//    for (msp = msplist; msp; msp = msp->next) 
//      {
//        if (mspShowFs(msp))
//        {
//          if (msp->type == BLXMSP_XY_PLOT) 
//            {
//              mspGetFsBottomEdge(msp, &maxy, fsPlotHeight+1);
//            }
//          else if (msp->type == BLXMSP_FS_SEG) 
//            {
//              mspGetFsBottomEdge(msp, &maxy, 1+1);
//            }
//        }
//      }
//    
//    return maxy + 2;
//}


/* Callbacks to be called when the dotter parameters have changed. */
static gboolean onZoomFactorChanged(GtkWidget *widget, const gint responseId, gpointer data)
{
  gboolean result = TRUE;
  
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  const char *text = gtk_entry_get_text(GTK_ENTRY(widget));
  gdouble newValue = g_strtod(text, NULL);
  
  if (newValue <= 0)
    {
      g_critical("Zoom factor must be greater than zero.\n");
      result = FALSE;
    }
  else if (newValue != properties->dotterWinCtx->zoomFactor)
    {
      properties->dotterWinCtx->zoomFactor = newValue;
      redrawAll(dotterWindow, NULL);
    }
  
  return result;
}

static gboolean onQStartChanged(GtkWidget *widget, const gint responseId, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  
  const char *text = gtk_entry_get_text(GTK_ENTRY(widget));
  int newValue = convertStringToInt(text);
  
  /* If display coords are negated, we must un-negate it before we use it */
  if (negateDisplayCoord(dwc->dotterCtx, TRUE))
    newValue *= -1;
  
  if (!valueWithinRange(newValue, &dwc->dotterCtx->refSeqFullRange))
    g_warning("Limiting reference sequence start to range %d -> %d.\n", dwc->dotterCtx->refSeqFullRange.min(), dwc->dotterCtx->refSeqFullRange.max());
  
  boundsLimitValue(&newValue, &dwc->dotterCtx->refSeqFullRange);
  
  gboolean changed = setStartCoord(dotterWindow, dwc, TRUE, newValue);
  
  /* If it's a self comparison, also update the vertical range. */
  if (dwc->selfComp)
    changed = setStartCoord(dotterWindow, dwc, FALSE, newValue) || changed;

  /* Check the crosshair is still in range and if not clip it */
  updateOnSelectedCoordsChanged(dotterWindow);

  if (changed)
    redrawAll(dotterWindow, NULL);
  
  return TRUE;
}

static gboolean onQEndChanged(GtkWidget *widget, const gint responseId, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  
  const char *text = gtk_entry_get_text(GTK_ENTRY(widget));
  int newValue = convertStringToInt(text);

  /* If display coords are negated, we must un-negate it before we use it */
  if (negateDisplayCoord(dwc->dotterCtx, TRUE))
    newValue *= -1;
  
  if (!valueWithinRange(newValue, &dwc->dotterCtx->refSeqFullRange))
    g_warning("Limiting reference sequence end to range %d -> %d.\n", dwc->dotterCtx->refSeqFullRange.min(), dwc->dotterCtx->refSeqFullRange.max());

  boundsLimitValue(&newValue, &dwc->dotterCtx->refSeqFullRange);

  gboolean changed = setEndCoord(dotterWindow, dwc, TRUE, newValue);
  
  /* If it's a self comparison, also update the vertical range. */
  if (dwc->selfComp)
    changed = setEndCoord(dotterWindow, dwc, FALSE, newValue) || changed;
  
  /* Check the crosshair is still in range and if not clip it */
  updateOnSelectedCoordsChanged(dotterWindow);

  if (changed)
    redrawAll(dotterWindow, NULL);

  return TRUE;
}

static gboolean onSStartChanged(GtkWidget *widget, const gint responseId, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  
  const char *text = gtk_entry_get_text(GTK_ENTRY(widget));
  int newValue = convertStringToInt(text);
  
  /* If display coords are negated, we must un-negate it before we use it */
  if (negateDisplayCoord(dwc->dotterCtx, FALSE))
    newValue *= -1;
  
  if (!valueWithinRange(newValue, &dwc->dotterCtx->matchSeqFullRange))
    g_warning("Limiting vertical sequence start to range %d -> %d.\n", dwc->dotterCtx->matchSeqFullRange.min(), dwc->dotterCtx->matchSeqFullRange.max());

  boundsLimitValue(&newValue, &dwc->dotterCtx->matchSeqFullRange);
  
  gboolean changed = setStartCoord(dotterWindow, dwc, FALSE, newValue);

  /* Check the crosshair is still in range and if not clip it */
  updateOnSelectedCoordsChanged(dotterWindow);

  if (changed)
    redrawAll(dotterWindow, NULL);

  return TRUE;
}

static gboolean onSEndChanged(GtkWidget *widget, const gint responseId, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  
  const char *text = gtk_entry_get_text(GTK_ENTRY(widget));
  int newValue = convertStringToInt(text);
  
  /* If display coords are negated, we must un-negate it before we use it */
  if (negateDisplayCoord(dwc->dotterCtx, FALSE))
    newValue *= -1;
  
  if (!valueWithinRange(newValue, &dwc->dotterCtx->matchSeqFullRange))
    g_warning("Limiting vertical sequence end to range %d -> %d.\n", dwc->dotterCtx->matchSeqFullRange.min(), dwc->dotterCtx->matchSeqFullRange.max());

  boundsLimitValue(&newValue, &dwc->dotterCtx->matchSeqFullRange);
  
  gboolean changed = setEndCoord(dotterWindow, dwc, FALSE, newValue);
  
  /* Check the crosshair is still in range and if not clip it */
  updateOnSelectedCoordsChanged(dotterWindow);

  if (changed)
    redrawAll(dotterWindow, NULL);
  
  return TRUE;
}

static gboolean onSlidingWinSizeChanged(GtkWidget *widget, const gint responseId, gpointer data)
{
  gboolean result = FALSE;
  
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  const char *text = gtk_entry_get_text(GTK_ENTRY(widget));
  int newValue = convertStringToInt(text);

  GError *error = NULL;
  gboolean changed = dotplotSetSlidingWinSize(properties->dotplot, newValue, &error);
  
  if (error)
    {
      reportAndClearIfError(&error, G_LOG_LEVEL_CRITICAL);
    }
  else
    {
      result = TRUE;
    }
  
  if (changed)
    redrawAll(dotterWindow, NULL);
  
  return result;
}


/* Callback called when the user has changed the 'splice sites on' option */
static gboolean onSetSpliceSitesOn(GtkWidget *button, const gint responseId, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  const gboolean spliceSitesOn = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button));
  alignmentToolSetSpliceSitesOn(properties->alignmentTool, spliceSitesOn);
  
  return TRUE;
}

/* Callback called when the user has changed the 'breaklines on' option */
static gboolean onSetBreaklinesOn(GtkWidget *button, const gint responseId, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  const gboolean breaklinesOn = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button));
  dotplotSetBreaklinesOn(properties->dotplot, breaklinesOn);
  
  return TRUE;
}

/* Callback called when the user has changed the 'horizontal labels on' option */
static gboolean onSetHozLabelsOn(GtkWidget *button, const gint responseId, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  const gboolean labelsOn = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button));
  dotplotSetHozLabelsOn(properties->dotplot, labelsOn);
  
  return TRUE;
}

/* Callback called when the user has changed the 'vertical labels on' option */
static gboolean onSetVertLabelsOn(GtkWidget *button, const gint responseId, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  const gboolean labelsOn = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button));
  dotplotSetVertLabelsOn(properties->dotplot, labelsOn);
  
  return TRUE;
}


/* Callback when we receive a response for the settings dialog */
static void onResponseSettingsDialog(GtkDialog *dialog, gint responseId, gpointer data)
{
  gboolean destroy = TRUE;
  
  switch (responseId)
  {
    case GTK_RESPONSE_ACCEPT:
      /* Destroy if successful */
      destroy = widgetCallAllCallbacks(GTK_WIDGET(dialog), GINT_TO_POINTER(responseId));
      break;
      
    case GTK_RESPONSE_APPLY:
      widgetCallAllCallbacks(GTK_WIDGET(dialog), GINT_TO_POINTER(responseId));
      destroy = FALSE;
      break;
      
    case GTK_RESPONSE_CANCEL:
    case GTK_RESPONSE_REJECT:
      destroy = TRUE;
      break;
      
    default:
      break;
  };
  
  if (destroy)
    {
      /* If it's a persistent dialog, just hide it, otherwise destroy it */
      const gboolean isPersistent = GPOINTER_TO_INT(data);
      
      if (isPersistent)
        {
          gtk_widget_hide_all(GTK_WIDGET(dialog));
        }
      else
        {
          gtk_widget_destroy(GTK_WIDGET(dialog));
        }
    }
}


/* Create the paraemter control widgets for the settings dialog */
static void settingsDialogParamControls(GtkWidget *dialog, GtkWidget *dotterWindow, const int border)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  DotterContext *dc = dwc->dotterCtx;
  
  /* Put everything in a frame */
  GtkWidget *frame = gtk_frame_new("Parameters");
  gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), frame);
  gtk_container_set_border_width(GTK_CONTAINER(frame), border); 
  
  /* Create a table to lay out the widgets */
  const int numRows = 4;
  const int numCols = 3;
  const int xpad = 2;
  const int ypad = 2;
  
  GtkTable *table = GTK_TABLE(gtk_table_new(numRows, numCols, FALSE));
  gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(table));
  
  /* Get the start and end values of each range, and negate them for display if necessary */
  const int qStart = getDisplayCoord(getStartCoord(dwc, TRUE), dc, TRUE);
  const int qEnd = getDisplayCoord(getEndCoord(dwc, TRUE), dc, TRUE);
  const int sStart = getDisplayCoord(getStartCoord(dwc, FALSE), dc, FALSE);
  const int sEnd = getDisplayCoord(getEndCoord(dwc, FALSE), dc, FALSE);
  
  GtkWidget *zoomEntry = createTextEntryFromDouble(dotterWindow, table, 1, 2, xpad, ypad, "_Zoom: ", dwc->zoomFactor, onZoomFactorChanged);
  gtk_widget_set_tooltip_text(zoomEntry, "Zoom out by this factor, e.g. a zoom factor of 3 will shrink the window to 1/3 of its full size");

  GtkWidget *windowEntry = NULL;
  
  /* Create the boxes for the sequence ranges. If it's a self comparison, we only really have one range. */
  if (dwc->selfComp)
    {
      createTextEntryFromInt(dotterWindow, table, 2, 2, xpad, ypad, "Range: ", qStart, onQStartChanged);
      createTextEntryFromInt(dotterWindow, table, 2, 3, xpad, ypad, NULL, qEnd, onQEndChanged);
      windowEntry = createTextEntryFromInt(dotterWindow, table, 3, 2, xpad, ypad, "Sliding _window size: ", dotplotGetSlidingWinSize(properties->dotplot), onSlidingWinSizeChanged);
    }
  else
    {
      createTextEntryFromInt(dotterWindow, table, 2, 2, xpad, ypad, "_Horizontal range: ", qStart, onQStartChanged);
      createTextEntryFromInt(dotterWindow, table, 2, 3, xpad, ypad, NULL, qEnd, onQEndChanged);
      createTextEntryFromInt(dotterWindow, table, 3, 2, xpad, ypad, "_Vertical range: ", sStart, onSStartChanged);
      createTextEntryFromInt(dotterWindow, table, 3, 3, xpad, ypad, NULL, sEnd, onSEndChanged);
      windowEntry = createTextEntryFromInt(dotterWindow, table, 4, 2, xpad, ypad, "Sliding _window size: ", dotplotGetSlidingWinSize(properties->dotplot), onSlidingWinSizeChanged);
    }

  if (windowEntry)
    gtk_widget_set_tooltip_text(windowEntry, "The size of the sliding window used to average pairwise scores. Note that this causes the matrix to be recalculated, which may time a long time for a large plot.");
}


/* Create the display control widgets for the settings dialog */
static void settingsDialogDisplayControls(GtkWidget *dialog, GtkWidget *dotterWindow, const int border)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotplotProperties *dotplotProperties = dotplotGetProperties(properties->dotplot);
  
  /* Put everything in a vbox inside a frame */
  GtkWidget *frame = gtk_frame_new("Display");
  gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), frame);
  gtk_container_set_border_width(GTK_CONTAINER(frame), border); 
  
  GtkWidget *vbox = gtk_vbox_new(FALSE, 0);
  gtk_container_add(GTK_CONTAINER(frame), vbox);

  /* Create a check box for toggling splice sites on and off */
  GtkWidget *splicesBtn = gtk_check_button_new_with_mnemonic("Highlight _splice sites");
  gtk_widget_set_tooltip_text(splicesBtn, "For known high-scoring pairs, highlight splice-sites in the alignment tool");
  gtk_container_add(GTK_CONTAINER(vbox), splicesBtn);
  gboolean spliceSitesOn = alignmentToolGetSpliceSitesOn(properties->alignmentTool);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(splicesBtn), spliceSitesOn);
  widgetSetCallbackData(splicesBtn, onSetSpliceSitesOn, dotterWindow);
  
  /* Create a check box for toggling breaklines on and off. If breaklines are
   * off at startup then it means that there are not multiple sequences, so
   * the option is not applicable. */
  static int disableBreaklines = -1; /* -1 for unset; 0 for false; 1 for true */

  if (disableBreaklines == -1)
    disableBreaklines = !dotplotProperties->breaklinesOn;
  
  GtkWidget *breaklinesBtn = gtk_check_button_new_with_mnemonic("Show _breaklines");
  gtk_container_add(GTK_CONTAINER(vbox), breaklinesBtn);
  gtk_widget_set_tooltip_text(breaklinesBtn, "Show breaklines between sequences when dottering multiple sequences that have been concatenated");
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(breaklinesBtn), dotplotProperties->breaklinesOn);
  
  if (disableBreaklines)
    gtk_widget_set_sensitive(breaklinesBtn, FALSE);
  
  widgetSetCallbackData(breaklinesBtn, onSetBreaklinesOn, dotterWindow);
  
  /* Add buttons to allow the user to turn off hoz/vert annotation labels */
  GtkWidget *hozBtn = gtk_check_button_new_with_mnemonic("Show _horizontal sequence labels");
  gtk_widget_set_tooltip_text(hozBtn, "Show labels for each breakline between multiple sequences on the horizontal axis");
  gtk_container_add(GTK_CONTAINER(vbox), hozBtn);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(hozBtn), dotplotProperties->hozLabelsOn);
  widgetSetCallbackData(hozBtn, onSetHozLabelsOn, dotterWindow);

  GtkWidget *vertBtn = gtk_check_button_new_with_mnemonic("Show _vertical sequence labels");
  gtk_widget_set_tooltip_text(vertBtn, "Show labels for each breakline between multiple sequences on the vertical axis");
  gtk_container_add(GTK_CONTAINER(vbox), vertBtn);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(vertBtn), dotplotProperties->vertLabelsOn);
  widgetSetCallbackData(vertBtn, onSetVertLabelsOn, dotterWindow);
  
}


/* Pop up a dialog to allow the user to set the dotter parameters */
static void showSettingsDialog(GtkWidget *dotterWindow)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;

  const DotterDialogId dialogId = DOTDIALOG_SETTINGS;
  GtkWidget *dialog = getPersistentDialog(dwc->dialogList, dialogId);
  
  if (!dialog)
    {
      /* Create the dialog */
      char *title = g_strdup_printf("%sSettings", dotterGetTitlePrefix(dwc->dotterCtx));

      dialog = gtk_dialog_new_with_buttons(title,
                                           GTK_WINDOW(dotterWindow), 
                                           GTK_DIALOG_DESTROY_WITH_PARENT,
                                           GTK_STOCK_OK,
                                           GTK_RESPONSE_ACCEPT,
                                           GTK_STOCK_CANCEL,
                                           GTK_RESPONSE_REJECT,
                                           NULL);

      g_free(title);
      
      /* These 2 calls are required to make the dialog persistent... */
      addPersistentDialog(dwc->dialogList, dialogId, dialog);
      g_signal_connect(dialog, "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), NULL);
      
      g_signal_connect(dialog, "response", G_CALLBACK(onResponseSettingsDialog), GINT_TO_POINTER(TRUE));
    }
  else
    {
      /* Clear contents and re-create */
      dialogClearContentArea(GTK_DIALOG(dialog));
    }

  /* Create the contents */
  const int border = 12; /* border around individual sections */
  settingsDialogParamControls(dialog, dotterWindow, border);
  settingsDialogDisplayControls(dialog, dotterWindow, border);

  gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT);
  gtk_widget_show_all(dialog);
  gtk_window_present(GTK_WINDOW(dialog));
  
  return;
}


/* Redraw the main dotter window, the alignment tool and the greyramp tool. Re-calculates borders etc. */
static void redrawAll(GtkWidget *dotterWindow, gpointer data)
{
  gtk_widget_queue_draw(dotterWindow);
  
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;

  /* Check the range values are the correct way round. */
  dwc->refSeqRange.sort();
  dwc->matchSeqRange.sort();
  
  if (properties)
    {
      gtk_widget_queue_draw(properties->greyrampTool);
      gtk_widget_queue_draw(properties->alignmentTool);
      recalcDotplot(properties->dotplot);
    }
}


/* Refresh the main dotter window, the alignment tool and the greyramp tool. Clears any cached
 * pixmaps but does not recalculate borders etc. */
static void refreshAll(GtkWidget *dotterWindow, gpointer data)
{
  callFuncOnAllChildWidgets(dotterWindow, (gpointer)widgetClearCachedDrawable);
  gtk_widget_queue_draw(dotterWindow);

  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  if (properties)
    {
      gtk_widget_queue_draw(properties->greyrampTool);
      callFuncOnAllChildWidgets(properties->alignmentTool, (gpointer)widgetClearCachedDrawable);
      callFuncOnAllChildWidgets(properties->dotplot, (gpointer)widgetClearCachedDrawable);
    }
}


static void readmtx(int MATRIX[24][24], char *mtxfile)
{
    FILE *fil;
    int row, col;
    char line[1025] = "#", *p;
    
    char *mtxfileText = g_strdup_printf("%s/%s", getenv("BLASTMAT"), mtxfile);
  
    if (!(fil = fopen(mtxfile, "r")) &&
        !(fil = fopen(mtxfileText, "r")))
      {
        char *msg = g_strdup_printf("Failed to open score matrix file %s - not found in ./ or $BLASTMAT/.\n", mtxfile);
        g_error(msg, mtxfile);
        g_free(msg);
      }
  
    g_free(mtxfileText);
    mtxfileText = NULL;
    
    /* Ignore header ... */
    while (!feof(fil) && *line == '#')
      {
        fgets(line, 1024, fil);
      }

    /* Read in the pairwise scores */
    for (row = 0; row < 24; row++)
    {
        if (!(fgets(line, 1024, fil)))
            g_error("Wrong number of rows in matrix file: %d (should be 24).\n", row);

        p = strtok(line, " \t\n");
        for (col = 0; col < 24; col++) 
        {
            while (*p == '*' || isalpha((int) *p))
                p = strtok(NULL, " \t\n");
          
            if (!p) 
              g_error("Error on row %d in matrix file.\n", row);

            MATRIX[row][col] = atoi(p);

            p = strtok(NULL, " \t\n");
        }
    }

    g_message("I read your score matrix %s.\n", mtxfile);
    fclose(fil);
}

static void mtxcpy(int dest[24][24], int src[24][24])
{
    int i, j;

    for (i = 0 ; i < 24 ; i++)
        for (j = 0 ; j < 24 ; j++)
            dest[i][j] = src[i][j];
}


static void DNAmatrix(int mtx[24][24])
{
    int i, j;

    for (i = 0 ; i < 6 ; i++)
        for (j = 0 ; j < 6 ; j++) {
            if ( i < 4 && j < 4) 
                mtx[i][j] = (i == j ? 5 : -4);
            else 
                mtx[i][j] = -4;
        }
}


/* Utility to get the length of the given GArray. Returns 0 if array is null. */
//static int gArrayGetLen(GArray *array)
//{
//  return (array ? array->len : 0);
//}


/***********************************************************
 *               Show/hide parts of the view               *
 ***********************************************************/

/* Show/hide the greyramp tool, bringing it to the front */
static void showHideGreyrampTool(GtkWidget *dotterWindow, const gboolean show)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  if (properties && properties->greyrampWindow && GTK_IS_WIDGET(properties->greyrampWindow))
    {
      /* Get the parent widget for the greyramp too. This is the container if docked or the
       * window otherwise */
      GtkWidget *parent = properties->windowsDocked ? properties->greyrampContainer : properties->greyrampWindow;

      if (parent && show)
        {
          /* Show it, and bring it to the front if it's a toplevel window */
          gtk_widget_show_all(parent);
      
          if (GTK_IS_WINDOW(parent))
            gtk_window_present(GTK_WINDOW(parent));

          /* Hide the minimised version */
          gtk_widget_hide(properties->greyrampToolMinimised);
        }
      else if (parent)
        {
          /* Hide it, and show the minimised version instead */
          gtk_widget_hide(parent);
          gtk_widget_show_all(properties->greyrampToolMinimised);
        }
    }
}

/* Show/hide the alignment tool, bringing it to the front */
static void showHideAlignmentTool(GtkWidget *dotterWindow, const gboolean show)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  if (properties && properties->alignmentWindow && GTK_IS_WIDGET(properties->alignmentWindow))
    {
      /* Get the parent widget for the alignment too. This is the container if docked or the
       * window otherwise */
      GtkWidget *parent = properties->windowsDocked ? properties->alignmentContainer : properties->alignmentWindow;

      if (parent && show)
        {
          /* Show it, and bring it to the front if it's a toplevel window */
          gtk_widget_show_all(parent);
      
          if (GTK_IS_WINDOW(parent))
            gtk_window_present(GTK_WINDOW(parent));
        }
      else if (parent)
        {
          /* Hide it */
          gtk_widget_hide(parent);
        }

    }
}

/* Bring the main dotter window to the front */
static void showDotterWindow(GtkWidget *dotterWindow)
{
  gtk_window_present(GTK_WINDOW(dotterWindow));
}


/* Move the given widget from source to dest */
static void reparentWidget(GtkWidget *widget, GtkContainer *source, GtkContainer *dest, const gboolean show)
{
  g_return_if_fail(widget && source && dest);

  /* If the container ref to the widget is removed it might be destroyed, so make sure there is a
   * ref to it. */
  g_object_ref(widget);
  gtk_container_remove(source, widget);
  gtk_container_add(dest, widget);
  g_object_unref(widget);

  /* Hide the old widget */
  gtk_widget_hide(GTK_WIDGET(source));

  /* Show the new widget (only if it's toggled on) */
  if (show)
    gtk_widget_show_all(GTK_WIDGET(dest));
}


static void dotterToggleDockWindows(GtkWidget *dotterWindow)
{
  g_return_if_fail(dotterWindow);

  DotterProperties *properties = dotterGetProperties(dotterWindow);
  gboolean greyrampVisible = getToggleMenuStatus(properties->dotterWinCtx->actionGroup, "ToggleGreyramp");
  gboolean alignmentVisible = getToggleMenuStatus(properties->dotterWinCtx->actionGroup, "ToggleAlignment");

  if (properties->windowsDocked)
    {
      reparentWidget(properties->alignmentTool, GTK_CONTAINER(properties->alignmentContainer), GTK_CONTAINER(properties->alignmentWindow), alignmentVisible);
      reparentWidget(properties->greyrampTool, GTK_CONTAINER(properties->greyrampContainer), GTK_CONTAINER(properties->greyrampWindow), greyrampVisible);
    }
  else
    {
      reparentWidget(properties->alignmentTool, GTK_CONTAINER(properties->alignmentWindow), GTK_CONTAINER(properties->alignmentContainer), alignmentVisible);
      reparentWidget(properties->greyrampTool, GTK_CONTAINER(properties->greyrampWindow), GTK_CONTAINER(properties->greyrampContainer), greyrampVisible);
    }

  properties->windowsDocked = !properties->windowsDocked;
}

/* Enable/disable menu options that use the selection in the alignment tool. This is a callback
 * called from the alignment tool following a selection/deselection. */
void dotterEnableSelectionMenus(DotterWindowContext *dwc, const gboolean enable)
{
  enableMenuAction(dwc->actionGroup, "CopySelnCoords", enable);
  enableMenuAction(dwc->actionGroup, "CopySeln", enable);
  enableMenuAction(dwc->actionGroup, "ClearSeln", enable);
}

/* Toggle the given menu item on or off */
void dotterSetToggleMenuStatus(DotterWindowContext *dwc, 
                               const char *menuItem,
                               const gboolean enable)
{
  setToggleMenuStatus(dwc->actionGroup, menuItem, enable);
}

/***********************************************************
 *                       Help Dialog                       *
 ***********************************************************/

/* A GtkAboutDialogActivateLinkFunc() called when user clicks on website link in "About" window. */
static void aboutDialogOpenLinkCB(GtkAboutDialog *about, const gchar *link, gpointer data)
{
  GError *error = NULL ;
    
  if (!seqtoolsLaunchWebBrowser(link, &error))
    g_critical("Cannot show link in web browser: \"%s\"", link) ;    
}


/* Shows the 'About' dialog */
static void showAboutDialog(GtkWidget *parent)
{
#if CHECK_GTK_VERSION(2, 6)
  const gchar *authors[] = {AUTHOR_LIST, NULL} ;

  gtk_about_dialog_set_url_hook(aboutDialogOpenLinkCB, NULL, NULL) ;

  gtk_show_about_dialog(GTK_WINDOW(parent),
                        "authors", authors,
                        "comments", dotterGetCommentsString(), 
                        "copyright", dotterGetCopyrightString(),
                        "license", dotterGetLicenseString(),
                        "name", dotterGetAppName(),
                        "version", dotterGetVersionString(),
                        "website", dotterGetWebSiteString(),
                        NULL) ;
#endif
  
  return ;
}


static void showHelpDialog(GtkWidget *dotterWindow)
{
  GError *error = NULL;
  
  /* The docs should live in /share/doc/seqtools/, in the same parent
   * directory that our executable's 'bin' directory is in. Open the 'quick
   * start' page. */
  char rel_path[100] = "../share/doc/seqtools/dotter_quick_start.html";
  
  /* Find the executable's path */
  char *exe = g_find_program_in_path(g_get_prgname());
  gboolean ok = (exe != NULL);
  
  if (ok)
    {
      /* Get the executable's directory */
      char *dir = g_path_get_dirname(exe);
      
      ok = dir != NULL;
      
      if (ok)
        {
          /* Get the path to the html page */
          char *path = g_strdup_printf("%s/%s", dir, rel_path);
          
          ok = path != NULL;
          
          if (ok)
            {
              g_message("Opening help page '%s'\n", path);
              seqtoolsLaunchWebBrowser(path, &error);
              g_free(path);
            }
          
          g_free(dir);
        }

      g_free(exe);
    }
  
  if (!ok)
    {
      if (error)
        reportAndClearIfError(&error, G_LOG_LEVEL_CRITICAL);
      else
        g_critical("Could not find help documentation: %s\n", rel_path);
    }
}


/***********************************************************
 *                          Events                         *
 ***********************************************************/

static void onQuitMenu(GtkAction *action, gpointer data)
{
  /* Close all associated windows */
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterContext *dc = dotterGetContext(dotterWindow);
  dotterContextCloseAllWindows(dc);
}

static void onCloseMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  closeWindow(dotterWindow);
}

static void onSavePlotMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  GError *error = NULL;
  savePlot(properties->dotplot, NULL, NULL, &error);
  
  prefixError(error, "Error saving plot. ");
  reportAndClearIfError(&error, G_LOG_LEVEL_CRITICAL);
}

static void onExportPlotMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  /* Set the background colour to something sensible for printing */
  GdkColor *defaultBgColor = getGdkColor(DOTCOLOR_BACKGROUND, properties->dotterWinCtx->dotterCtx->defaultColors, FALSE, TRUE);
  setWidgetBackgroundColor(dotterWindow, defaultBgColor);
  redrawAll(dotterWindow, NULL);
  
  GError *error = NULL;
  exportPlot(properties->dotplot, GTK_WINDOW(dotterWindow), NULL, &error);
  
  prefixError(error, "Error exporting plot. ");
  reportAndClearIfError(&error, G_LOG_LEVEL_CRITICAL);

  /* Revert the background colour */
  onPrintColorsChanged(dotterWindow);

  redrawAll(dotterWindow, NULL);
}

static void onPrintMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  printDotterWindow(dotterWindow);
}

static void onSettingsMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  showSettingsDialog(dotterWindow);
}

static void onHelpMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  showHelpDialog(dotterWindow);
}

static void onAboutMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  showAboutDialog(dotterWindow);
}

static void onCloseAlignmentMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  if (properties && properties->dotterWinCtx)
    setToggleMenuStatus(properties->dotterWinCtx->actionGroup, "ToggleAlignment", FALSE);
}


/* Called when the user selects the print menu option for the alignment tool */
static void onPrintAlignmentMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  GtkWidget *alignmentTool = properties->alignmentTool;

  /* Set the background colour to something sensible for printing */
  GdkColor *defaultBgColor = getGdkColor(DOTCOLOR_BACKGROUND, dwc->dotterCtx->defaultColors, FALSE, TRUE);
  setWidgetBackgroundColor(alignmentTool, defaultBgColor);
  alignmentToolRedrawAll(alignmentTool);

  /* Make sure cached drawables are re-drawn before we print them. */
  gdk_window_process_all_updates();
  
  GtkWidget *window = gtk_widget_get_toplevel(alignmentTool);
  blxPrintWidget(alignmentTool, NULL, GTK_WINDOW(window), &dwc->printSettings, &dwc->pageSetup, NULL, TRUE, PRINT_FIT_BOTH);

  /* Revert the background colour */
  defaultBgColor = getGdkColor(DOTCOLOR_BACKGROUND, dwc->dotterCtx->defaultColors, FALSE, dwc->usePrintColors);
  setWidgetBackgroundColor(alignmentTool, defaultBgColor);
  alignmentToolRedrawAll(alignmentTool);
}


/* Utility to copy an integer value as a string to the primary clipboard */
static void copyIntToPrimaryClipboard(const int val)
{
  char *displayText = convertIntToString(val);
  setPrimaryClipboardText(displayText);
  g_free(displayText); 
}

/* Callback called when the user selects the 'copy horizontal coord' menu option */
static void onCopyHCoordMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  copyIntToDefaultClipboard(properties->dotterWinCtx->refCoord);
  copyIntToPrimaryClipboard(properties->dotterWinCtx->refCoord);
}

/* Callback called when the user selects the 'copy vertical coord' menu option */
static void onCopyVCoordMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  copyIntToDefaultClipboard(properties->dotterWinCtx->matchCoord);
  copyIntToPrimaryClipboard(properties->dotterWinCtx->matchCoord);
}

/* Callback called when the user selects the 'copy selection' menu option */
static void onCopySelnMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  alignmentToolCopySeln(properties->alignmentTool);
}

/* Callback called when the user selects the 'copy selection coords' menu option */
static void onCopySelnCoordsMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  alignmentToolCopySelnCoords(properties->alignmentTool);
}

/* Callback called when the user selects the 'clear selection' menu option */
static void onClearSelnMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  alignmentToolClearSequenceSelection(properties->alignmentTool);
}


/* Callback called when the user selects the 'maximise greyramp' menu option */
static void onMaximiseGreyrampMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);

  showHideGreyrampTool(dotterWindow, TRUE);
}

/* Callback called when the user selects the 'minimise greyramp' menu option */
static void onMinimiseGreyrampMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);

  showHideGreyrampTool(dotterWindow, FALSE);
}

static void onShowHideGreyrampMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);

  gboolean show = gtk_toggle_action_get_active(GTK_TOGGLE_ACTION(action));

  showHideGreyrampTool(dotterWindow, show);
}

static void onShowHideAlignmentMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);

  gboolean show = gtk_toggle_action_get_active(GTK_TOGGLE_ACTION(action));

  showHideAlignmentTool(dotterWindow, show);
}

static void onToggleCrosshairMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  toggleCrosshairOn(properties->dotplot);
}

static void onToggleCoordsMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  toggleCrosshairCoordsOn(properties->dotplot);
}

static void onToggleFullscreenMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  toggleCrosshairFullscreen(properties->dotplot);
}

static void onTogglePixelmapMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  dotplotTogglePixelmap(properties->dotplot);
}

static void onToggleGridMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  dotplotToggleGrid(properties->dotplot);
}

static void onToggleHspMode(GtkRadioAction *action, GtkRadioAction *current, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  
  const DotterHspMode hspMode = (const DotterHspMode)gtk_radio_action_get_current_value(current);
  setHspMode(properties->dotplot, hspMode);
}

static void onPrintColorsChanged(GtkWidget *dotterWindow)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;

  /* Refresh the background colors for both the main window and the alignment tool */
  GdkColor *defaultBgColor = getGdkColor(DOTCOLOR_BACKGROUND, dwc->dotterCtx->defaultColors, FALSE, dwc->usePrintColors);
  
  setWidgetBackgroundColor(dotterWindow, defaultBgColor);
  setWidgetBackgroundColor(properties->alignmentTool, defaultBgColor);
  
  /* Redraw everything */
  refreshAll(dotterWindow, NULL);
}

static void onToggleUsePrintColorsMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  
  /* Toggle the flag*/
  dwc->usePrintColors = !dwc->usePrintColors;
  onPrintColorsChanged(dotterWindow);
}

static void onToggleBumpExonsMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  dotplotToggleBumpExons(properties->dotplot);
}

static void onToggleDockWindowsMenu(GtkAction *action, gpointer data)
{
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  dotterToggleDockWindows(dotterWindow);
}


/* Mouse button handler */
static gboolean onButtonPressDotter(GtkWidget *window, GdkEventButton *event, gpointer data)
{
  gboolean handled = FALSE;
  
  if (event->type == GDK_BUTTON_PRESS && event->button == 3) /* right click */
    {
      GtkMenu *contextMenu = GTK_MENU(data);
      gtk_menu_popup (contextMenu, NULL, NULL, NULL, NULL, event->button, event->time);
    }
  else if (event->type == GDK_BUTTON_PRESS && event->button == 1) /* left click */
    {
      /* If the dot-plot was clicked the selected coords will have changed. Perform required updates. */
      updateOnSelectedCoordsChanged(window);
      handled = TRUE;
    }
  
  return handled;
}

/* Mouse button handler for the alignment/greyramp tools */
static gboolean onButtonPressTool(GtkWidget *greyrampTool, GdkEventButton *event, gpointer data)
{
  gboolean handled = FALSE;
  
  if (event->type == GDK_BUTTON_PRESS && event->button == 3) /* right click */
    {
      GtkMenu *contextMenu = GTK_MENU(data);
      gtk_menu_popup (contextMenu, NULL, NULL, NULL, NULL, event->button, event->time);
      handled = TRUE;
    }
  
  return handled;
}


/* Mouse move handler */
static gboolean onMouseMoveDotter(GtkWidget *window, GdkEventMotion *event, gpointer data)
{
  gboolean handled = FALSE;
  
  if (event->state & GDK_BUTTON1_MASK)  /* left-drag */
    {
      /* If the dot-plot was clicked the selected coords will have changed. Perform required updates. */
      updateOnSelectedCoordsChanged(window);
      handled = TRUE;
    }

  return handled;
}


/* Get the factor to convert between nucleotide and display (e.g. peptide) coords, or 1 if no
 * conversion is necessary */
int getResFactor(DotterContext *dc, const gboolean horizontal)
{
  return horizontal && dc->blastMode == BLXMODE_BLASTX ? dc->numFrames : 1;
}


/* Returns true if display coordinates should be shown negated for the given scale. */
static gboolean negateDisplayCoord(DotterContext *dc, const gboolean horizontal)
{
  gboolean result = FALSE;
  
  if (dc->negateCoords)
    {
    if (horizontal)
      result = dc->hozScaleRev;
    else 
      result = dc->vertScaleRev;
    }
  
  return result;
}


/* Convert the given coord to a display coord (just negates it for the display if necessary) */
int getDisplayCoord(const int coordIn, DotterContext *dc, const gboolean horizontal)
{
  int result = coordIn;
  
  if (negateDisplayCoord(dc, horizontal))
    result *= -1;
  
  return result;
}


/* Get the currently-selected (i.e. crosshair) coord for the horizontal or 
 * vertical sequence, as indicated by the bool */
int getSelectedCoord(DotterWindowContext *dwc, const gboolean horizontal)
{
  return (horizontal ? dwc->refCoord : dwc->matchCoord);
}


/* Get the start coord of the display range for the given sequence */
int getStartCoord(DotterWindowContext *dwc, const gboolean horizontal)
{
  int result = UNSET_INT;
  
  if (horizontal)
    result = dwc->dotterCtx->hozScaleRev ? dwc->refSeqRange.max() : dwc->refSeqRange.min();
  else
    result = dwc->dotterCtx->vertScaleRev ? dwc->matchSeqRange.max() : dwc->matchSeqRange.min();
  
  return result;
}

/* Get the end coord of the display range for the given sequence */
int getEndCoord(DotterWindowContext *dwc, const gboolean horizontal)
{
  int result = UNSET_INT;
  
  if (horizontal)
    result = dwc->dotterCtx->hozScaleRev ? dwc->refSeqRange.min() : dwc->refSeqRange.max();
  else
    result = dwc->dotterCtx->vertScaleRev ? dwc->matchSeqRange.min() : dwc->matchSeqRange.max();
  
  return result;
}



/* Set the start coord of the display range for the given sequence */
static gboolean setStartCoord(GtkWidget *dotterWindow, DotterWindowContext *dwc, const gboolean horizontal, const int newValue)
{
  gboolean changed = FALSE; 
  
  if (horizontal)
    {
      if (dwc->dotterCtx->hozScaleRev)
        changed = dwc->refSeqRange.setMax(newValue);
      else
        changed = dwc->refSeqRange.setMin(newValue);
    }
  else
    {
      if (dwc->dotterCtx->vertScaleRev)
        changed = dwc->matchSeqRange.setMax(newValue);
      else
        changed = dwc->matchSeqRange.setMin(newValue);
    }
  
  return changed;
}

/* Set the end coord of the display range for the given sequence */
static gboolean setEndCoord(GtkWidget *dotterWindow, DotterWindowContext *dwc, const gboolean horizontal, const int newValue)
{
  gboolean changed = FALSE;
  
  if (horizontal)
    {
      if (dwc->dotterCtx->hozScaleRev)
        changed = dwc->refSeqRange.setMin(newValue);
      else
        changed = dwc->refSeqRange.setMax(newValue);
    }
  else
    {
      if (dwc->dotterCtx->vertScaleRev)
        changed = dwc->matchSeqRange.setMin(newValue);
      else
        changed = dwc->matchSeqRange.setMax(newValue);
    }
  
  return changed;
}

/* Move the given sequence coord by the given number of coords (which can be negative to move 
 * in the decreasing direction. 'horizontal' indicates whether it's the horizontal or vertical
 * sequence that we're modifying and 'reverse' indicates whether that sequence's scale is shown reversed. */
static void incrementCoord(GtkWidget *dotterWindow, 
                           DotterContext *dc,
                           int *coord, 
                           const gboolean reverse, 
                           const gboolean horizontal, 
                           const gboolean convertCoords,
                           const int numCoords)
{
  const int incValue = convertCoords ? numCoords * getResFactor(dc, horizontal) : numCoords;

  if (reverse)
    {
      *coord -= incValue;
    }
  else
    {
      *coord += incValue;
    }
  
  updateOnSelectedCoordsChanged(dotterWindow);
}


/* Handle Q key press (Ctrl-Q => close all windows) */
static gboolean onKeyPressQ(GtkWidget *dotterWindow, const gboolean ctrlModifier)
{
  if (ctrlModifier)
    dotterContextCloseAllWindows(dotterGetContext(dotterWindow));
  
  return ctrlModifier;
}

/* Handle W key press (Ctrl-W => close window) */
static gboolean onKeyPressW(GtkWidget *widget, const gboolean ctrlModifier)
{
  gboolean handled = FALSE;

  if (ctrlModifier)
    {
      handled = closeWindow(widget);
    }
  
  return handled;
}

/* Handle H key press (Ctrl-H => show help dialog) */
static gboolean onKeyPressH(GtkWidget *dotterWindow, const gboolean ctrlModifier)
{
  if (ctrlModifier)
    showHelpDialog(dotterWindow);
  
  return ctrlModifier;
}


/* Handle S key press (Ctrl-S => show settings dialog) */
static gboolean onKeyPressS(GtkWidget *dotterWindow, const gboolean ctrlModifier)
{
  if (ctrlModifier)
    showSettingsDialog(dotterWindow);
    
  return ctrlModifier;
}

/* Handle G key press (Ctrl-G => show/hide greyramp tool) */
static gboolean onKeyPressG(GtkWidget *dotterWindow, const gboolean ctrlModifier)
{
  if (ctrlModifier)
    {
      DotterProperties *properties = dotterGetProperties(dotterWindow);
      gboolean active = getToggleMenuStatus(properties->dotterWinCtx->actionGroup, "ToggleGreyramp");

      /* Toggle the visiblity */
      setToggleMenuStatus(properties->dotterWinCtx->actionGroup, "ToggleGreyramp", !active);
    }
  
  return ctrlModifier;
}

/* Handle A key press (Ctrl-A => show/hide alignment tool) */
static gboolean onKeyPressA(GtkWidget *dotterWindow, const gboolean ctrlModifier)
{
  if (ctrlModifier)
    {
      DotterProperties *properties = dotterGetProperties(dotterWindow);
      gboolean active = getToggleMenuStatus(properties->dotterWinCtx->actionGroup, "ToggleAlignment");

      /* Toggle the visiblity */
      setToggleMenuStatus(properties->dotterWinCtx->actionGroup, "ToggleAlignment", !active);
    }
  
  return ctrlModifier;
}

/* Handle C key press (Ctrl-C => copy selection; Shift-Ctrl-C => copy selection coords) */
static gboolean onKeyPressC(GtkWidget *dotterWindow, 
                            const gboolean ctrlModifier,
                            const gboolean shiftModifier)
{
  if (ctrlModifier)
    {
      DotterProperties *properties = dotterGetProperties(dotterWindow);

      if (shiftModifier)
        alignmentToolCopySelnCoords(properties->alignmentTool);
      else
        alignmentToolCopySeln(properties->alignmentTool);
    }

  return ctrlModifier;
}

/* Handle D key press (Ctrl-D => show dotplot) */
static gboolean onKeyPressD(GtkWidget *dotterWindow, const gboolean ctrlModifier)
{
  if (ctrlModifier)
    showDotterWindow(dotterWindow);
  
  return ctrlModifier;
}

/* Handle K key press (Ctrl-K => dock/undock windows) */
static gboolean onKeyPressK(GtkWidget *dotterWindow, const gboolean ctrlModifier)
{
  if (ctrlModifier)
    {
      DotterProperties *properties = dotterGetProperties(dotterWindow);
      setToggleMenuStatus(properties->dotterWinCtx->actionGroup, "DockWindows", !properties->windowsDocked);
    }
  
  return ctrlModifier;
}

/* Handle up/down key presses */
static gboolean onKeyPressUpDown(GtkWidget *dotterWindow, const gboolean isUp, const gboolean modifier)
{
  /* Increment/decrement the vertical (i.e. match) sequence coord */
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;
  
  const int numCoords = isUp ? -1 : 1;
  
  incrementCoord(dotterWindow, dwc->dotterCtx, &dwc->matchCoord, dwc->dotterCtx->vertScaleRev, FALSE, !modifier, numCoords);  
  return TRUE;
}

/* Handle left/right key presses */
static gboolean onKeyPressLeftRight(GtkWidget *dotterWindow, const gboolean isLeft, const gboolean modifier)
{
  /* Increment/decrement the horizontal (i.e. reference) sequence coord */
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;

  const int numCoords = isLeft ? -1 : 1;
  
  incrementCoord(dotterWindow, dwc->dotterCtx, &dwc->refCoord, dwc->dotterCtx->hozScaleRev, TRUE, !modifier, numCoords);
  return TRUE;
}

/* Handle comma/period key presses */
static gboolean onKeyPressCommaPeriod(GtkWidget *dotterWindow, const gboolean isComma, const gboolean modifier)
{
  /* Increment/decrement both sequence coords */
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;

  incrementCoord(dotterWindow, dwc->dotterCtx, &dwc->refCoord, dwc->dotterCtx->hozScaleRev, TRUE, !modifier, isComma ? -1 : 1);
  incrementCoord(dotterWindow, dwc->dotterCtx, &dwc->matchCoord, dwc->dotterCtx->vertScaleRev, FALSE, !modifier, isComma ? -1 : 1);
  return TRUE;
}

/* Handle left/right square bracket presses */
static gboolean onKeyPressLeftRightBracket(GtkWidget *dotterWindow, const gboolean isLeft, const gboolean modifier)
{
  /* Increment the horizontal and decrement the vertical, or vice versa */
  DotterProperties *properties = dotterGetProperties(dotterWindow);
  DotterWindowContext *dwc = properties->dotterWinCtx;

  incrementCoord(dotterWindow, dwc->dotterCtx, &dwc->refCoord, dwc->dotterCtx->hozScaleRev, TRUE, !modifier, isLeft ? -1 : 1);
  incrementCoord(dotterWindow, dwc->dotterCtx, &dwc->matchCoord, dwc->dotterCtx->vertScaleRev, FALSE, !modifier, isLeft ? 1 : -1);
  return TRUE;

}

/* Handle Esc key press (clear selection) */
static gboolean onKeyPressEsc(GtkWidget *dotterWindow)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  alignmentToolClearSequenceSelection(properties->alignmentTool);

  return TRUE;
}


/* Key presses applicable to all windows */
gboolean onKeyPressDotter(GtkWidget *widget, GdkEventKey *event, gpointer data)
{
  gboolean handled = FALSE;
  
  GtkWidget *dotterWindow = GTK_WIDGET(data);
  
  const gboolean ctrlModifier = (event->state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK;  
  const gboolean shiftModifier = (event->state & GDK_SHIFT_MASK) == GDK_SHIFT_MASK;  
  
  switch (event->keyval)
    {
      case GDK_A:   /* fall through */
      case GDK_a:   handled = onKeyPressA(dotterWindow, ctrlModifier);              break;

      case GDK_C:   /* fall through */
      case GDK_c:   handled = onKeyPressC(dotterWindow, ctrlModifier, shiftModifier); break;

      case GDK_D:   /* fall through */
      case GDK_d:   handled = onKeyPressD(dotterWindow, ctrlModifier);              break;

      case GDK_G:   /* fall through */
      case GDK_g:   handled = onKeyPressG(dotterWindow, ctrlModifier);              break;
        
      case GDK_H:   /* fall through */
      case GDK_h:   handled = onKeyPressH(dotterWindow, ctrlModifier);              break;

      case GDK_K:   /* fall through */
      case GDK_k:   handled = onKeyPressK(dotterWindow, ctrlModifier);              break;

      case GDK_Q:   /* fall through */
      case GDK_q:   handled = onKeyPressQ(dotterWindow, ctrlModifier);              break;

      case GDK_S:   /* fall through */
      case GDK_s:   handled = onKeyPressS(dotterWindow, ctrlModifier);              break;

      case GDK_W:   /* fall through */
      case GDK_w:   handled = onKeyPressW(widget, ctrlModifier);                    break;

      case GDK_Escape:        handled = onKeyPressEsc(dotterWindow);

      case GDK_Up:            handled = onKeyPressUpDown(dotterWindow, TRUE, shiftModifier);        break;
      case GDK_Down:          handled = onKeyPressUpDown(dotterWindow, FALSE, shiftModifier);       break;
            
      case GDK_Left:          handled = onKeyPressLeftRight(dotterWindow, TRUE, shiftModifier);     break;
      case GDK_Right:         handled = onKeyPressLeftRight(dotterWindow, FALSE, shiftModifier);    break;
            
      case GDK_comma:         handled = onKeyPressCommaPeriod(dotterWindow, TRUE, shiftModifier);   break;
      case GDK_less:          handled = onKeyPressCommaPeriod(dotterWindow, TRUE, shiftModifier);   break;
      case GDK_period:        handled = onKeyPressCommaPeriod(dotterWindow, FALSE, shiftModifier);  break;
      case GDK_greater:       handled = onKeyPressCommaPeriod(dotterWindow, FALSE, shiftModifier);  break;
        
      case GDK_bracketleft:   handled = onKeyPressLeftRightBracket(dotterWindow, TRUE, shiftModifier);        break;
      case GDK_braceleft:     handled = onKeyPressLeftRightBracket(dotterWindow, TRUE, shiftModifier);        break;
      case GDK_bracketright:  handled = onKeyPressLeftRightBracket(dotterWindow, FALSE, shiftModifier);       break;
      case GDK_braceright:    handled = onKeyPressLeftRightBracket(dotterWindow, FALSE, shiftModifier);       break;
        
      default: break;
    }
  
  return handled;
}


/***********************************************************
 *                      Initialisation                     *
 ***********************************************************/

/* This creates BlxColumnInfo entries for each "column" of data (a misnomer in dotter
 * because we don't currently display this data in columns! The format comes from blixem which does
 * display the data in columns, and we use the same parser, and the same data structures, for dotter). */
GList* dotterCreateColumns()
{
  GList *columnList = NULL;
  
  /* Create the columns' data structs. The columns appear in the order
   * that they are added here. */
  blxColumnCreate(BLXCOL_SEQNAME, FALSE, "Name", G_TYPE_STRING, NULL, 0, TRUE, TRUE, FALSE, FALSE, FALSE, "Name", NULL, NULL, &columnList);

  return columnList;
}


/* Create the UI manager for the menus */
static GtkUIManager* createUiManager(GtkWidget *window, const DotterHspMode hspMode, GtkActionGroup **actionGroup_out)
{
  GtkActionGroup *action_group = gtk_action_group_new ("MenuActions");

  gtk_action_group_add_actions(action_group, menuEntries, G_N_ELEMENTS (menuEntries), window);
  gtk_action_group_add_toggle_actions(action_group, toggleMenuEntries, G_N_ELEMENTS (toggleMenuEntries), window);
  gtk_action_group_add_radio_actions(action_group, radioMenuEntries, G_N_ELEMENTS (radioMenuEntries), hspMode, G_CALLBACK(onToggleHspMode), window);

  /* If the HSPs are on initially then we're in hspOnly mode, so we don't show the pixmap; therefore,
   * only turn the pixelmap on if hsps are off */
  enableMenuAction(action_group, "TogglePixmap", (hspMode == DOTTER_HSPS_OFF));

  /* Disable menu items that require a selection */
  enableMenuAction(action_group, "CopySeln", FALSE);
  enableMenuAction(action_group, "CopySelnCoords", FALSE);
  enableMenuAction(action_group, "ClearSeln", FALSE);
  
  GtkUIManager *ui_manager = gtk_ui_manager_new ();
  gtk_ui_manager_insert_action_group (ui_manager, action_group, 0);
  gtk_ui_manager_set_add_tearoffs(ui_manager, TRUE);
  
  GtkAccelGroup *accel_group = gtk_ui_manager_get_accel_group (ui_manager);
  gtk_window_add_accel_group (GTK_WINDOW (window), accel_group);

  if (actionGroup_out)
    *actionGroup_out = action_group;

  return ui_manager;
}


/* Create a menu. Optionally add it to the given menu bar, if menuBar is not null, with the given label */
static GtkWidget* createDotterMenu(GtkWidget *window, 
                                   const char *menuDescription, 
                                   const char *path, 
                                   GtkUIManager *ui_manager)
{
  GError *error = NULL;
  if (!gtk_ui_manager_add_ui_from_string (ui_manager, menuDescription, -1, &error))
    {
      prefixError(error, "Building menus failed: ");
      reportAndClearIfError(&error, G_LOG_LEVEL_ERROR);
    }
  
  GtkWidget *menu = gtk_ui_manager_get_widget (ui_manager, path);
  
  return menu;
}


static GtkWidget* createDotterWindow(DotterContext *dc, 
                                     DotterWindowContext *dwc,
                                     const DotterHspMode hspMode, 
                                     GtkWidget *dotplot,
                                     GtkWidget *dotplotContainer, 
                                     GtkWidget *greyrampContainer,
                                     GtkWidget *alignmentContainer,
                                     GtkWidget *greyrampTool,
                                     GtkWidget *alignmentTool,
                                     GtkWidget *greyrampToolMinimised,
                                     const char *exportFileName,
                                     char *windowColor)
{ 
  DEBUG_ENTER("createDotterWindow");

  GtkWidget *dotterWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_widget_set_name(dotterWindow, MAIN_WINDOW_NAME);
  
  char *title = g_strdup_printf("%s%s vs. %s", dotterGetTitlePrefix(dc), dc->refSeqName, dc->matchSeqName);
  gtk_window_set_title(GTK_WINDOW(dotterWindow), title);
  g_free(title);
  
  /* Set the parent window in the message handlers' data, now we know it */
  dc->msgData->parent = GTK_WINDOW(dotterWindow);
  
  /* Create the menu bar, and a right-click context menu */
  dwc->uiManager = createUiManager(dotterWindow, hspMode, &dwc->actionGroup);
  GtkWidget *menuBar = createDotterMenu(dotterWindow, mainMenuDescription, "/MenuBar", dwc->uiManager);
  GtkWidget *contextMenu = createDotterMenu(dotterWindow, mainMenuDescription, "/ContextMenu", dwc->uiManager);
  GtkWidget *contextMenuGreyrampMin = createDotterMenu(dotterWindow, mainMenuDescription, "/MinimisedGreyrampContextMenu", dwc->uiManager);
  GtkWidget *contextMenuGreyrampMax = createDotterMenu(dotterWindow, mainMenuDescription, "/MaximisedGreyrampContextMenu", dwc->uiManager);
  GtkWidget *contextMenuAlignment = createDotterMenu(dotterWindow, mainMenuDescription, "/AlignmentContextMenu", dwc->uiManager);

  blxSetWidgetColor(menuBar, windowColor);

  /* We'll set the default window size based on the dotplot/exon widget size, up to a 
   * max based on screen size. */
  int maxWidth = 300, maxHeight = 200;
  gbtools::GUIGetTrueMonitorSizeFraction(dotterWindow, MAX_WINDOW_WIDTH_FRACTION, MAX_WINDOW_HEIGHT_FRACTION, &maxWidth, &maxHeight);

  const int exonViewHeight = 2 * (DEFAULT_EXON_HEIGHT + (2 * DEFAULT_EXON_YPAD));
  DotplotProperties *dotplotProperties = dotplotGetProperties(dotplot);
  const int dotplotWidth = getDotplotWidth(dotplot, dotplotProperties);
  int greyrampWidth = 400; /* roughly */
  const int alignmentToolHeight = 300; /* roughly */

  /* We'll base the layout on the relative size of the dotplot to the window size - we'll place
   * the greyramp tool on the same row as the dotplot if it'll fit and we can still display the
   * entire dotplot (not worrying about exons for now). If it won't fit, we'll place the greyramp
   * tool on the row below, adjacent to the alignment tool. */
  /*! \todo Ideally we'd adjust the layout after the user changes the settings, i.e. the zoom or
   * the range of sequence displayed */
  gboolean maximise_dotplot = FALSE;

  if (dotplotWidth > maxWidth - greyrampWidth)
    {
      maximise_dotplot = TRUE;
      greyrampWidth = 0; /* on a different row so don't include it in the width calculation */
    }

  if (MINIMISE_GREYRAMP_DEFAULT)
    {
      greyrampWidth = 0; /* full greyramp tool not shown so don't include it in the width calc */
    }

  int width = dotplotWidth + exonViewHeight + greyrampWidth;
  int height = getDotplotHeight(dotplot, dotplotProperties) + exonViewHeight + alignmentToolHeight;
  width = min(width, maxWidth);
  height = min(height, maxHeight);
  
  gtk_window_set_default_size(GTK_WINDOW(dotterWindow), width, height);

  /* Put the widgets in a table */
  const int numRows = 3;
  const int numCols = 2;
  int padding = 0;
  int row = 0;

  GtkTable *table = GTK_TABLE(gtk_table_new(numRows, numCols, FALSE));
  gtk_container_add(GTK_CONTAINER(dotterWindow), GTK_WIDGET(table));

  gtk_table_attach(table, menuBar, 0, numCols, row, row + 1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), GTK_SHRINK, padding, padding);
  ++row;

  if (maximise_dotplot)
    {
      /* dotplot spans all columns; alignment tool + greyramp on same row. */
      gtk_table_attach(table, dotplotContainer, 0, numCols, row, row + 1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), padding, padding);
      ++row;
      gtk_table_attach(table, greyrampToolMinimised, 0, numCols, row, row + 1, GTK_SHRINK, GTK_SHRINK, padding, padding);
      ++row;
      gtk_table_attach(table, alignmentContainer, 0, 1, row, row + 1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), GTK_SHRINK, padding, padding);
      gtk_table_attach(table, greyrampContainer, 1, 2, row, row + 1, GTK_SHRINK, GTK_FILL, padding, padding);
    }
  else
    {
      /* dotplot and greyramp on same row; alignment tool spans all columns */
      gtk_table_attach(table, dotplotContainer, 0, 1, row, row + 1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), padding, padding);
      gtk_table_attach(table, greyrampContainer, 1, 2, row, row + 1, GTK_SHRINK, GTK_FILL, padding, padding);
      ++row;
      gtk_table_attach(table, greyrampToolMinimised, 0, numCols, row, row + 1, GTK_SHRINK, GTK_SHRINK, padding, padding);
      ++row;
      gtk_table_attach(table, alignmentContainer, 0, numCols, row, row + 1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), GTK_SHRINK, padding, padding);
    }

  gtk_widget_add_events(dotterWindow, GDK_BUTTON_PRESS_MASK);
  gtk_widget_add_events(dotterWindow, GDK_POINTER_MOTION_MASK);
  g_signal_connect(G_OBJECT(dotterWindow), "key-press-event", G_CALLBACK(onKeyPressDotter), dotterWindow);
  g_signal_connect(G_OBJECT(dotterWindow), "motion-notify-event", G_CALLBACK(onMouseMoveDotter), NULL);
  g_signal_connect(G_OBJECT(dotterWindow), "button-press-event", G_CALLBACK(onButtonPressDotter), contextMenu);
  g_signal_connect(G_OBJECT(greyrampTool), "button-press-event", G_CALLBACK(onButtonPressTool), contextMenuGreyrampMax);
  g_signal_connect(G_OBJECT(greyrampToolMinimised), "button-press-event", G_CALLBACK(onButtonPressTool), contextMenuGreyrampMin);
  g_signal_connect(G_OBJECT(alignmentTool), "button-press-event", G_CALLBACK(onButtonPressTool), contextMenuAlignment);
  
  gtk_widget_show_all(dotterWindow);
  
  DEBUG_EXIT("createDotterWindow returning ");
  return dotterWindow;
}


/***********************************************************
 *                       Utilities                         *
 ***********************************************************/


/* Returns a string which is the name of the Dotter application. */
const char *dotterGetAppName(void)
{
  return DOTTER_TITLE ;
}

/* Returns a string which is the prefix to window titles. */
const char *dotterGetTitlePrefix(DotterContext *dc)
{
  return dc->abbrevTitle ? DOTTER_PREFIX_ABBREV : DOTTER_PREFIX ;
}

/* Returns a copyright string for the Dotter application. */
const char *dotterGetCopyrightString(void)
{
  return DOTTER_COPYRIGHT_STRING ;
}

/* Returns the Dotter website URL. */
const char *dotterGetWebSiteString(void)
{
  return DOTTER_WEBSITE_STRING ;
}

/* Returns a comments string for the Dotter application. Note that unlike the const
 * functions, this one allocates a new string which must be free'd by the caller */
const char *dotterGetCommentsString(void)
{
  char *result = g_strdup_printf("%s\n%s\n%s %s\n\n%s\n", 
                                 DOTTER_TITLE_STRING, 
                                 gbtools::UtilsGetVersionTitle(),
                                 UT_COMPILE_PHRASE, 
                                 UT_MAKE_COMPILE_DATE(), 
                                 AUTHOR_TEXT);

  return result;
}

/* Returns a license string for the dotter application. */
const char *dotterGetLicenseString(void)
{
  return DOTTER_LICENSE_STRING ;
}

/* Returns a string representing the Version/Release/Update of the Dotter code. */
const char *dotterGetVersionString(void)
{
  return DOTTER_VERSION_STRING ;
}

/* Utility to copy an integer value as a string to the default clipboard */
void copyIntToDefaultClipboard(const int val)
{
  char *displayText = convertIntToString(val);
  setDefaultClipboardText(displayText);
  g_free(displayText); 
}


/* Print the main dotter window */
static void printDotterWindow(GtkWidget *dotterWindow)
{
  DotterProperties *properties = dotterGetProperties(dotterWindow);

  /* Set the background colour to something sensible for printing */
  GdkColor *defaultBgColor = getGdkColor(DOTCOLOR_BACKGROUND, properties->dotterWinCtx->dotterCtx->defaultColors, FALSE, TRUE);
  setWidgetBackgroundColor(dotterWindow, defaultBgColor);
  redrawAll(dotterWindow, NULL);

  /* The crosshair on the dotplot does not get cached in the dotplot's drawable,
   * but we want it to show in the print, so draw it on now. */
  GtkWidget *dotplot = properties->dotplot;
  dotplotPrepareForPrinting(dotplot);
  
  /* Print the parent of the dotplot, because this contains the exon views as well.
   * Note that we don't want to print the scrolled window, because that will chop off
   * parts of the plot that are not currently visible; we want to print the whole plot) */
  GtkWidget *parent = gtk_widget_get_parent(dotplot);

  /* Do the print */
  DotterWindowContext *dwc = properties->dotterWinCtx;
  blxPrintWidget(parent, NULL, GTK_WINDOW(dotterWindow), &dwc->printSettings, &dwc->pageSetup, NULL, TRUE, PRINT_FIT_BOTH);
  
  /* Revert the background colour */
  onPrintColorsChanged(dotterWindow);

  /* Redraw the entire dotplot to make sure the crosshair we added gets cleared */
  redrawAll(dotterWindow, NULL);
}


/**************************** eof ***************************/