File: blxview.cpp

package info (click to toggle)
seqtools 4.44.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 28,492 kB
  • sloc: cpp: 53,636; sh: 12,232; makefile: 386
file content (2012 lines) | stat: -rw-r--r-- 71,694 bytes parent folder | download | duplicates (4)
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
/*  File: blxview.c
 *  Author: Erik Sonnhammer, 1993-02-20
 *  Copyright (c) 2009 - 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: Setup and miscellaneous functions for Blixem.
 *               
 *              This file is a bit of a mish-mash. It originally contained all
 *              of the graphical stuff for Blixem, but that has been moved to
 *              other files. This file now mostly contains setup functions,
 *              but it also contains other functions that don't really belong
 *              anywhere else.
 *----------------------------------------------------------------------------
 */


/*
MSP score codes (for obsolete exblx file format):
----------------
-1 exon                  -> Big picture + Alignment
-2 intron                -> Big picture + Alignment
-3 Any colored segment   -> Big picture
-4 stringentSEGcolor     -> Big picture
-5 mediumSEGcolor        -> Big picture
-6 nonglobularSEGcolor   -> Big picture
-10 hidden by hand
*/

#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <gdk/gdkkeysyms.h>
#include <algorithm>

#include <blixemApp/blixem_.hpp>
#include <blixemApp/blxcontext.hpp>
#include <blixemApp/blxwindow.hpp>
#include <blixemApp/detailview.hpp>
#include <blixemApp/blxdotter.hpp>
#include <blixemApp/sequencecellrenderer.hpp>
#include <seqtoolsUtils/blxmsp.hpp>
#include <seqtoolsUtils/blxparser.hpp>
#include <seqtoolsUtils/utilities.hpp>
#include <gbtools/gbtools.hpp>

using namespace std;


#define MAXALIGNLEN			      10000
#define ORGANISM_PREFIX_SEPARATOR	      "  "
#define GFF3_VERSION_HEADER		      "##gff-version 3"	  /* the header line of a GFF v3 file */
#define GFF3_SEQUENCE_REGION_HEADER	      "##sequence-region" /* the start comment of the sequence-region comment line in a GFF v3 file */
#define MIN_GAP_HIGHLIGHT_WIDTH		      5			  /* minimum width of assembly gaps markers */


static void            blviewCreate(char *align_types, const char *paddingSeq, GArray* featureLists[], GList *seqList, GSList *supportedTypes, CommandLineOptions *options, const gboolean External, GSList *styles) ;
static void            processGeneName(BlxSequence *blxSeq);
static void            processOrganism(BlxSequence *blxSeq);


/* GLOBAL VARIABLES... sigh... */

GtkWidget *blixemWindow = NULL ;
static char *padseq = 0;



/*
 *                Internal routines
 */


//static int possort(MSP *msp1, MSP *msp2) {
//    return ( (msp1->qstart > msp2->qstart) ? 1 : -1 );
//}
//
//static int namesort(MSP *msp1, MSP *msp2) {
//    if (strcmp(msp1->sname, msp2->sname))
//	return strcmp(msp1->sname, msp2->sname);
//    else
//	return possort(msp1, msp2);
//}
//static int scoresort(MSP *msp1, MSP *msp2) {
//    return ( (msp1->score < msp2->score) ? 1 : -1 );
//}
//
//static int idsort(MSP *msp1, MSP *msp2)
//{
//  int result = 0 ;
//
//  result = ( (msp1->id < msp2->id) ? 1 : -1 ) ;
//
//  return result ;
//}


//static void wholePrint(void)
//{
   // int
//	tmp,
//	dispstart_save = dispstart,
//	BigPictON_save = BigPictON;
//
//    static int
//	start=1, end=0;
//    ACEIN zone_in;
//
//    if (!end) end = qlen;
//
//    /* Swap coords if necessary */
//    if ((plusmin < 0 && start < end) || (plusmin > 0 && start > end )) {
//	tmp = start;
//	start = end;
//	end = tmp;
//    }
//
//    /* Apply max limit MAXALIGNLEN */
//    if ((abs(start-end)+1) > MAXALIGNLEN*symbfact) {
//	start = dispstart - plusmin*MAXALIGNLEN*symbfact;
//	if (start < 1) start = 1;
//	if (start > qlen) start = qlen;
//
//	end = start + plusmin*MAXALIGNLEN*symbfact;
//	if (end > qlen) end = qlen;
//	if (end < 1) end = 1;
//    }
//
//    if (!(zone_in = messPrompt("Please state the zone you wish to print",
//			       messprintf("%d %d", start, end),
//			       "iiz", 0)))
//      return;
//
//    aceInInt(zone_in, &start);
//    aceInInt(zone_in, &end);
//    aceInDestroy (zone_in);
//
//    dispstart = start;
//    displen = abs(end-start)+1;
//
//    /* Validation */
//    if (plusmin > 0 && start > end) {
//	g_message("Please give a range where from: is less than to:");
//	return;
//    }
//    else if (plusmin < 0 && start < end) {
//	g_message("Please give a range where from: is more than to:");
//	return;
//    }
//    if (displen/symbfact > MAXALIGNLEN) {
//	g_message("Sorry, can't print more than %d residues.  Anyway, think of the paper!", MAXALIGNLEN*symbfact);
//	return;
//    }
//
//    wholePrintOn = 1;
//    BigPictON = 0;
////    oneGraph = 1;
//
//    blviewRedraw();
//    graphPrint();
//
//    /* Restore */
//    wholePrintOn = 0;
//    dispstart = dispstart_save;
//    displen = dispstart_save;
////    oneGraph = 0;
//    BigPictON = BigPictON_save;
//
//    blviewRedraw();
//}

//static void blxPrint(void)
//{
//  oneGraph = 1;
//  blviewRedraw();
//  graphPrint();
//  oneGraph = 0;
//
//  blviewRedraw();
//}


/* Check we have everything we need */
static void validateInput(CommandLineOptions *options)
{
  if (!options->refSeq)
    {
      g_error("Error: reference sequence not specified.\n");
    }
  
  /* if we were given the blast mode instead of seq type, determine the display sequence type */
  if (options->seqType == BLXSEQ_NONE && options->blastMode != BLXMODE_UNSET)
    {
      if (options->blastMode == BLXMODE_BLASTN)
        options->seqType = BLXSEQ_DNA;
      else
        options->seqType = BLXSEQ_PEPTIDE;
    }
  
  /* Check we have a valid seq type */
  if (options->seqType == BLXSEQ_NONE)
    {
      g_message("\nNo sequence type specified. Detected ");
      
      GError *error = NULL;
      BlxSeqType seqType = determineSeqType(options->refSeq, &error);
      reportAndClearIfError(&error, G_LOG_LEVEL_ERROR);
      
      if (seqType == BLXSEQ_PEPTIDE)
	{
	  g_message("protein sequence. Will try to run Blixem in protein mode.\n");
	  options->seqType = BLXSEQ_PEPTIDE;
	}
      else
	{
	  g_message("nucleotide sequence. Will try to run Blixem in nucelotide mode.\n");
	  options->seqType = BLXSEQ_DNA;
	}
    }
  
  /* Ideally we'd get rid of blast mode and just deal with real sequence types (ref seq type, match
   * seq type and display type), but it's too in-built for now so make sure it's set */
  if (options->blastMode == BLXMODE_UNSET)
    options->blastMode = (options->seqType == BLXSEQ_DNA ? BLXMODE_BLASTN : BLXMODE_BLASTX);
  
  /* Set the number of reading frames */
  if (options->seqType == BLXSEQ_PEPTIDE)
    options->numFrames = 3;
  else
    options->numFrames = 1;
  
  /* Now we've got the ref seq, we can work out the zoom, if zooming to view the whole sequence */
  if (options->zoomWhole)
    {
      options->bigPictZoom = strlen(options->refSeq);
    }
  else
    {
      if (options->seqType == BLXSEQ_DNA)
        options->bigPictZoom = 30;
      else
        options->bigPictZoom = 10;
    }  
}




/* Utility to get the parent sequence of the given variant, if it is not already set.
 * returns true if the returned parent is not null. */
static gboolean getParent(BlxSequence *variant, BlxSequence **parent, GList *allSeqs)
{
  if (*parent == NULL)
    {
      *parent = blxSequenceGetVariantParent(variant, allSeqs);
    }
  
  return (*parent != NULL);
}


/* This function checks if the given sequence is missing its optional data (such as organism
 * and gene name) and, if so, looks for the parent sequence and copies the data from there. */
static void populateMissingDataFromParent(BlxSequence *curSeq, GList *seqList, GList *columnList)
{
  BlxSequence *parent = NULL;
  GList *item = columnList;
  
  for ( ; item; item = item->next)
    {
      BlxColumnInfo *columnInfo = (BlxColumnInfo*)(item->data);
      GValue *value = blxSequenceGetValue(curSeq, columnInfo->columnId);
      
      if (!value)
        {
          getParent(curSeq, &parent, seqList);
          GValue *parentValue = blxSequenceGetValue(parent, columnInfo->columnId);
          blxSequenceSetValue(curSeq, columnInfo->columnId, parentValue);
        }
    }
}


/* Merge new features into our existing context: merges the newMsps list into mspList and newSeqs
 * list into seqList. Takes ownership of the contents of both newMsps and newSeqs. */
void blxMergeFeatures(MSP *newMsps, GList *newSeqs, MSP **mspList, GList **seqList)
{
  g_return_if_fail(mspList && seqList);

  if (mspList && *mspList)
    {
      /* Append new MSPs to MSP list */
      MSP *lastMsp = *mspList;
  
      while (lastMsp->next)
        lastMsp = lastMsp->next;
  
      lastMsp->next = newMsps;
    }
  else
    {
      /* Create new msp list */
      *mspList = newMsps;
    }

  /* Append new sequences to sequence list */
  *seqList = g_list_concat(*seqList, newSeqs);
}


/* This function to loads the contents of a natively-supported features file
 * (e.g. GFF) into blixem. The new features are appended onto the existing
 * sequence and MSP lists.
 * A non-local or non-native file can be passed to check if it is loadable
 * and, if not, this function returns early and sets the error. */
void loadNativeFile(const char *filename,
                    const char *buffer,
                    GKeyFile *keyFile,
                    BlxBlastMode *blastMode,
                    GArray* featureLists[],
                    GSList *supportedTypes, 
                    GSList *styles,
                    MSP **newMsps,
                    GList **newSeqs,
                    GList *columnList,
                    GHashTable *lookupTable,
                    const int refSeqOffset,
                    const IntRange* const refSeqRange,
                    GError **error)
{
  if (!filename && !buffer)
    {
      g_set_error(error, BLX_ERROR, 1, "No file or buffer provided.");
      return;
    }

  char *dummyseq1 = NULL;    /* Needed for blxparser to handle both dotter and blixem */
  char dummyseqname1[FULLNAMESIZE+1] = "";
  char *dummyseq2 = NULL;    /* Needed for blxparser to handle both dotter and blixem */
  char dummyseqname2[FULLNAMESIZE+1] = "";

  /* The range passed to the parser must be in the original parsed coords, so subtract the
   * offset. (It is used to validate that the range in the GFF file we're reading in is within 
   * blixem's known range.)  */
  IntRange toplevelRange;
  
  if (refSeqRange)
    {
      toplevelRange.set(refSeqRange->min() - refSeqOffset, refSeqRange->max() - refSeqOffset);
    }
  
  if (filename)
    {
      /* Open the file for reading */
      FILE *file = fopen(filename, "r");

      if (!file)
        {
          g_set_error(error, BLX_ERROR, 1, "Error opening file '%s' for reading.\n", filename);
        }
      else
        {
          parseFS(newMsps, file, blastMode, featureLists, newSeqs, columnList, supportedTypes, styles,
                  &dummyseq1, dummyseqname1, &toplevelRange, &dummyseq2, dummyseqname2, keyFile, lookupTable, NULL, error) ;
          
          fclose(file);
        }
    }
  else if (buffer)
    {
      parseBuffer(newMsps, buffer, blastMode, featureLists, newSeqs, columnList, supportedTypes, styles,
                  &dummyseq1, dummyseqname1, &toplevelRange, &dummyseq2, dummyseqname2, keyFile, lookupTable, error) ;      
    }
}


/* Once we've fetched all the sequences we need to do some post-processing. Loop 
 * twice: once to modify any fields in our own custom manner, and once more to
 * see if any with missing data can copy it from their parent. (Need to do these in
 * separate loops or we don't know if the data we're copying is processed or not.) */
void finaliseFetch(GList *seqList, GList *columnList)
{
  GList *seqItem = seqList;

  for ( ; seqItem; seqItem = seqItem->next)
    {
      BlxSequence *blxSeq = (BlxSequence*)(seqItem->data);
      processGeneName(blxSeq);
      processOrganism(blxSeq);
    }
  
  for (seqItem = seqList; seqItem; seqItem = seqItem->next)
    {
      BlxSequence *blxSeq = (BlxSequence*)(seqItem->data);
      populateMissingDataFromParent(blxSeq, seqList, columnList);
    }
}


/* Find any gaps in the reference sequence */
static void findAssemblyGaps(const char *refSeq, GArray *featureLists[], MSP **mspList, const IntRange* const refSeqRange)
{
  /* Find the last msp in the list so we can append new ones to the end */
  MSP *lastMsp = *mspList;
  while (lastMsp && lastMsp->next)
    lastMsp = lastMsp->next;
  
  /* Scan for the gap character */
  const char *cp = strchr(refSeq, SEQUENCE_CHAR_GAP);

  while (cp && *cp)
    {
      /* Found the start of a gap; remember the start coord */
      const int startCoord = cp - refSeq + refSeqRange->min();
    
      /* Loop until we find a non-gap character (or the end of the string) */
      while (cp && *cp == SEQUENCE_CHAR_GAP)
	++cp;
    
      const int endCoord = cp - refSeq - 1 + refSeqRange->min();
    
      MSP *msp = createEmptyMsp(&lastMsp, mspList);
      msp->type = BLXMSP_GAP;
      msp->qRange.set(startCoord, endCoord);
      
      featureLists[msp->type] = g_array_append_val(featureLists[msp->type], msp);
    
      /* Continue looking for more gaps */
      cp = strchr(cp, SEQUENCE_CHAR_GAP);
    }
}


/* blxview() can be called either from other functions in the Blixem
 * program itself or directly by functions in other programs such as
 * xace.
 *
 * Interface
 *    pfetch:  if non-NULL, then we use pfetch instead of efetch for
 *             _all_ sequence fetching (use the node/port info. in the
 *             pfetch struct to locate the pfetch server).
 *
 */
gboolean blxview(CommandLineOptions *options,
                 GArray* featureLists[],
                 GList *seqList,
                 GSList *supportedTypes,
                 PfetchParams *pfetch, 
                 char *align_types, 
                 gboolean External,
                 GSList *styles,
                 GHashTable *lookupTable)
{
  if (blixemWindow)
    gtk_widget_destroy(blixemWindow) ;

  if (!External)
    {
      /* When being called internally, the config file will not have been
       * initialised yet, so do it now. */
      GError *error = NULL;
      blxInitConfig(NULL, options, &error);
      reportAndClearIfError(&error, G_LOG_LEVEL_WARNING);
    }
  
  validateInput(options);
  
  /* Find any assembly gaps (i.e. gaps in the reference sequence) */
  findAssemblyGaps(options->refSeq, featureLists, &options->mspList, &options->refSeqRange);

  /* offset has not been applied yet, so pass offset=0 */
  BulkFetch bulk_fetch(External, options->saveTempFiles, options->seqType,
                       &seqList, options->columnList,
                       options->bulkFetchDefault, options->fetchMethods, &options->mspList, &options->blastMode, 
                       featureLists, supportedTypes, NULL, 0, &options->refSeqRange, 
                       options->dataset, FALSE, lookupTable,
#ifdef PFETCH_HTML
                       options->ipresolve,
                       options->cainfo,
#endif
                       options->fetch_debug); 

  gboolean status = bulk_fetch.performFetch();

  if (status)
    {
      finaliseFetch(seqList, options->columnList);

      /* Construct missing data and do any other required processing now we have all the sequence data */
      finaliseBlxSequences(featureLists, &options->mspList, &seqList, options->columnList, 
                           options->refSeqOffset, options->seqType, 
                           options->numFrames, &options->refSeqRange, TRUE, lookupTable);

    }

  /* Note that we create a blxview even if MSPlist is empty.
   * But only if it's an internal call.  If external & anything's wrong, we die. */
  if (status || !External)
    {
      blviewCreate(align_types, padseq, featureLists, seqList, supportedTypes, options, External, styles) ;
    }

  return status;
}


/* Find all of the different alignment types (i.e. source names) and 
 * compile them into a single string, separated by the given separator string */
static char* findAlignTypes(GArray* featureLists[], const char *separatorStr)
{
  GSList *sourceList = NULL;
  GString *resultStr = g_string_new(NULL);
  
  /* Loop through all MSPs of type 'match' */
  const GArray* const mspList = featureLists[BLXMSP_MATCH];
  
  int i = 0;
  const MSP *msp = mspArrayIdx(mspList, i);
  
  for ( ; msp; msp = mspArrayIdx(mspList, ++i))
    {
      const char *source = mspGetSource(msp);
      
      if (source)
        {
          /* See if we've already seen this source. If not, add it to the list,
           * and append it to the string. */
          GQuark quark = g_quark_from_string(source);
          
          if (!g_slist_find(sourceList, GINT_TO_POINTER(quark)))
            {
              sourceList = g_slist_prepend(sourceList, GINT_TO_POINTER(quark));
              
              if (resultStr->len)
                g_string_append(resultStr, separatorStr);
              
              g_string_append(resultStr, source);
            }
        }
    }
  
  char *result = resultStr->str;
  g_string_free(resultStr, FALSE);
  
  return result;
}


/* Initialize the display and the buttons */
static void blviewCreate(char *align_types, 
			 const char *paddingSeq,
                         GArray* featureLists[],
                         GList *seqList,
                         GSList *supportedTypes,
			 CommandLineOptions *options,
                         const gboolean External,
                         GSList *styles)
{
  if (!blixemWindow)
    {
      /* Create the window */
      blixemWindow = createBlxWindow(options, paddingSeq, featureLists, seqList, supportedTypes, External, styles);

      /* Set the window title. Get a description of all the alignment types 
       * (unless already supplied) */
      if (!align_types)
        align_types = findAlignTypes(featureLists, ", ");

      /* If no alignment description was set, create a generic description */
      if (!align_types)
        align_types = g_strdup_printf("%s", options->seqType == BLXSEQ_PEPTIDE ? "peptide alignment" : "nucleotide alignment");
      
      BlxContext *bc = blxWindowGetContext(blixemWindow);
      
      char *title = g_strdup_printf("%s(%s) %s %s",
                                    blxGetTitlePrefix(bc),
                                    align_types,
                                    (options->dataset ? options->dataset : ""),
                                    options->refSeqName);
      
      gtk_window_set_title(GTK_WINDOW(blixemWindow), title);
      g_free(title);
    }

  char *nameSeparatorPos = (char *)strrchr(options->refSeqName, '/');
  if (nameSeparatorPos)
    {
      options->refSeqName = nameSeparatorPos + 1;
    }
  
  if (options->dotterFirst && options->mspList && options->mspList->sname &&
      (mspIsBlastMatch(options->mspList) || options->mspList->type == BLXMSP_HSP || options->mspList->type == BLXMSP_GSP))
    {
      /* We must select the sequence before calling callDotter. Get the first
       * sequence to the right of the start coord. */
      MSP *msp = nextMatch(blxWindowGetDetailView(blixemWindow), NULL, FALSE);
      
      if (msp)
        {
          blxWindowSelectSeq(blixemWindow, msp->sSequence);
          
          GError *error = NULL;
          
          if (!error)
            {
              callDotterOnSelectedSeqs(blixemWindow, FALSE, FALSE, BLXDOTTER_REF_AUTO, NULL);
            }
            
          reportAndClearIfError(&error, G_LOG_LEVEL_CRITICAL);
        }
      else 
        {
          g_error("Could not run Dotter on first sequence; no sequences found to the right of the start coord.\n");
        }
    }

  if (options->startNextMatch)
    {
      /* Set the start coord to be the start of the next MSP on from the default start coord */
      nextMatch(blxWindowGetDetailView(blixemWindow), NULL, FALSE);
    }
}

/***********************************************************
 *               Sequences and MSPs
 ***********************************************************/

/* The parsed gene name generally contains extra info that we're not interested in. This function
 * tries to extract just the part of the info that we're interested in. */
static void processGeneName(BlxSequence *blxSeq)
{
  /* Data is usually in the format: "Name=SMARCA2; Synonyms=BAF190B, BRM, SNF2A, SNF2L2;"
   * Therefore, look for the Name tag and extract everything up to the ; or end of line.
   * If there is no name tag, just include everything */
  const char *geneName = blxSequenceGetGeneName(blxSeq);
  
  if (geneName)
    {
      const char *startPtr = strstr(geneName, "Name=");
      
      if (!startPtr)
        {
          startPtr = strstr(geneName, "name=");
        }
        
      if (startPtr)
        {
          startPtr += 5;
          const char *endPtr = strchr(startPtr, ';');
          const int numChars = endPtr ? endPtr - startPtr : strlen(startPtr);
          
          char *result = (char*)g_malloc((numChars + 1) * sizeof(char));
          
          g_utf8_strncpy(result, startPtr, numChars);
          result[numChars] = 0;
          
          blxSequenceSetValueFromString(blxSeq, BLXCOL_GENE_NAME, result);

          g_free(result);
        }
    }
}


/* Add a prefix to the given BlxSequence's organism field, e.g. change "Homo sapiens (human)" 
 * to "Hs - Homo sapiens (human)". This is so that we can have a very narrow column that just 
 * displays the prefix part of the field. */
static void processOrganism(BlxSequence *blxSeq)
{
  const char *organism = blxSequenceGetOrganism(blxSeq);
  
  if (organism)
    {
      /* To create the alias, we'll take the first letter of each word until we hit a non-alpha
       * character. To reduce likelihood of duplicates, we'll take 3 chars from the second word
       * and then quit. e.g. 
       *   Homo sapiens (human)           -> Hsap
       *   Mus musculus (house mouse)     -> Mmus 
       *   Macaca mulatta (Rhesus monkey) -> Mmul 
       */
      int srcIdx = 0;
      int srcLen = strlen(organism);
      
      int destIdx = 0;
      int destLen = 5; /* limit the length of the alias */
      char alias[destLen + 1];
      
      gboolean startWord = TRUE;
      gboolean first = TRUE;
      
      for ( ; srcIdx < srcLen && destIdx < destLen; ++srcIdx)
        {
          if (organism[srcIdx] == ' ')
            {
              startWord = TRUE;
            }
          else if (g_ascii_isalpha(organism[srcIdx]))
            {
              if (startWord)
                {
                  alias[destIdx] = organism[srcIdx];
                  ++destIdx;
                  startWord = FALSE;

                  if (!first)
                    {
                      /* For the second word, also include the next 2 chars 
                       * and then exit. */
                      ++srcIdx;
                      if (srcIdx < srcLen && destIdx < destLen)
                        {
                          alias[destIdx] = organism[srcIdx];
                          ++destIdx;
                        }

                      ++srcIdx;
                      if (srcIdx < srcLen && destIdx < destLen)
                        {
                          alias[destIdx] = organism[srcIdx];
                          ++destIdx;
                        }
                      break;
                    }

                  first = FALSE;
                }
            }
          else
            {
              /* Finish if we've hit a char that's not an alpha char or space. */
              break;
            }
        }

      alias[destIdx] = '\0';
      
      if (destIdx > 0)
        {
          blxSeq->organismAbbrev = g_strdup(alias);
        }
    }
}


/* Returns true if this msp is part of a feature series */
gboolean mspHasFs(const MSP *msp)
{
  gboolean result = (msp->type == BLXMSP_FS_SEG || msp->type == BLXMSP_XY_PLOT);
  return result;
}


/* Return the (cached) full extent of the match that we're showing in match seq coords */
const IntRange* mspGetFullSRange(const MSP* const msp, const gboolean seqSelected, const BlxContext* const bc)
{
  const IntRange *result = NULL;
  
  if (seqSelected || !bc->flags[BLXFLAG_SHOW_UNALIGNED_SELECTED] || !bc->flags[BLXFLAG_SHOW_POLYA_SITE_SELECTED])
    result = &msp->fullSRange;
  else
    result = &msp->sRange;

  if (!result->isSet())
    g_warn_if_reached();
  
  return result;
}

/* Return the (cached) full extent of the match on the ref sequence in display coords
 * (including any portions of unaligned sequence that we're showing). Depending on the
 * options, the range may depend on whether the sequence is selected or not. */
const IntRange* mspGetFullDisplayRange(const MSP* const msp, const gboolean seqSelected, const BlxContext* const bc)
{
  const IntRange *result = NULL;
  
  /* Check if showing unaligned sequence or polya tails for all sequences, or just the selected
     sequence */
  if ((bc->flags[BLXFLAG_SHOW_UNALIGNED] || bc->flags[BLXFLAG_SHOW_POLYA_SITE]) && 
      (seqSelected || 
       (bc->flags[BLXFLAG_SHOW_UNALIGNED] && !bc->flags[BLXFLAG_SHOW_UNALIGNED_SELECTED]) || 
       (bc->flags[BLXFLAG_SHOW_POLYA_SITE] && !bc->flags[BLXFLAG_SHOW_POLYA_SITE_SELECTED])))
    {
      result = &msp->fullRange;
    }
  else
    {
      result = &msp->displayRange;
    }

  if (!result->isSet())
    g_warn_if_reached();

  return result;
}

/* Return the (cached) extent of the alignment that we're showing in display coords
 * (excluding unaligned sequence) */
const IntRange* mspGetDisplayRange(const MSP* const msp)
{
  return &msp->displayRange;
}


/* Get the full range of the given MSP that we want to display, in s coords. This will generally 
 * be the coords of the alignment but could extend outside this range we are displaying unaligned 
 * portions of the match sequence or polyA tails etc. */
static void mspCalcFullSRange(const MSP* const msp, 
			      const gboolean *flags,
			      const int numUnalignedBases, 
			      const GArray* const polyASiteList,
			      IntRange *result)
{
  /* Normally we just display the part of the sequence in the alignment */
  result->set(msp->sRange);
  
  if (mspIsBlastMatch(msp))
    {
      if (flags[BLXFLAG_SHOW_UNALIGNED] && mspGetMatchSeq(msp))
	{
	  /* We're displaying additional unaligned sequence outside the alignment range. Get 
	   * the full range of the match sequence */
	  result->set(1, mspGetMatchSeqLen(msp));
	  
	  if (flags[BLXFLAG_LIMIT_UNALIGNED_BASES])
	    {
	      /* Only include up to 'numUnalignedBases' each side of the MSP range (still limited
	       * to the range we found above, though). */
	      result->set(max(result->min(), msp->sRange.min() - numUnalignedBases), 
                          min(result->max(), msp->sRange.max() + numUnalignedBases));
	    }
	}
      
      if (flags[BLXFLAG_SHOW_POLYA_SITE] && mspHasPolyATail(msp))
	{
	  /* We're displaying polyA tails, so override the 3' end coord with the full extent of
	   * the s sequence if there is a polyA site here. The 3' end is the min q coord if the
	   * match is on forward ref seq strand or the max coord if on the reverse. */
	  const gboolean sameDirection = (mspGetRefStrand(msp) == mspGetMatchStrand(msp));
	  
	  if (sameDirection)
	    {
	      result->setMax(mspGetMatchSeqLen(msp));
	    }
	  else
	    {
	      result->setMin(1);
	    }
	}
    }
}


/* Get the full range of the given MSP that we want to display, in q coords. This will generally 
 * be the coords of the alignment but could extend outside this range we are displaying unaligned 
 * portions of the match sequence or polyA tails etc. */
static void mspCalcFullQRange(const MSP* const msp, 
			      const gboolean *flags,
			      const int numUnalignedBases, 
			      const GArray* const polyASiteList,
			      const int numFrames,
			      const IntRange* const fullSRange,
			      IntRange *result)
{
  /* Default to the alignment range so we can exit quickly if there are no special cases */
  result->set(msp->qRange);
  
  if (mspIsBlastMatch(msp) && (flags[BLXFLAG_SHOW_UNALIGNED] || flags[BLXFLAG_SHOW_POLYA_SITE]))
    {
      /* Find the offset of the start and end of the full range compared to the alignment range and
       * offset the ref seq range by the same amount. We need to multiply by the number of reading
       * frames because q coords are in nucleotides and s coords are in peptides. */
      const int startOffset = (msp->sRange.min() - fullSRange->min()) * numFrames;
      const int endOffset = (fullSRange->max() - msp->sRange.max()) * numFrames;
      
      const gboolean sameDirection = (mspGetRefStrand(msp) == mspGetMatchStrand(msp));

      if (sameDirection)
        {
          result->set(result->min() - startOffset, result->max() + endOffset);
        }
      else
        {
          result->set(result->min() - endOffset, result->max() + startOffset);
        }
    }
}


/* Calculate the full extent of the match sequence to display, in display coords,
 * and cache the result in the msp. Includes any portions of unaligned sequence that we're
 * displaying */
void mspCalculateFullExtents(MSP *msp, const BlxContext* const bc, const int numUnalignedBases)
{
  mspCalcFullSRange(msp, bc->flags, numUnalignedBases, bc->featureLists[BLXMSP_POLYA_SITE], &msp->fullSRange);
  mspCalcFullQRange(msp, bc->flags, numUnalignedBases, bc->featureLists[BLXMSP_POLYA_SITE], bc->numFrames, &msp->fullSRange, &msp->fullRange);
 
  /* convert the Q range to display coords */
  const int frame = mspGetRefFrame(msp, bc->seqType);
  const int coord1 = convertDnaIdxToDisplayIdx(msp->fullRange.min(), bc->seqType, frame, bc->numFrames, bc->displayRev, &bc->refSeqRange, NULL);
  const int coord2 = convertDnaIdxToDisplayIdx(msp->fullRange.max(), bc->seqType, frame, bc->numFrames, bc->displayRev, &bc->refSeqRange, NULL);
  msp->fullRange.set(coord1, coord2);
  
  /* Remember the max len of all the MSPs in the detail-view */
  if (typeShownInDetailView(msp->type) && msp->fullRange.length() > getMaxMspLen())
    {
      setMaxMspLen(msp->fullRange.length());
    }
}


/* Convert the ref-seq range of the given msp in display coords and cache it in the msp */
static void mspCalculateDisplayRange(MSP *msp, const BlxContext* const bc)
{
  const int frame = mspGetRefFrame(msp, bc->seqType);
  const int coord1 = convertDnaIdxToDisplayIdx(msp->qRange.min(), bc->seqType, frame, bc->numFrames, bc->displayRev, &bc->refSeqRange, NULL);
  const int coord2 = convertDnaIdxToDisplayIdx(msp->qRange.max(), bc->seqType, frame, bc->numFrames, bc->displayRev, &bc->refSeqRange, NULL);
  msp->displayRange.set(coord1, coord2);  
}


/* This caches the display range (in display coords rather than dna coords,
 * and inverted if the display is inverted) for each MSP */
void cacheMspDisplayRanges(const BlxContext* const bc, const int numUnalignedBases)
{
  /* This also calculates the max msp len */
  setMaxMspLen(0);
  
  MSP *msp = bc->mspList;
  for ( ; msp; msp = msp->next)
    {
      mspCalculateDisplayRange(msp, bc);
      mspCalculateFullExtents(msp, bc, numUnalignedBases);
    }
}


/* Return the match-sequence coord of an MSP at the given reference-sequence coord,
 * where the MSP is a gapped MSP and the ref-seq coord is known to lie within the
 * MSP's alignment range. */
static gboolean mspGetGappedAlignmentCoord(const MSP *msp, const int qIdx, const BlxContext *bc, int *result_out)
{
  gboolean success = FALSE;
  int result = UNSET_INT;
  
  const gboolean qForward = (mspGetRefStrand(msp) == BLXSTRAND_FORWARD);
  const gboolean sameDirection = (mspGetRefStrand(msp) == mspGetMatchStrand(msp));

  /* Gapped alignment. Look to see if x lies inside one of the "gaps" ranges. */
  GSList *rangeItem = msp->gaps;
  
  for ( ; rangeItem ; rangeItem = rangeItem->next)
    {
      CoordRange *curRange = (CoordRange*)(rangeItem->data);
      
      int qRangeMin, qRangeMax, sRangeMin, sRangeMax;
      getCoordRangeExtents(curRange, &qRangeMin, &qRangeMax, &sRangeMin, &sRangeMax);
      
      /* We've "found" the value if it's in or before this range. Note that the
       * the range values are in decreasing order if the q strand is reversed. */
      gboolean found = qForward ? qIdx <= qRangeMax : qIdx >= qRangeMin;
      
      if (found)
        {
          gboolean inRange = (qForward ? qIdx >= qRangeMin : qIdx <= qRangeMax);
          
          if (inRange)
            {
              /* It's inside this range. Calculate the actual index. */
              int offset = (qIdx - qRangeMin) / bc->numFrames;
              result = sameDirection ? sRangeMin + offset : sRangeMax - offset;
              success = TRUE;
            }
          
          break;
        }
    }
  
  if (success && result_out)
    *result_out = result;

  return success;
}


/* Return the match-sequence coord of an MSP at the given reference-sequence coord,
 * where the MSP is an ungapped MSP and the ref-seq coord is known to lie within the
 * MSP's alignment range. */
static gboolean mspGetUngappedAlignmentCoord(const MSP *msp, const int qIdx, const BlxContext *bc, int *result_out)
{
  gboolean success = FALSE;
  int result = UNSET_INT;
  
  /* If strands are in the same direction, find the offset from qRange.min and add it to 
   * sRange.min. If strands are in opposite directions, find the offset from qRange.min and
   * subtract it from sRange.max. Note that the offset could be negative if we're outside
   * the alignment range. */
  int offset = (qIdx - msp->qRange.min()) / bc->numFrames ;
  const gboolean sameDirection = (mspGetRefStrand(msp) == mspGetMatchStrand(msp));

  result = (sameDirection) ? msp->sRange.min() + offset : msp->sRange.max() - offset ;
  
  if (result < msp->sRange.min() || result > msp->sRange.max())
    {
      result = UNSET_INT;
      success = FALSE;
    }
  else
    {
      success = TRUE;
    }
  
  if (success && result_out)
    *result_out = result;

  return success;
}  


/* Return the match-sequence coord of an MSP at the given reference-sequence coord,
 * where the ref-seq coord is known to lie outside the MSP's alignment range. The 
 * result will be unset unless the option to display unaligned portions of 
 * sequence is enabled. */
static gboolean mspGetUnalignedCoord(const MSP *msp, 
                                     const int qIdx, 
                                     const gboolean seqSelected, 
                                     const int numUnalignedBases, 
                                     const BlxContext *bc,
                                     int *result_out)
{
  gboolean success = FALSE;
  int result = UNSET_INT;
  
  /* First convert to display coords */
  const int frame = mspGetRefFrame(msp, bc->seqType);
  const int displayIdx = convertDnaIdxToDisplayIdx(qIdx, bc->seqType, frame, bc->numFrames, bc->displayRev, &bc->refSeqRange, NULL);
  const IntRange* const mspRange = mspGetDisplayRange(msp);

  /* Note that because we have converted to display coords the ref seq coords are
   * now in the direction of the display, regardless of the ref seq strand. */
  const gboolean sameDirection = (mspGetMatchStrand(msp) == mspGetRefStrand(msp));
  const gboolean sForward = (sameDirection != bc->displayRev);
  
  if (displayIdx < mspRange->min())
    {
      /* Find the offset backwards from the low coord and subtract it from the low end
       * of the s coord range (or add it to the high end, if the directions are opposite).
       * We're working in display coords here. */
      const int offset = mspRange->min() - displayIdx;
      result = sForward ? msp->sRange.min() - offset : msp->sRange.max() + offset;
      success = TRUE;
    }
  else
    {
      /* Find the offset forwards from the high coord and add it to the high end of the
       * s coord range (or subtract it from the low end, if the directions are opposite). */
      const int offset = displayIdx - mspRange->max();
      result = sForward ? msp->sRange.max() + offset : msp->sRange.min() - offset;
      success = TRUE;
    }
  
  /* Get the full display range of the match sequence. If the result is still out of range
   * then there's nothing to show for this qIdx. */
  const IntRange *fullSRange = mspGetFullSRange(msp, seqSelected, bc);
  
  if (!valueWithinRange(result, fullSRange))
    {
      result = UNSET_INT;
      success = FALSE;
    }
  
  if (success && result_out)
    *result_out = result;

  return success;
}



/* Given a base index on the reference sequence, find the corresonding base 
 * in the match sequence. Returns TRUE and sets the result if successful. */
gboolean mspGetMatchCoord(const MSP *msp, 
                          const int qIdx, 
                          const gboolean seqSelected,
                          const int numUnalignedBases,
                          BlxContext *bc,
                          int *result_out)
{
  gboolean success = FALSE;
  
  if (mspIsBlastMatch(msp) || mspIsBoxFeature(msp))
    {
      const gboolean inMspRange = valueWithinRange(qIdx, &msp->qRange);
      
      if (msp->gaps && g_slist_length(msp->gaps) >= 1 && inMspRange)
        {
          success = mspGetGappedAlignmentCoord(msp, qIdx, bc, result_out);
        }
      else if (!inMspRange && mspIsBlastMatch(msp))
        {
          /* The q index is outside the alignment range but if the option to show
           * unaligned sequence is enabled we may still have a valie result. */
          success = mspGetUnalignedCoord(msp, qIdx, seqSelected, numUnalignedBases, bc, result_out);
        }
      else
        {
          success = mspGetUngappedAlignmentCoord(msp, qIdx, bc, result_out);
        }
    }
  
  return success;
}



/***********************************************************
 *               General
 ***********************************************************/

/* Redraw the entire blixem window. (Call blxWindowRedrawAll directly where possible,
 * rather than this function, which relies on the global variable 'blixemWindow'). */
void blviewRedraw(void)
{
  if (blixemWindow)
    {
      blxWindowRedrawAll(blixemWindow);
    }
}

GtkWidget* getBlixemWindow()
{
  return blixemWindow;
}


/* Reset any global variables / singleton instances */
void blviewResetGlobals()
{
  blixemWindow = NULL;
  destroyMessageList();
}

/***********************************************************
 *               Styles and colours
 ***********************************************************/

/* Set the given BlxColor elements from the given color string(s). Works out some good defaults
 * for blxColor.selected blxcolor.print etc if these colors are not given */
static void setBlxColorValues(const char *normal, const char *selected, BlxColor *blxColor, GError **error)
{
  GError *tmpError = NULL;
  
  if (normal)
    {
      getColorFromString(normal, &blxColor->normal, &tmpError);

      if (!tmpError)
        {
          getSelectionColor(&blxColor->normal, &blxColor->selected); /* will use this if selection color is not given/has error */
          
          /* Calculate print coords as a greyscale version of normal colors */
          convertToGrayscale(&blxColor->normal, &blxColor->print);            /* calculate print colors, because they are not given */
          getSelectionColor(&blxColor->print, &blxColor->printSelected);
        }

      /* Treat white as transparent. Not ideal but blixem can read zmap styles
       * files where this assumption is made */
      blxColor->transparent = (!strncasecmp(normal, "white", 5) || !strncasecmp(normal, "#ffffff", 7));
    }
  else
    {
      blxColor->transparent = TRUE;
    }

  /* Use the selected-color string, if given */
  if (!tmpError && selected)
    {
      getColorFromString(selected, &blxColor->selected, &tmpError);
    }
  
  if (tmpError)
    g_propagate_error(error, tmpError);
}


/* Create a BlxStyle. For transcripts, CDS and UTR features can have different colors, but they
 * are from the same source and hence have the same style object. We therefore use the default
 * fillColor, lineColor etc. variables for CDS features and provide additional options to supply 
 * UTR colors as well. */
BlxStyle* createBlxStyle(const char *styleName, 
			 const char *fillColor, 
			 const char *fillColorSelected, 
			 const char *lineColor, 
			 const char *lineColorSelected, 
			 const char *fillColorUtr, 
			 const char *fillColorUtrSelected, 
			 const char *lineColorUtr, 
			 const char *lineColorUtrSelected, 
			 GError **error)
{
  BlxStyle *style = new BlxStyle;
  GError *tmpError = NULL;

  if (!styleName)
    {
      g_set_error(error, BLX_ERROR, 1, "Style name is NULL.\n");
    }
    
  if (!tmpError)
    {
      style->styleName = g_strdup(styleName);
    }
  
  if (!tmpError)
    {      
      setBlxColorValues(fillColor ? fillColor : fillColorUtr,
                        fillColorSelected ? fillColorSelected : fillColorUtrSelected,
                        &style->fillColor, &tmpError);
    }
  
  if (!tmpError)
    {
      setBlxColorValues(lineColor ? lineColor : lineColorUtr,
                        lineColorSelected ? lineColorSelected : lineColorUtrSelected,
                        &style->lineColor, &tmpError);
    }
  
  if (!tmpError)
    {
      setBlxColorValues(fillColorUtr ? fillColorUtr : fillColor,
                        fillColorUtrSelected ? fillColorUtrSelected : fillColorSelected,
                        &style->fillColorUtr, &tmpError);
    }

  if (!tmpError)
    {
      setBlxColorValues(lineColorUtr ? lineColorUtr : lineColor,
                        lineColorUtrSelected ? lineColorUtrSelected : lineColorSelected,
                        &style->lineColorUtr, &tmpError);
    }

  if (tmpError)
    {
      delete style;
      style = NULL;
      g_propagate_error(error, tmpError);
    }
  
  return style;
}


/* Destroy a BlxStyle */
void destroyBlxStyle(BlxStyle *style)
{
  if (style)
    {
      g_free(style->styleName);
    }
}


/* This function highlights any regions within the given display range that
 * are assembly gaps (which are BLXMSP_GAP type MSPs in the given MSP array).
 * The given rect defines the drawing area on the given drawable that corresponds
 * to the given display range. Gaps that lie within the display range are drawn
 * within the rect at the appropriate positions. */
void drawAssemblyGaps(GtkWidget *widget,
                      GdkDrawable *drawable,
                      GdkColor *color,
                      const gboolean displayRev,
                      GdkRectangle *rect, 
                      const IntRange* const dnaRange,
                      const GArray *mspArray)
{
  /* See if any gaps lie within the display range. */
  int i = 0;
  MSP *gap = mspArrayIdx(mspArray, i);
  
  for ( ; gap; gap = mspArrayIdx(mspArray, ++i))
    {
      if (rangesOverlap(&gap->qRange, dnaRange))
        {
	  /* Draw to max coord plus one (or min coord minus one if reversed) to be inclusive */
          const int gapMin = gap->qRange.min(true, displayRev);
          const int gapMax = gap->qRange.max(true, displayRev);

	  const int x1 = convertBaseIdxToRectPos(gapMin, rect, dnaRange, TRUE, displayRev, TRUE);
	  const int x2 = convertBaseIdxToRectPos(gapMax, rect, dnaRange, TRUE, displayRev, TRUE);
          
	  const int width = max(MIN_GAP_HIGHLIGHT_WIDTH, abs(x2 - x1));
	
          cairo_t *cr = gdk_cairo_create(drawable);
          gdk_cairo_set_source_color(cr, color);
          cairo_rectangle(cr, min(x1, x2), 0, width, widget->allocation.height);
          cairo_clip(cr);
          cairo_paint_with_alpha(cr, 0.1);
          cairo_destroy(cr);
        }
    }
  
}


/* Get the color strings for the given group from the given 
 * styles file. If the string is not found then recurse
 * through any parent styles */
static void getStylesFileColorsRecursive(GKeyFile *keyFile,
                                         const char *group,
                                         BlxStyleColors *colors,
                                         GError **error)
{
  /* Loop through the normal colors, if we still need to find any */
  if (!colors->fillColor || !colors->lineColor ||
      !colors->fillColorSelected || !colors->lineColorSelected)
    {
      char **normalColors = g_key_file_get_string_list(keyFile, group, "colours", NULL, NULL);
      char **color = normalColors;
      
      if (normalColors)
        colors->normalFound = TRUE;
      
      for ( ; color && *color; ++color)
        {
          /* Ignore leading whitespace */
          char *c = *color;
          while (*c == ' ')
            ++c;
          
          if (c && *c)
            {
              if (!strncasecmp(c, "normal fill ", 12))
                {
                  if (!colors->fillColor) 
                    colors->fillColor = g_strchug(g_strchomp(g_strdup(c + 12)));
                }
              else if (!strncasecmp(c, "normal border ", 14))
                {
                  if (!colors->lineColor)
                    colors->lineColor = g_strchug(g_strchomp(g_strdup(c + 14)));
                }
              else if (!strncasecmp(c, "selected fill ", 14))
                {
                  if (!colors->fillColorSelected)
                    colors->fillColorSelected = g_strchug(g_strchomp(g_strdup(c + 14)));
                }
              else if (!strncasecmp(c, "selected border ", 16))
                {
                  if (!colors->lineColorSelected)
                    colors->lineColorSelected = g_strchug(g_strchomp(g_strdup(c + 16)));
                }
              else if (error && *error)
                {
                  postfixError(*error, "  '%s' is not a valid color field\n", c);
                }
              else
                {
                  g_set_error(error, BLX_ERROR, 1, "  '%s' is not a valid color field\n", c);
                }
            }
        }

      if (normalColors)
        g_strfreev(normalColors);
    }

  /* Loop through the CDs colors, if we still need to find any */
  if (!colors->fillColorCds || !colors->lineColorCds ||
      !colors->fillColorCdsSelected || !colors->lineColorCdsSelected)
    {
      char **cdsColors = g_key_file_get_string_list(keyFile, group, "transcript-cds-colours", NULL, NULL);
      char **color = cdsColors;

      if (cdsColors)
        colors->cdsFound = TRUE;

      for ( ; color && *color; ++color)
        {
          /* Ignore leading whitespace */
          char *c = *color;
          while (*c == ' ')
            ++c;
          
          if (c && *c)
            {
              if (!strncasecmp(c, "normal fill ", 12))
                {
                  if (!colors->fillColorCds) 
                    colors->fillColorCds = g_strchug(g_strchomp(g_strdup(c + 12)));
                }
              else if (!strncasecmp(c, "normal border ", 14))
                {
                  if (!colors->lineColorCds)
                    colors->lineColorCds = g_strchug(g_strchomp(g_strdup(c + 14)));
                }
              else if (!strncasecmp(c, "selected fill ", 14))
                {
                  if (!colors->fillColorCdsSelected)
                    colors->fillColorCdsSelected = g_strchug(g_strchomp(g_strdup(c + 14)));
                }
              else if (!strncasecmp(c, "selected border ", 16))
                {
                  if (!colors->lineColorCdsSelected)
                    colors->lineColorCdsSelected = g_strchug(g_strchomp(g_strdup(c + 16)));
                }
              else if (error && *error)
                {
                  postfixError(*error, "  '%s' is not a valid color field\n", c);
                }
              else
                {
                  g_set_error(error, BLX_ERROR, 1, "  '%s' is not a valid color field\n", c);
                }
            }
        }
      
      if (cdsColors)
        g_strfreev(cdsColors);
    }

  /* If there are still any outstanding, recurse to the next parent */
  if (!colors->fillColor || !colors->lineColor || 
      !colors->fillColorSelected || !colors->lineColorSelected || 
      !colors->fillColorCds || !colors->lineColorCds ||
      !colors->fillColorCdsSelected || !colors->lineColorCdsSelected)
    {
      char *parent = g_key_file_get_string(keyFile, group, "parent-style", NULL);
      
      if (parent)
        {
          getStylesFileColorsRecursive(keyFile, parent, colors, error);
          g_free(parent);
        }
    }
}


/* For backwards compatibility, read the old-style color fields
 * for the given source (group) from the given key file. (The 
 * key names were changed to be consistent with zmap). */
static void readStylesFileColorsOld(GKeyFile *keyFile, 
                                    const char *group, 
                                    GSList **stylesList,
                                    GError **error)
{
  char *fillColor = g_key_file_get_string(keyFile, group, "fill_color", NULL);
  char *lineColor = g_key_file_get_string(keyFile, group, "line_color", NULL);
  char *fillColorSelected = g_key_file_get_string(keyFile, group, "fill_color_selected", NULL);
  char *lineColorSelected = g_key_file_get_string(keyFile, group, "line_color_selected", NULL);
  char *fillColorUtr = g_key_file_get_string(keyFile, group, "fill_color_utr", NULL);
  char *lineColorUtr = g_key_file_get_string(keyFile, group, "line_color_utr", NULL);
  char *fillColorUtrSelected = g_key_file_get_string(keyFile, group, "fill_color_utr_selected", NULL);
  char *lineColorUtrSelected = g_key_file_get_string(keyFile, group, "line_color_utr_selected", NULL);
  
  /* If there was an error, skip this group. Otherwise, go ahead and create the style */
  if (fillColor && lineColor)
    {
      BlxStyle *style = createBlxStyle(group, 
                                       fillColor, fillColorSelected,
                                       lineColor, lineColorSelected,
                                       fillColorUtr, fillColorUtrSelected,
                                       lineColorUtr, lineColorUtrSelected,
                                       error);

      if (style)
        *stylesList = g_slist_append(*stylesList, style);
    }
  else if (!fillColor)
    {
      g_set_error(error, BLX_ERROR, 1, "Style '%s' does not contain required field fill_color", group);
    }
  else if (!lineColor)
    {
      g_set_error(error, BLX_ERROR, 1, "Style '%s' does not contain required field line_color", group);
    }
  
  
  if (fillColor) g_free(fillColor);
  if (lineColor) g_free(lineColor);
  if (fillColorSelected) g_free(fillColorSelected);
  if (lineColorSelected) g_free(lineColorSelected);
  if (fillColorUtr) g_free(fillColorUtr);
  if (lineColorUtr) g_free(lineColorUtr);
  if (fillColorUtrSelected) g_free(fillColorUtrSelected);
  if (lineColorUtrSelected) g_free(lineColorUtrSelected);
}


/* Read the new-style color fields for the given source (group) 
 * from the given key file. Returns true if colors were found. */
static gboolean readStylesFileColors(GKeyFile *keyFile, 
                                     const char *group, 
                                     GSList **stylesList,
                                     GError **error)
{
  gboolean result = FALSE;
  GError *tmpError = NULL;
  g_key_file_set_list_separator(keyFile, ';');

  /* Get the colors from the styles. We may need to recurse through multiple
   * style parents before we find them. */
  BlxStyleColors colors = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, FALSE, FALSE};
  getStylesFileColorsRecursive(keyFile, group, &colors, &tmpError);
  
  /* If colors were found, create the style */
  if (!tmpError && (colors.normalFound || colors.cdsFound))
    {
      /* Unfortunately blixem stores cds/utr colors differently to zmap, which
       * leads to the following messy logic:
       * If the optional cds colors are set then the default 'colors' field 
       * in the styles file gives our utr colors and the 'transcript-cds-colors'
       * field gives our normal colors. Otherwise, the 'colors' field gives our
       * normal colors and we don't set the utr colors (because they default 
       * to the normal colors). */
      BlxStyle *style = NULL;
      
      if (colors.cdsFound)
        {
          style = createBlxStyle(group, 
                                 colors.fillColorCds, colors.fillColorCdsSelected,
                                 colors.lineColorCds, colors.lineColorCdsSelected,
                                 colors.fillColor, colors.fillColorSelected,
                                 colors.lineColor, colors.lineColorSelected,
                                 &tmpError);
        }
      else
        {
          style = createBlxStyle(group, 
                                 colors.fillColor, colors.fillColorSelected,
                                 colors.lineColor, colors.lineColorSelected,
                                 NULL, NULL,
                                 NULL, NULL,
                                 &tmpError);
        }

      if (style)
        *stylesList = g_slist_append(*stylesList, style);

      if (tmpError)
        prefixError(tmpError, "  "); /* indent the error message */
    }
  
  /* Clean up */
  if (colors.fillColor) g_free(colors.fillColor);
  if (colors.lineColor) g_free(colors.lineColor);
  if (colors.fillColorSelected) g_free(colors.fillColorSelected);
  if (colors.lineColorSelected) g_free(colors.lineColorSelected);
  if (colors.fillColorCds) g_free(colors.fillColorCds);
  if (colors.lineColorCds) g_free(colors.lineColorCds);
  if (colors.fillColorCdsSelected) g_free(colors.fillColorCdsSelected);
  if (colors.lineColorCdsSelected) g_free(colors.lineColorCdsSelected);

  /* Error handling */
  if (tmpError)
    g_propagate_error(error, tmpError);

  return result;
}


/* Read in the styles file. Returns a list of style structs for each style
 * found. Uses the given key file if specified, otherwise checks to see
 * if there is a key file specified in the config file. */
GSList* blxReadStylesFile(const char *keyFileName_in, GError **error)
{
  GSList *result = NULL;

  char *keyFileName = NULL;

  if (keyFileName_in)
    {
      keyFileName = g_strdup(keyFileName_in);
    }
  else
    {
      /* See if the styles file is specified in the config */
      GKeyFile *keyFile = blxGetConfig();

      if (keyFile)
        keyFileName = g_key_file_get_string(keyFile, BLIXEM_GROUP, STYLES_FILE_KEY, NULL);
    }
  
  if (!keyFileName)
    {
      return result;
    }
  
  /* Load the key file */
  GKeyFile *keyFile = g_key_file_new();
  GKeyFileFlags flags = G_KEY_FILE_NONE ;

  if (g_key_file_load_from_file(keyFile, keyFileName, flags, error))
    {
      /* Get all the groups (i.e. style names) from the file */
      gsize num_groups;
      char **groups = g_key_file_get_groups(keyFile, &num_groups) ;

      /* Loop through each style */
      char **group;
      int i;
      GError *tmpError = NULL;
      
      for (i = 0, group = groups ; i < (int)num_groups ; i++, group++)
	{
          gboolean found = readStylesFileColors(keyFile, *group, &result, &tmpError);

          /* If it wasn't found, look for old-style colors */
          if (!found && !tmpError)
            readStylesFileColorsOld(keyFile, *group, &result, NULL);

          if (tmpError)
            {
              /* Compile all errors into one */
              prefixError(tmpError, "[%s]\n", *group);
              
              if (error && *error)
                postfixError(*error, "%s", tmpError->message);
              else
                g_set_error(error, BLX_ERROR, 1, "%s", tmpError->message);

              g_error_free(tmpError);
              tmpError = NULL;
            }
        }
      
      if (tmpError)
        {          
          g_propagate_error(error, tmpError);
        }
      
      g_strfreev(groups);
    }
  
  if (error && *error)
    {
      prefixError(*error, "Errors found while reading styles file '%s'\n", keyFileName);
      postfixError(*error, "\n");
    }

  g_free(keyFileName);
  g_key_file_free(keyFile) ;
  keyFile = NULL ;
  
  return result;
}


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

/* Returns a string which is the name of the Blixem application. */
const char *blxGetAppName()
{
  return BLIXEM_TITLE ;
}

/* Returns a string which is used to prefix window titles (full or abbrev
 * depending on settings). */
const char *blxGetTitlePrefix(const BlxContext * const bc)
{
  return bc->flags[BLXFLAG_ABBREV_TITLE] ? BLIXEM_PREFIX_ABBREV : BLIXEM_PREFIX ;
}

/* Returns a copyright string for the Blixem application. */
const char *blxGetCopyrightString()
{
  return BLIXEM_COPYRIGHT_STRING ;
}

/* Returns the Blixem website URL. */
const char *blxGetWebSiteString()
{
  return BLIXEM_WEBSITE_STRING ;
}

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

  return result;
}

/* Returns a license string for the blx application. */
const char *blxGetLicenseString()
{
  return BLIXEM_LICENSE_STRING ;
}

/* Returns a string representing the Version/Release/Update of the Blixem code. */
const char *blxGetVersionString()
{
  return BLIXEM_VERSION_STRING ;
}


/***********************************************************
 *                      Columns
 ***********************************************************/

/* Check if the column has a column-width set in the config and if so override the default value */
static void getColumnWidthsConfig(BlxColumnInfo *columnInfo)
{
  /* Do nothing for the sequence column, because it has dynamic width */
  if (columnInfo->columnId == BLXCOL_SEQUENCE)
    return;
    
  GKeyFile *key_file = blxGetConfig();
  GError *error = NULL;

  if (key_file && g_key_file_has_group(key_file, COLUMN_WIDTHS_GROUP) && g_key_file_has_key(key_file, COLUMN_WIDTHS_GROUP, columnInfo->title, &error))
    {
      if (!error)
        {
          const int newWidth = g_key_file_get_integer(key_file, COLUMN_WIDTHS_GROUP, columnInfo->title, &error);
          
          if (error)
            {
              reportAndClearIfError(&error, G_LOG_LEVEL_CRITICAL);
            }
          else if (newWidth > 0)
            {
              columnInfo->width = newWidth;
              columnInfo->showColumn = TRUE;
            }
          else
            {
              columnInfo->showColumn = FALSE;
            }
        }
    }
}


/* Check if the column has a column-summary flag set in the config and if so 
 * override the default value */
static void getColumnSummaryConfig(BlxColumnInfo *columnInfo)
{
  /* Do nothing if we can't show the summary for this column */
  if (!columnInfo->canShowSummary)
    return;
    
  GKeyFile *key_file = blxGetConfig();

  if (key_file && g_key_file_has_group(key_file, COLUMN_SUMMARY_GROUP))
    {
      /* The value is true if we should include the column in summary info, false if we should
       * not. If the group exists but the column is not listed then that also indicates we should not
       * show it (this call will correctly return false in that case). */
      columnInfo->showSummary = g_key_file_get_boolean(key_file, COLUMN_SUMMARY_GROUP, columnInfo->title, NULL);
    }
}


/* This checks if the column has any properties specified for it in the config
 * file and, if so, overrides the default values in the given column with 
 * the config file values. */
static void getColumnConfig(BlxColumnInfo *columnInfo)
{
  getColumnWidthsConfig(columnInfo);
  getColumnSummaryConfig(columnInfo);
}

//static void destroyColumnList(GList **columnList)
//{
//  GList *column = *columnList;
//  
//  for ( ; column; column = column->next)
//    {
//      g_free(column->data);
//    }
//    
//  g_list_free(*columnList);
//  *columnList = NULL;
//}


/* This creates BlxColumnInfo entries for each column required in the detail view. It
 * returns a list of the columns created. */
GList* blxCreateColumns(const gboolean optionalColumns, const gboolean customSeqHeader)
{
  GList *columnList = NULL;
  
  /* Create the columns' data structs. The columns appear in the order
   * that they are added here. */
  blxColumnCreate(BLXCOL_SEQNAME,     TRUE,             "Name",       G_TYPE_STRING, RENDERER_TEXT_PROPERTY,     BLXCOL_SEQNAME_WIDTH,        TRUE,            TRUE,  TRUE,  TRUE,  TRUE,   "Name",        NULL, NULL, &columnList);
  blxColumnCreate(BLXCOL_SOURCE,      TRUE,             "Source",     G_TYPE_STRING, RENDERER_TEXT_PROPERTY,     BLXCOL_SOURCE_WIDTH,         TRUE,            TRUE,  TRUE,  TRUE,  TRUE,   "Source",      NULL, NULL, &columnList);
                                                                                                                                                                                                              
  blxColumnCreate(BLXCOL_ORGANISM,    TRUE,             "Organism",   G_TYPE_STRING, RENDERER_TEXT_PROPERTY,     BLXCOL_ORGANISM_WIDTH,       optionalColumns, TRUE,  TRUE,  TRUE,  TRUE,   "Organism",    "OS", NULL, &columnList);
  blxColumnCreate(BLXCOL_GENE_NAME,   TRUE,             "Gene Name",  G_TYPE_STRING, RENDERER_TEXT_PROPERTY,     BLXCOL_GENE_NAME_WIDTH,      optionalColumns, FALSE, TRUE,  TRUE,  TRUE,   "Gene name",   "GN", NULL, &columnList);
  blxColumnCreate(BLXCOL_TISSUE_TYPE, TRUE,             "Tissue Type",G_TYPE_STRING, RENDERER_TEXT_PROPERTY,     BLXCOL_TISSUE_TYPE_WIDTH,    optionalColumns, FALSE, TRUE,  TRUE,  TRUE,   "Tissue type", "FT", "tissue_type", &columnList);
  blxColumnCreate(BLXCOL_STRAIN,      TRUE,             "Strain",     G_TYPE_STRING, RENDERER_TEXT_PROPERTY,     BLXCOL_STRAIN_WIDTH,         optionalColumns, FALSE, TRUE,  TRUE,  TRUE,   "Strain",      "FT", "strain", &columnList);
                                                                                                                                                                             
  /* Insert optional columns here, with a dynamically-created IDs that are >= BLXCOL_NUM_COLS */                                                                             
  int columnId = BLXCOL_NUM_COLUMNS;                                                                                                                                         
  blxColumnCreate((BlxColumnId)columnId++, TRUE,        "Description",G_TYPE_STRING, RENDERER_TEXT_PROPERTY,     BLXCOL_DEFAULT_WIDTH,        optionalColumns, FALSE, TRUE,  TRUE,  TRUE,   "Description", "DE", NULL, &columnList);
                                                                                                                                                                                                             
  blxColumnCreate(BLXCOL_GROUP,       TRUE,             "Group",      G_TYPE_STRING, RENDERER_TEXT_PROPERTY,     BLXCOL_GROUP_WIDTH,          TRUE,            FALSE, FALSE, FALSE, TRUE,   "Group",       NULL, NULL, &columnList);
  blxColumnCreate(BLXCOL_SCORE,       TRUE,             "Score",      G_TYPE_DOUBLE, RENDERER_TEXT_PROPERTY,     BLXCOL_SCORE_WIDTH,          TRUE,            TRUE,  FALSE, FALSE, FALSE,  "Score",       NULL, NULL, &columnList);
  blxColumnCreate(BLXCOL_ID,          TRUE,             "%Id",        G_TYPE_DOUBLE, RENDERER_TEXT_PROPERTY,     BLXCOL_ID_WIDTH,             TRUE,            TRUE,  FALSE, FALSE, FALSE,  "Identity",    NULL, NULL, &columnList);
  blxColumnCreate(BLXCOL_START,       TRUE,             "Start",      G_TYPE_INT,    RENDERER_TEXT_PROPERTY,     BLXCOL_START_WIDTH,          TRUE,            TRUE,  FALSE, FALSE, FALSE,  "Position",    NULL, NULL, &columnList);
  blxColumnCreate(BLXCOL_SEQUENCE,    !customSeqHeader, "Sequence",   G_TYPE_POINTER,RENDERER_SEQUENCE_PROPERTY, BLXCOL_SEQUENCE_WIDTH,       TRUE,            TRUE,  FALSE, FALSE, FALSE,  NULL,          "SQ", NULL, &columnList);
  blxColumnCreate(BLXCOL_END,         TRUE,             "End",        G_TYPE_INT,    RENDERER_TEXT_PROPERTY,     BLXCOL_END_WIDTH,            TRUE,            TRUE,  FALSE, FALSE, FALSE,  NULL,          NULL, NULL, &columnList);

  /* For each column, check if it is configured in the config file and if so update accordingly */
  GList *columnItem  = columnList;

  for ( ; columnItem; columnItem = columnItem->next)
    {
      BlxColumnInfo *columnInfo = (BlxColumnInfo*)(columnItem->data);
      getColumnConfig(columnInfo);
    }

  return columnList;
}


/* Return the width of the column with the given column id */
int getColumnWidth(const GList *columnList, const BlxColumnId columnId)
{
  int result = 0;

  BlxColumnInfo *columnInfo = getColumnInfo(columnList, columnId);

  if (columnInfo)
    {
      result = columnInfo->width;
    }
  
  return result;
}


/* Return the width of the column with the given column id */
const char* getColumnTitle(const GList *columnList, const BlxColumnId columnId)
{
  const char *result = NULL;
  
  BlxColumnInfo *columnInfo = getColumnInfo(columnList, columnId);

  if (columnInfo)
    {
      result = columnInfo->title;
    }
  
  return result;
}


/* Gets the x coords at the start/end of the given column and populate them into the range
 * return argument. */
void getColumnXCoords(const GList *columnList, const BlxColumnId columnId, IntRange *xRange)
{
  xRange->set(0, 0);
  
  /* Loop through all visible columns up to the given column, summing their widths. */
  const GList *columnItem = columnList;
  
  for ( ; columnItem; columnItem = columnItem->next)
    {
      BlxColumnInfo *columnInfo = (BlxColumnInfo*)(columnItem->data);
      
      if (columnInfo->columnId != columnId)
        {
          if (showColumn(columnInfo))
            xRange->setMin(xRange->min() + columnInfo->width);
        }
      else
        {
          /* We've got to the required column. Calculate the x coord at the end
           * of this column and then break. */
          if (showColumn(columnInfo))
            xRange->setMax(xRange->min() + columnInfo->width);
          else
            xRange->setMax(xRange->min()); /* return zero-width if column is not visible */
          
          break;
        }
    }
}


/* Returns true if the given column should be visible */
gboolean showColumn(BlxColumnInfo *columnInfo)
{
  return (columnInfo->showColumn && columnInfo->dataLoaded && columnInfo->width > 0);
}


/* Save the column widths to the given config file. */
void saveColumnWidths(GList *columnList, GKeyFile *key_file)
{
  /* Loop through each column */
  GList *listItem = columnList;
  
  for ( ; listItem; listItem = listItem->next)
    {
      BlxColumnInfo *columnInfo = (BlxColumnInfo*)(listItem->data);

      if (columnInfo && columnInfo->columnId != BLXCOL_SEQUENCE)
        {
          /* If column is not visible, set width to zero to indicate that it should be hidden */
          if (columnInfo->showColumn)
            g_key_file_set_integer(key_file, COLUMN_WIDTHS_GROUP, columnInfo->title, columnInfo->width);
          else
            g_key_file_set_integer(key_file, COLUMN_WIDTHS_GROUP, columnInfo->title, 0);
        }
    }
}


/* Save the summary columns to the given config file. */
void saveSummaryColumns(GList *columnList, GKeyFile *key_file)
{
  /* Loop through each column */
  GList *listItem = columnList;
  
  for ( ; listItem; listItem = listItem->next)
    {
      BlxColumnInfo *columnInfo = (BlxColumnInfo*)(listItem->data);

      if (columnInfo && columnInfo->canShowSummary)
        {
          g_key_file_set_boolean(key_file, COLUMN_SUMMARY_GROUP, columnInfo->title, columnInfo->showSummary);
        }
    }
}


/* Reset column widths to default values */
void resetColumnWidths(GList *columnList)
{
  /* Quick and dirty: just set the width and visibility manually. This should be
   * done differently so we can just loop through and find the correct values somehow;
   * currently we run the risk of getting out of sync with the initial values set in
   * blxCreateColumns */
  getColumnInfo(columnList, BLXCOL_SEQNAME)->width = BLXCOL_SEQNAME_WIDTH;
  getColumnInfo(columnList, BLXCOL_SEQNAME)->showColumn = TRUE;

  getColumnInfo(columnList, BLXCOL_SCORE)->width = BLXCOL_SCORE_WIDTH;
  getColumnInfo(columnList, BLXCOL_SCORE)->showColumn = TRUE;

  getColumnInfo(columnList, BLXCOL_ID)->width = BLXCOL_ID_WIDTH;
  getColumnInfo(columnList, BLXCOL_ID)->showColumn = TRUE;

  getColumnInfo(columnList, BLXCOL_START)->width = BLXCOL_START_WIDTH;
  getColumnInfo(columnList, BLXCOL_START)->showColumn = TRUE;

  getColumnInfo(columnList, BLXCOL_SEQUENCE)->width = BLXCOL_SEQUENCE_WIDTH;
  getColumnInfo(columnList, BLXCOL_SEQUENCE)->showColumn = TRUE;

  getColumnInfo(columnList, BLXCOL_END)->width = BLXCOL_END_WIDTH;
  getColumnInfo(columnList, BLXCOL_END)->showColumn = TRUE;

  getColumnInfo(columnList, BLXCOL_SOURCE)->width = BLXCOL_SOURCE_WIDTH;
  getColumnInfo(columnList, BLXCOL_SOURCE)->showColumn = TRUE;

  getColumnInfo(columnList, BLXCOL_GROUP)->width = BLXCOL_GROUP_WIDTH;
  getColumnInfo(columnList, BLXCOL_GROUP)->showColumn = FALSE;

  getColumnInfo(columnList, BLXCOL_ORGANISM)->width = BLXCOL_ORGANISM_WIDTH;
  getColumnInfo(columnList, BLXCOL_ORGANISM)->showColumn = TRUE;

  getColumnInfo(columnList, BLXCOL_GENE_NAME)->width = BLXCOL_GENE_NAME_WIDTH;
  getColumnInfo(columnList, BLXCOL_GENE_NAME)->showColumn = FALSE;

  getColumnInfo(columnList, BLXCOL_TISSUE_TYPE)->width = BLXCOL_TISSUE_TYPE_WIDTH;
  getColumnInfo(columnList, BLXCOL_TISSUE_TYPE)->showColumn = FALSE;

  getColumnInfo(columnList, BLXCOL_STRAIN)->width = BLXCOL_STRAIN_WIDTH;
  getColumnInfo(columnList, BLXCOL_STRAIN)->showColumn = FALSE;

}



/***************** end of file ***********************/