File: puzzle2.c

package info (click to toggle)
tree-puzzle 5.2-11
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 4,376 kB
  • sloc: ansic: 45,111; sh: 3,366; makefile: 243
file content (1850 lines) | stat: -rw-r--r-- 54,266 bytes parent folder | download
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
/*
 * puzzle2.c
 *
 *
 * Part of TREE-PUZZLE 5.2 (July 2004)
 *
 * (c) 2003-2004 by Heiko A. Schmidt, Korbinian Strimmer, and Arndt von Haeseler
 * (c) 1999-2003 by Heiko A. Schmidt, Korbinian Strimmer,
 *                  M. Vingron, and Arndt von Haeseler
 * (c) 1995-1999 by Korbinian Strimmer and Arndt von Haeseler
 *
 * All parts of the source except where indicated are distributed under
 * the GNU public licence.  See http://www.opensource.org for details.
 *
 * ($Id$)
 *
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif


#define EXTERN extern

#include "puzzle.h"
#include <string.h>

#if PARALLEL
#	include "ppuzzle.h"
#	include "sched.h"
#endif /* PARALLEL */


/******************************************************************************/
/* sequences                                                                  */
/******************************************************************************/

/* read ten characters of current line as identifier */
void readid(FILE *infp, int t)
{
	int i, j, flag, ci;

	for (i = 0; i < 10; i++) {
		ci = fgetc(infp);
		if (ci == EOF || !isprint(ci)) {
			fprintf(STDOUT, "\n\n\nUnable to proceed (no name for sequence %d)\n\n\n", t+1);
#			if PARALLEL
				PP_Finalize();
#			endif
			exit(1);
		}
		Identif[t][i] = (char) ci;
	}	
	/* convert leading blanks in taxon name to underscores */
	flag = FALSE;
	for (i = 9; i > -1; i--) {
		if (flag == FALSE) {
			if (Identif[t][i] != ' ') flag = TRUE; 
		} else {
			if (Identif[t][i] == ' ') Identif[t][i] = '_';
		}
	}
	/* check whether this name is already used */
	for (i = 0; i < t; i++) { /* compare with all other taxa */
		flag = TRUE; /* assume identity */
		for (j = 0; (j < 10) && (flag == TRUE); j++)
			if (Identif[t][j] != Identif[i][j])
				flag = FALSE;
		if (flag) {
			fprintf(STDOUT, "\n\n\nUnable to proceed (multiple occurrence of sequence name '");
			fputid(STDOUT, t);
			fprintf(STDOUT, "')\n\n\n");
#			if PARALLEL
				PP_Finalize();
#			endif
			exit(1);
		}
	}
} /* readid */

/******************/


/* read next allowed character */
char readnextcharacter(FILE *ifp, int notu, int nsite)
{
	char c;

	/* ignore blanks and control characters except newline (UNIX,DOS) or CR (Mac,DOS) */
	do {
		if (fscanf(ifp, "%c", &c) != 1) {
			fprintf(STDOUT, "\n\n\nUnable to proceed (missing character at position %d in sequence '", nsite + 1);
			fputid(STDOUT, notu);
			fprintf(STDOUT, "')\n\n\n");
#			if PARALLEL
				PP_Finalize();
#			endif
			exit(1);
		}
	} while (c == ' ' || (iscntrl((int) c) && (c != '\n') && (c != '\r')));
	return c;
} /* readnextcharacter */

/******************/


/* skip rest of the line */
void skiprestofline(FILE *ifp,    /* input file stream */
                    int   notu,   /* taxon number      - for error msg. */
                    int   nsite)  /* sequence position - for error msg. */
{
	int ci;

	/* read chars until the first newline or CR */
	do{
		ci = fgetc(ifp);
		if (ci == EOF) {
			fprintf(STDOUT, "Unable to proceed (missing newline at position %d in sequence '", nsite + 1);
			fputid(STDOUT, notu);
			fprintf(STDOUT, "')\n\n\n");
#			if PARALLEL
				PP_Finalize();
#			endif
			exit(1);
		}
	} while (((char) ci != '\n') && ((char) ci != '\r'));
} /* skiprestofline */

/******************/


/* skip control characters and blanks */
void skipcntrl(FILE *ifp,    /* input file stream */
               int   notu,   /* taxon number      - for error msg. */
               int   nsite)  /* sequence position - for error msg. */
{
	int ci;

	/* read over all control characters and blanks */
	do {
		ci = fgetc(ifp);
		if (ci == EOF) {
			fprintf(STDOUT, "\n\n\nUnable to proceed (missing character at position %d in sequence '", nsite + 1);
			fputid(STDOUT, notu);
			fprintf(STDOUT, "')\n\n\n");
#			if PARALLEL
				PP_Finalize();
#			endif
			exit(1);
		}
	} while (iscntrl(ci) || (char) ci == ' ');
	/* go one character back */
	if (ungetc(ci, ifp) == EOF) {
		fprintf(STDOUT, "\n\n\nUnable to proceed (positioning error at position %d in sequence '", nsite + 1);
		fputid(STDOUT, notu);
		fprintf(STDOUT, "')\n\n\n");
#		if PARALLEL
			PP_Finalize();
#		endif
		exit(1);
	}
} /* skipcntrl */

/******************/


/* read sequences of one data set */
void getseqs(FILE    *ifp,      /* in:  input file stream */
             int      Maxspc,   /* in:  number of taxa */
             int      Maxseqc,  /* in:  number of sites */
             cmatrix *seqch,    /* out: alignment matrix */
             cmatrix  identif)  /* io:  taxon names (10 char w/o stop) */
{
	int notu, nsite, endofline, linelength, i;
	char c;
	cmatrix seqchars;
	
	seqchars = new_cmatrix(Maxspc, Maxseqc);
	/* read all characters */
	nsite = 0; /* next site to be read */
	while (nsite < Maxseqc) {
		/* read first taxon */
		notu = 0;

		/* only Maxspc, Maxseqc read so far: */
		/* go to next true line */
		skiprestofline(ifp, notu, nsite); 

		skipcntrl(ifp, notu, nsite);

		if (nsite == 0) readid(ifp, notu);
		endofline = FALSE;
		linelength = 0;		
		do {
			c = readnextcharacter(ifp, notu, nsite + linelength);
			if ((c == '\n') || (c == '\r')) endofline = TRUE;
			else if (c == '.') {
				fprintf(STDOUT, "\n\n\nUnable to proceed (invalid character '.' at position ");
				fprintf(STDOUT, "%d in first sequence)\n\n\n", nsite + linelength + 1);
#				if PARALLEL
					PP_Finalize();
#				endif
				exit(1);
			     } else if (nsite + linelength < Maxseqc) {
				       /* change to upper case */
				       seqchars[notu][nsite + linelength] = (char) toupper((int) c);
				       linelength++;
			            } else {
				       endofline = TRUE;
				       skiprestofline(ifp, notu, nsite + linelength);
			            }
		} while (!endofline);	
		if (linelength == 0) {
			fprintf(STDOUT, "\n\n\nUnable to proceed (line with length 0 at position %d in sequence '", nsite + 1);
			fputid(STDOUT, notu);
			fprintf(STDOUT, "')\n\n\n");
#			if PARALLEL
				PP_Finalize();
#			endif
			exit(1);
		}
		/* read other taxa */
		for (notu = 1; notu < Maxspc; notu++) {
			/* go to next true line */
			if (notu != 1) skiprestofline(ifp, notu, nsite);
			skipcntrl(ifp, notu, nsite);
			if (nsite == 0) readid(ifp, notu);
			for (i = nsite; i < nsite + linelength; i++) {
				c = readnextcharacter(ifp, notu, i);
				if ((c == '\n') || (c == '\r')) { /* too short */
					fprintf(STDOUT, "\n\n\nUnable to proceed (line to short at position %d in sequence '", i + 1);
					fputid(STDOUT, notu);
					fprintf(STDOUT, "')\n\n\n");
#					if PARALLEL
						PP_Finalize();
#					endif
					exit(1);
				} else if (c == '.') {
					seqchars[notu][i] = seqchars[0][i];
				} else {
					/* change to upper case */
					seqchars[notu][i] = (char) toupper((int) c);
				}
			}
		}
		nsite = nsite + linelength;
	}
	*seqch =seqchars;

} /* getseqs */

/******************/


/* initialize identifer arrays */
void initid(int      t,        /* in:  number of taxa */
            cmatrix *identif,  /* out: name array w/o end of string */
            cmatrix *namestr)  /* out: name array with end of string */
{
	int i, j;

	*identif = new_cmatrix(t, 10);
	*namestr = new_cmatrix(t, 11);
	for (i = 0; i < t; i++) {
		(*namestr)[i][0] = '\0';
		(*namestr)[i][9] = '\0';
		for (j = 0; j < 10; j++) {
			(*identif)[i][j] = ' ';
		} /* for j */
	} /* for i */
} /* initid */

/******************/


/******************/


/* copy undelimited identifer array to '\0' delimited identifer array */
void identif2namestr(int     num,      /* number of taxa         */
                     cmatrix Identif,  /* non-delimited names    */
                     cmatrix Namestr)  /* proper delimited names */
{
	int i, j;
	int laggingspc;

	for (i = 0; i < num; i++) {
		laggingspc = 1;
		for (j = 9; j >= 0; j--) {
			Namestr[i][j] = Identif[i][j];
			if (laggingspc == 1) {
				if (Identif[i][j] != ' ') {
					Namestr[i][j+1] = '\0';
					laggingspc = 0;
				} 
			} 

		} /* for j (letter 10-1) */
	} /* for i (species) */
} /* identif2namestr */

/******************/


/* print identifier of specified taxon in full 10 char length */
void fputid10(FILE *ofp, int t)
{	
	int i;

	for (i = 0; i < 10; i++) fputc(Identif[t][i], ofp);
} /* fputid10 */

/******************/


/* print identifier of specified taxon up to first space */
int fputid(FILE *ofp, int t)
{	
	int i;
	
	i = 0;
	while (i < 10 && Identif[t][i] != ' ') {
		fputc(Identif[t][i], ofp);
		i++;
	}
	return i;
} /* fputid */

/******************/


/* read first line of sequence data set */
void getsizesites(FILE *ifp,      /* in: input file stream */
                  int  *Maxspc,   /* out: number of taxa */
                  int  *Maxseqc)  /* out: number of sites */
{
	if (fscanf(ifp, "%d", Maxspc) != 1) {
			fprintf(STDOUT, "\n\n\nUnable to proceed (missing number of sequences)\n\n\n");
#			if PARALLEL
				PP_Finalize();
#			endif
			exit(1);
	}
	if (fscanf(ifp, "%d", Maxseqc) != 1) {
			fprintf(STDOUT, "\n\n\nUnable to proceed (missing number of sites)\n\n\n");
#			if PARALLEL
				PP_Finalize();
#			endif
			exit(1);
	}
	
	if (*Maxspc < 3) {
		fprintf(STDOUT, "\n\n\nUnable to proceed (less than 3 sequences - no tree possible)\n\n\n");
#		if PARALLEL
			PP_Finalize();
#		endif
		exit(1);
	}
	seqnumcheck = SEQNUM_OK;
	if (*Maxspc < 4) {
		fprintf(STDOUT, "\n\n\nLess than 4 sequences: No quartet methods possible!!!\n\n\n");
		fprintf(STDOUT, "Parameter estimation and tree testing is still possible.\n\n\n");
		seqnumcheck = SEQNUM_TOOFEW;
	}
	if (*Maxspc > 257) {
		fprintf(STDOUT, "\n\n\nMore than 257 sequences: No quartet puzzling available!!!\n");
		fprintf(STDOUT, "Parameter estimation, likelihood mapping, and tree testing is still possible.\n\n\n");
		seqnumcheck = SEQNUM_TOOMANY;
	}
	/* correct default analysis types */
	if ((seqnumcheck!=SEQNUM_OK) && (puzzlemode==QUARTPUZ))
		puzzlemode = (puzzlemode + 1) % NUMPUZZLEMODES;
	if ((seqnumcheck==SEQNUM_TOOFEW) && (typ_optn==LIKMAPING_OPTN))
		typ_optn = (typ_optn + 1) % NUMTYPES;
#if 0
	if (*Maxspc < 4) {
		fprintf(STDOUT, "\n\n\nUnable to proceed (less than 4 sequences)\n\n\n");
#		if PARALLEL
			PP_Finalize();
#		endif
		exit(1);
	}
	if (*Maxspc > 257) {
		fprintf(STDOUT, "\n\n\nUnable to proceed (more than 257 sequences)\n\n\n");
#		if PARALLEL
			PP_Finalize();
#		endif
		exit(1);
	}
#		endif
	if (*Maxseqc < 1) {
		fprintf(STDOUT, "\n\n\nUnable to proceed (no sequence sites)\n\n\n");
#		if PARALLEL
			PP_Finalize();
#		endif
		exit(1);
	}
} /* getsizesites */

/******************/


/* read alignment from file */
void readsequencefile(FILE    *seqfp,     /* in:  sequence input file stream */
                      int     *Maxspc,    /* out: number of taxa             */
                      int     *Maxseqc,   /* out: number of sites            */
                      cmatrix *identif,   /* out: name array w/o end of str  */
                      cmatrix *namestr,   /* out: name array with end of str */
                      cmatrix *Seqchars)  /* out: alignment matrix           */
{
	getsizesites(seqfp, Maxspc, Maxseqc);
	initid(*Maxspc, identif, namestr);
	getseqs(seqfp, *Maxspc, *Maxseqc, Seqchars, *identif);
	identif2namestr(*Maxspc, *identif, *namestr);
} /* readsequencefile */

/******************/


/* read subsets from file */
void readsubsetfile(FILE    *seqfp,              /* in:  sequence input file stream */
                    int      Maxspc,             /* in:  number of taxa             */
                    cmatrix  namestr,            /* in:  names taxa (seq file)      */
                    int     *Maxsubset,          /* out: number of subsets          */
                    imatrix *ss_setovlgraph,     /* out: size of overlap >= 3 between 2 subsets */
                    imatrix *ss_setoverlaps,     /* out: size of overlap between 2 subsets */
                    imatrix *ss_setovllist,      /* out: list with ovlerlapping subsets */
                    ivector *ss_setovllistsize,  /* out: size of list with ovlerlapping subsets */
                    imatrix *ss_matrix,          /* out: boolean list: taxon in set? */
                    imatrix *ss_list,            /* out: list of taxa in set */
                    ivector *ss_listsize)         /* out: size of list with taxa */
{
	int ss_maxspc;
	int n;
	int set1, set2;
	int tmp;

        cmatrix  ss_identarr;
        cmatrix  ss_namearr;
        cmatrix  ss_strmatr;

	/* read the subset file sizes */
	getsizesites(seqfp, &ss_maxspc, Maxsubset);

	/* check sizes */
	if (ss_maxspc != Maxspc) {
		fprintf(STDOUT, "ERROR: Number of taxa in subsetfile does not match!!! (%d != %d)\n", ss_maxspc, Maxspc);
#		if PARALLEL
			PP_SendDone();
			MPI_Finalize();
#		endif /* PARALLEL */
		exit(1);
	}

	/* initialize name arrays for checking */
	initid(ss_maxspc, &ss_identarr, &ss_namearr);

	/* read the data */
	getseqs(seqfp, ss_maxspc, *Maxsubset, &ss_strmatr, ss_identarr);

	/* check the file names */
	identif2namestr(ss_maxspc, ss_identarr, ss_namearr);
	for(n = 0; n<Maxspc; n++) {
		if (ss_maxspc != Maxspc) {
			fprintf(STDOUT, "ERROR: Taxon names or order in subset file do not match!!!\n       (%d \"%s\" != \"%s\")\n", n+1, namestr[n], ss_namearr[n]);
#			if PARALLEL
				PP_SendDone();
				MPI_Finalize();
#			endif /* PARALLEL */
			exit(1);
		}
		
	}

	free_cmatrix(ss_identarr);
	free_cmatrix(ss_namearr);

	*ss_setovlgraph = new_imatrix(*Maxsubset, *Maxsubset);
	*ss_setoverlaps = new_imatrix(*Maxsubset, *Maxsubset);

	*ss_setovllist     = new_imatrix(*Maxsubset, *Maxsubset);
	*ss_setovllistsize = new_ivector(*Maxsubset);

	*ss_matrix         = new_imatrix(*Maxsubset, Maxspc);

	*ss_list           = new_imatrix(*Maxsubset, Maxspc);
	*ss_listsize       = new_ivector(*Maxsubset);

	for (n=0; n<Maxspc; n++) {
		for (set1=0; set1<*Maxsubset; set1++) {
			switch (ss_strmatr[n][set1]) {
				case 'X':
				case '1':
                    			(*ss_matrix)[set1][n] = 1;
                    			(*ss_list)[set1][((*ss_listsize)[set1])++] = n;
					break;
				case '-':
				case '0':
                    			(*ss_matrix)[set1][n] = 0;
					break;
				default:
					fprintf(STDOUT, "ERROR: Unknown character in subset file!!! (\"%c\", taxon %d, site %d)\n", ss_strmatr[n][set1], n+1, set1+1);
#					if PARALLEL
						PP_SendDone();
						MPI_Finalize();
#					endif /* PARALLEL */
					exit(1);
					break;
			}
		}

		for (set1=1; set1<*Maxsubset; set1++) {
			for (set2=0; set2<set1; set2++) {
				if (((*ss_matrix)[set1][n]) && ((*ss_matrix)[set2][n])) 
					/* number of sequences in overlap */
                    			((*ss_setoverlaps)[set1][set2])++;
					
			}
		}
	} /* for Maxspc */

	for (set1=1; set1<*Maxsubset; set1++) {
		for (set2=0; set2<set1; set2++) {
			/* number of sequences in overlap */
                   	tmp = (*ss_setoverlaps)[set1][set2];
                   	(*ss_setoverlaps)[set2][set1] = tmp;
			if (tmp >= 3) {
				/* number of sequences (>=3) in overlap */
                   		(*ss_setovlgraph)[set1][set2] = tmp;
                   		(*ss_setovlgraph)[set2][set1] = tmp;
				/* list of overlapping sets */
                    		(*ss_setovllist)[set1][((*ss_setovllistsize)[set1])++] = set2;
                    		(*ss_setovllist)[set2][((*ss_setovllistsize)[set2])++] = set1;
			}
				
		}
	}
} /* readsubsetfile */

/******************/


/* permute taxon order */
void permutetaxa_ss(int      Maxspc,             /* in:  number of taxa             */
                    ivector  permutation,        /* permuted taxon order            */
                    cmatrix  namestr,            /* in:  names taxa (seq file)      */
                    int      Maxsubset,          /* out: number of subsets          */
                    imatrix  ss_setovlgraph,     /* out: size of overlap >= 3 between 2 subsets */
                    imatrix  ss_setoverlaps,     /* out: size of overlap between 2 subsets */
                    imatrix  ss_setovllist,      /* out: list with ovlerlapping subsets */
                    ivector  ss_setovllistsize,  /* out: size of list with ovlerlapping subsets */
                    imatrix  ss_matrix,          /* out: boolean list: taxon in set? */
                    imatrix  ss_list,            /* out: list of taxa in set */
                    ivector  ss_listsize)         /* out: size of list with taxa */
{
	ivector candidatesetlist;
	int     candidatesetsize = 0;
	ivector candidatetaxalist;
	int     candidatetaxasize = 0;
	ivector taxonstatus;			/* 0 - not done; 1 - candidate; 2 - inserted */
	ivector setstatus;			/* 0 - not used; 1 - front; 2 - used*/
	int     permpos;
	int     k;
	int     tmprand;
	int     currset;
	int     currtaxon;
	candidatesetlist  = new_ivector(Maxsubset);
	candidatetaxalist = new_ivector(Maxspc);
	taxonstatus       = new_ivector(Maxspc);
	setstatus         = new_ivector(Maxsubset);

	/* first subset */
	currset = randominteger(Maxsubset);
	setstatus[currset] = 2; /* inserted */

	/* init subset front nodes */
	/*   insert sets with ovl(currset) >= 3 into candidate set list */
	for (k=0; k<ss_setovllistsize[currset]; k++) {
		candidatesetlist[candidatesetsize] = ss_setovllist[currset][k];
		setstatus[candidatesetlist[candidatesetsize++]] = 1;
	}
	/*   insert taxa from currset into candidate taxon list */
	for (k=0; k<ss_listsize[currset]; k++) {
		candidatetaxalist[candidatetaxasize] = ss_list[currset][k];
		taxonstatus[candidatetaxalist[candidatetaxasize++]] = 1;
	}

	/* start collectin permutation */
	for (permpos=0; permpos<Maxspc; permpos++) {
		/* if no taxa left, choose next set */
		while (candidatetaxasize == 0) {
			/* next set */
			tmprand = randominteger(candidatesetsize);
			currset = candidatesetlist[tmprand];
			/* move last set entry to gap */
			candidatesetlist[tmprand] = candidatesetlist[--candidatesetsize]; /* XXXX */
			/* candidatesetlist[tmprand] = candidatesetlist[candidatesetsize--]; */
			setstatus[currset] = 2; /* inserted */
			/* add new sets (ovl>=3) to set candidate list */
			for (k=0; k<ss_setovllistsize[currset]; k++) {
				if (setstatus[ss_setovllist[currset][k]] == 0) {
					candidatesetlist[candidatesetsize] = ss_setovllist[currset][k];
					setstatus[candidatesetlist[candidatesetsize++]] = 1;
				}
			}
			/* add new taxa to taxon candidate list */
			for (k=0; k<ss_listsize[currset]; k++) {
				if (taxonstatus[ss_list[currset][k]] == 0) {
					candidatetaxalist[candidatetaxasize] = ss_list[currset][k];
					taxonstatus[candidatetaxalist[candidatetaxasize++]] = 1;
				}
			}

		} /* if candidatetaxasize == 0 */

		tmprand = randominteger(candidatetaxasize);
		currtaxon = candidatetaxalist[tmprand];

		candidatetaxalist[tmprand] = candidatetaxalist[--candidatetaxasize];
		permutation[permpos] = currtaxon;
		taxonstatus[currtaxon] = 2;

	} /* one random taxon after the other */
	
	free_ivector(candidatesetlist);
	free_ivector(candidatetaxalist);
	free_ivector(taxonstatus);
	free_ivector(setstatus);
} /* permutetaxa_ss */

/******************/


/* print subsets */
void fprintfss(FILE    *ofp,              /* in:  output file stream         */
             int      Maxspc,             /* in:  number of taxa             */
             int      Maxsubset,          /* out: number of subsets          */
             imatrix  ss_setovlgraph,     /* out: size of overlap >= 3 between 2 subsets */
             imatrix  ss_setoverlaps,     /* out: size of overlap between 2 subsets */
             imatrix  ss_setovllist,      /* out: list with ovlerlapping subsets */
             ivector  ss_setovllistsize,  /* out: size of list with ovlerlapping subsets */
             imatrix  ss_matrix,          /* out: boolean list: taxon in set? */
             imatrix  ss_list,            /* out: list of taxa in set */
             ivector  ss_listsize)         /* out: size of list with taxa */
{
	int     s, s1, s2, t;


	for (s=0; s<Maxsubset; s++) {
		fprintf(ofp, "   set %d (%d taxa)\n", s, ss_listsize[s]);
			fprintf(ofp, "      taxa:        ");
		for (t=0; t<ss_listsize[s]; t++) {
			fprintf(ofp, "%3d", ss_list[s][t]);
			if (t+1 < ss_listsize[s]) fprintf(ofp, ",");
			if (((t+1) % 15) == 0)
				fprintf(ofp, "\n                   ");
		}
		fprintf(ofp, "\n      overlap with:");
		for (t=0; t<ss_setovllistsize[s]; t++) {
			fprintf(ofp, "%3d", ss_setovllist[s][t]);
			if (t+1 < ss_setovllistsize[s]) fprintf(ofp, ",");
			if (((t+1) % 15) == 0)
				fprintf(ofp, "\n                   ");
		}
		fprintf(ofp, "\n\n");
	}
	fprintf(ofp, "   Overlap Graph:\n");
	for (s1=0; s1<Maxsubset; s1++) {
		fprintf(ofp, "   %3d :\t", s1);
		for (s2=0; s2<Maxsubset; s2++) {
			if (s1==s2) 
				fprintf(ofp, "(%3d) ", ss_listsize[s1]);
			else 
				fprintf(ofp, " %3d  ", ss_setoverlaps[s1][s2]);
		}
		fprintf(ofp, "\n");
	}
	fprintf(ofp, "\n\n");
	fflush(ofp);
} /* fprintfss */

/******************/
/* check connectedness of subsets */
void checkss(FILE    *ofp,              /* in:  output file stream         */
             int      Maxspc,             /* in:  number of taxa             */
             int      Maxsubset,          /* out: number of subsets          */
             imatrix  ss_setovlgraph,     /* out: size of overlap >= 3 between 2 subsets */
             imatrix  ss_setoverlaps,     /* out: size of overlap between 2 subsets */
             imatrix  ss_setovllist,      /* out: list with ovlerlapping subsets */
             ivector  ss_setovllistsize,  /* out: size of list with ovlerlapping subsets */
             imatrix  ss_matrix,          /* out: boolean list: taxon in set? */
             imatrix  ss_list,            /* out: list of taxa in set */
             ivector  ss_listsize)         /* out: size of list with taxa */
{
	int     s1, s2;
	int numdone;
        int *setarr;
        setarr = new_ivector(Maxsubset);

	s1 = 0;
	numdone=0;
	do {
		setarr[s1] = 2; /* 1=seen, 2=visited */
		for (s2=0; s2<Maxsubset; s2++) {
			if ((setarr[s2]==0) && (ss_setoverlaps[s1][s2] >= 3))
		  	setarr[s2]=1; 
		}

		numdone++;
		s1=0;
		while ((s1 < Maxsubset) && (setarr[s1]!=1)) s1++;

	} while (s1 != Maxsubset);

	if (Maxsubset != numdone) {
		fprintf(stderr, "Unable to proceed. More than one connected component! (%d != %d)\n", Maxsubset, numdone);
		fprintf(stderr, "visited: \n  ");
		for (s2=0; s2<Maxsubset; s2++) 
			if (setarr[s2]==2) fprintf(stderr, "%d, ", s2);
		fprintf(stderr, "\nseen: \n  ");
		for (s2=0; s2<Maxsubset; s2++) 
			if (setarr[s2]==1) fprintf(stderr, "%d, ", s2);
		fprintf(stderr, "\nlost: \n  ");
		for (s2=0; s2<Maxsubset; s2++) 
			if (setarr[s2]==0) fprintf(stderr, "%d, ", s2);
		exit(1);
	} 
} /* checkss */

/******************/


/* guess data type: NUCLEOTIDE:0, AMINOACID:1, BINARY:2 */
int guessdatatype(cmatrix Seqchars,   /* alignment matrix (Maxspc x Maxseqc) */
                  int     Maxspc,     /* number of taxa */
                  int     Maxseqc)    /* number of sites */
{
	uli numnucs, numchars, numbins;
	int notu, nsite;
	char c;
	
	/* count A, C, G, T, U, N */
	numnucs = 0;
	numchars = 0;
	numbins = 0;
	for (notu = 0; notu < Maxspc; notu++)
		for (nsite = 0; nsite < Maxseqc; nsite++) {
			c = Seqchars[notu][nsite];
			if (c == 'A' || c == 'C' || c == 'G' ||
			    c == 'T' || c == 'U' || c == 'N') numnucs++;
			if (c != '-' && c != '?') numchars++;
			if (c == '0' || c == '1') numbins++;
		}
	if (numchars == 0) numchars = 1;
	/* more than 85 % frequency means nucleotide data */
	if ((double) numnucs / (double) numchars > 0.85) 
		return NUCLEOTIDE; /* 0 */
	else if ((double) numbins / (double) numchars > 0.2) 
		return BINARY; /* 2 */
	else 
		return AMINOACID; /* 1 */
} /* guessdatatype */

/******************/


/* translate characters into format used by ML engine */
void translatedataset(int maxspc, int maxseqc, int *maxsite, cmatrix seqchars, cmatrix *seqchar, ivector *seqgapchar, ivector *seqotherchar)
{	
	int notu, sn, co;
	char c;
	cvector code;
	
	if (*seqgapchar   != NULL) free_ivector(*seqgapchar);
	if (*seqotherchar != NULL) free_ivector(*seqotherchar);
	Seqgapchar   = new_ivector(Maxspc);
	Seqotherchar = new_ivector(Maxspc);

	/* Seqgapchar   = (int *) calloc(maxspc, sizeof(int)); */
	/* Seqotherchar = (int *) calloc(maxspc, sizeof(int)); */


	/* determine maxsite - number of ML sites per taxon */
	if (data_optn == NUCLEOTIDE && SH_optn) {
		if (SHcodon)
			*maxsite = maxseqc / 3;
		else
			*maxsite = maxseqc / 2; /* assume doublets */
		
	} else
		*maxsite = maxseqc;
	if (data_optn == NUCLEOTIDE && (*maxsite % 3) == 0  && !SH_optn) {	
		if (codon_optn == 1 || codon_optn == 2 || codon_optn == 3)
			*maxsite = *maxsite / 3; /* only one of the three codon positions */
		if (codon_optn == 4)
			*maxsite = 2*(*maxsite / 3); /* 1st + 2nd codon positions */
	}
	
	/* reserve memory */
	if (*seqchar != NULL) free_cmatrix(*seqchar);
	*seqchar = new_cmatrix(maxspc, *maxsite);

	/* code length */
	if (data_optn == NUCLEOTIDE && SH_optn)
		code = new_cvector(2);
	else
		code = new_cvector(1);
	
	/* decode characters */
	if (data_optn == NUCLEOTIDE && SH_optn) { /* SH doublets */
		
		for (notu = 0; notu < maxspc; notu++) {
			for (sn = 0; sn < *maxsite; sn++) {
					for (co = 0; co < 2; co++) {
						if (SHcodon)
							c = seqchars[notu][sn*3 + co];
						else
							c = seqchars[notu][sn*2 + co];
						code[co] = c;
					}
				(*seqchar)[notu][sn] = code2int(code, &((*seqgapchar)[notu]), &((*seqotherchar)[notu]));
			}
		}
		
	} else if (!(data_optn == NUCLEOTIDE && (maxseqc % 3) == 0)) { /* use all */

		for (notu = 0; notu < maxspc; notu++) {
			for (sn = 0; sn < *maxsite; sn++) {
				code[0] = seqchars[notu][sn];
				(*seqchar)[notu][sn] = code2int(code, &((*seqgapchar)[notu]), &((*seqotherchar)[notu]));
			}
		}

	} else { /* codons */
		
		for (notu = 0; notu < maxspc; notu++) {
			for (sn = 0; sn < *maxsite; sn++) {
				if (codon_optn == 1 || codon_optn == 2 || codon_optn == 3)
					code[0] = seqchars[notu][sn*3+codon_optn-1];
				else if (codon_optn == 4) {
					if ((sn % 2) == 0)
						code[0] = seqchars[notu][(sn/2)*3];
					else
						code[0] = seqchars[notu][((sn-1)/2)*3+1];
				} else
					code[0] = seqchars[notu][sn];
				(*seqchar)[notu][sn] = code2int(code, &((*seqgapchar)[notu]), &((*seqotherchar)[notu]));
			}
		}
	
	}

	free_cvector(code);

} /* translatedataset */

/******************/



/* estimate mean base frequencies from translated data set */
void estimatebasefreqs()
{
	int tpmradix, i, j;
	uli all, *gene;
	
	tpmradix = gettpmradix();
	
	if (Freqtpm != NULL) free_dvector(Freqtpm);
	Freqtpm = new_dvector(tpmradix);
	
	if (Basecomp != NULL) free_imatrix(Basecomp);
	Basecomp = new_imatrix(Maxspc, tpmradix);
	
	gene = (uli *) calloc((size_t) (tpmradix + 1), sizeof(uli));
	if (gene == NULL) maerror("gene in estimatebasefreqs");
	
	for (i = 0; i < tpmradix + 1; i++) gene[i] = 0;
	for (i = 0; i < Maxspc; i++)
		for (j = 0; j < tpmradix; j++) Basecomp[i][j] = 0;
	for (i = 0; i < Maxspc; i++)
		for (j = 0; j < Maxsite; j++) {
			gene[(int) Seqchar[i][j]]++;
			if (Seqchar[i][j] != tpmradix) Basecomp[i][(int) Seqchar[i][j]]++;
			}

	all = Maxspc * Maxsite - gene[tpmradix];
	if (all != 0) { /* normal case */
		for (i = 0; i < tpmradix; i++)
			Freqtpm[i] = (double) gene[i] / (double) all;
	} else { /* pathological case with no unique character in data set */
		for (i = 0; i < tpmradix; i++)
			Freqtpm[i] = 1.0 / (double) tpmradix;
	}
	
	free(gene);
	
	Frequ_optn = TRUE;
} /* estimatebasefreqs */

/******************/


/* guess model of substitution */
void guessmodel()
{
	double c1, c2, c3, c4, c5, c6;
	dvector f;
	dmatrix a;
	int i;

	Dayhf_optn = FALSE;
	Jtt_optn = TRUE;
	mtrev_optn = FALSE;
	cprev_optn = FALSE;
	blosum62_optn = FALSE;
	vtmv_optn = FALSE;
	wag_optn = FALSE;
	TSparam = 2.0;
	YRparam = 1.0;
	optim_optn = TRUE;
	HKY_optn = TRUE;
	print_GTR_optn = TRUE;
	GTR_optn = FALSE;
	TN_optn = FALSE;
	
	if (data_optn == AMINOACID) { /* amino acids */
		
		/* chi2 fit to amino acid frequencies */
		
		f = new_dvector(20);
		a = new_dmatrix(20,20);
		/* chi2 distance Dayhoff */
		dyhfdata(a, f);
		c1 = 0;
		for (i = 0; i < 20; i++)
			c1 = c1 + (Freqtpm[i]-f[i])*(Freqtpm[i]-f[i]);
		/* chi2 distance JTT */
		jttdata(a, f);
		c2 = 0;
		for (i = 0; i < 20; i++)
			c2 = c2 + (Freqtpm[i]-f[i])*(Freqtpm[i]-f[i]);
		/* chi2 distance mtREV */
		mtrevdata(a, f);
		c3 = 0;
		for (i = 0; i < 20; i++)
			c3 = c3 + (Freqtpm[i]-f[i])*(Freqtpm[i]-f[i]);
		/* chi2 distance VT */
		vtmvdata(a, f);
		c4 = 0;
		for (i = 0; i < 20; i++)
			c4 = c4 + (Freqtpm[i]-f[i])*(Freqtpm[i]-f[i]);
		/* chi2 distance WAG */
		wagdata(a, f);
		c5 = 0;
		for (i = 0; i < 20; i++)
			c5 = c5 + (Freqtpm[i]-f[i])*(Freqtpm[i]-f[i]);
		/* chi2 distance cpREV */
		cprev45data(a, f);
		c6 = 0;
		for (i = 0; i < 20; i++)
			c6 = c6 + (Freqtpm[i]-f[i])*(Freqtpm[i]-f[i]);

		free_dvector(f);
		free_dmatrix(a);

#ifndef CPREV
		if ((c1 < c2) && (c1 < c3) && (c1 < c4) && (c1 < c5)) {
		        /* c1 -> Dayhoff */
			Dayhf_optn = TRUE;
			Jtt_optn = FALSE;
			mtrev_optn = FALSE;
			cprev_optn = FALSE;
			vtmv_optn = FALSE;
			wag_optn = FALSE;
			fprintf(STDOUT, "(consists very likely of amino acids encoded on nuclear DNA)\n");
		} else {
			if ((c2 < c3) && (c2 < c4) && (c2 < c5)) {
				/* c2 -> JTT */
				Dayhf_optn = FALSE;
				Jtt_optn = TRUE;
				mtrev_optn = FALSE;
				cprev_optn = FALSE;
				vtmv_optn = FALSE;
				wag_optn = FALSE;
				fprintf(STDOUT, "(consists very likely of amino acids encoded on nuclear DNA)\n");
			} else {
				if ((c3 < c4) && (c3 < c5)) {
					/* c3 -> mtREV */
					Dayhf_optn = FALSE;
					Jtt_optn = FALSE;
					mtrev_optn = TRUE;
					cprev_optn = FALSE;
					vtmv_optn = FALSE;
					wag_optn = FALSE;
					fprintf(STDOUT, "(consists very likely of amino acids encoded on mtDNA)\n");
				} else {
					if ((c4 < c5)) {
						/* c4 -> VT */
						Dayhf_optn = FALSE;
						Jtt_optn = FALSE;
						mtrev_optn = FALSE;
						cprev_optn = FALSE;
						vtmv_optn = TRUE;
						wag_optn = FALSE;
						fprintf(STDOUT, "(consists very likely of amino acids encoded on nuclear DNA)\n");
					} else {
							/* c5 -> WAG */
							Dayhf_optn = FALSE;
							Jtt_optn = FALSE;
							mtrev_optn = FALSE;
							cprev_optn = FALSE;
							vtmv_optn = FALSE;
							wag_optn = TRUE;
							fprintf(STDOUT, "(consists very likely of amino acids encoded on nuclear DNA)\n");
					} /* if c4 else c5 */
				} /* if c3 else c4 */
			} /* if c2 */
		} /* if c1 */

#else /* CPREV */

		if ((c1 < c2) && (c1 < c3) && (c1 < c4) && (c1 < c5) && (c1 < c6)) {
		        /* c1 -> Dayhoff */
			Dayhf_optn = TRUE;
			Jtt_optn = FALSE;
			mtrev_optn = FALSE;
			cprev_optn = FALSE;
			vtmv_optn = FALSE;
			wag_optn = FALSE;
			fprintf(STDOUT, "(consists very likely of amino acids encoded on nuclear DNA)\n");
		} else {
			if ((c2 < c3) && (c2 < c4) && (c2 < c5) && (c2 < c6)) {
				/* c2 -> JTT */
				Dayhf_optn = FALSE;
				Jtt_optn = TRUE;
				mtrev_optn = FALSE;
				cprev_optn = FALSE;
				vtmv_optn = FALSE;
				wag_optn = FALSE;
				fprintf(STDOUT, "(consists very likely of amino acids encoded on nuclear DNA)\n");
			} else {
				if ((c3 < c4) && (c3 < c5) && (c3 < c6)) {
					/* c3 -> mtREV */
					Dayhf_optn = FALSE;
					Jtt_optn = FALSE;
					mtrev_optn = TRUE;
					cprev_optn = FALSE;
					vtmv_optn = FALSE;
					wag_optn = FALSE;
					fprintf(STDOUT, "(consists very likely of amino acids encoded on mtDNA)\n");
				} else {
					if ((c4 < c5) && (c4 < c6)) {
						/* c4 -> VT */
						Dayhf_optn = FALSE;
						Jtt_optn = FALSE;
						mtrev_optn = FALSE;
						cprev_optn = FALSE;
						vtmv_optn = TRUE;
						wag_optn = FALSE;
						fprintf(STDOUT, "(consists very likely of amino acids encoded on nuclear DNA)\n");
					} else {
						if (c5 < c6) {
							/* c5 -> WAG */
							Dayhf_optn = FALSE;
							Jtt_optn = FALSE;
							mtrev_optn = FALSE;
							cprev_optn = FALSE;
							vtmv_optn = FALSE;
							wag_optn = TRUE;
							fprintf(STDOUT, "(consists very likely of amino acids encoded on nuclear DNA)\n");
						} else {
							/* if (c6) */
							/* c6 -> cpREV */
							Dayhf_optn = FALSE;
							Jtt_optn = FALSE;
							mtrev_optn = FALSE;
							cprev_optn = TRUE;
							vtmv_optn = FALSE;
							wag_optn = FALSE;
							fprintf(STDOUT, "(consists very likely of amino acids encoded on cpDNA)\n");
						} /* if c5 else c6 */
					} /* if c4 else c5 */
				} /* if c3 else c4 */
			} /* if c2 */
		} /* if c1 */
#endif /* CPREV */

	} else if (data_optn == NUCLEOTIDE) {
		fprintf(STDOUT, "(consists very likely of nucleotides)\n");
	} else {
		fprintf(STDOUT, "(consists very likely of binary state data)\n");
	}
} /* guessmodel */


/******************************************************************************/

/* parts outsourced to treesort.c/treesort.h */
#if 0 /* TREESORT_H */
#endif /* TREESORT_H */

/* parts outsourced to consensus.c/consensus.h */
#if 0 /* CONSENSUS_H */
#endif /* CONSENSUS_H */


/******************************************************************************/
/* storing and evaluating quartet branching information                       */
/******************************************************************************/

/* general remarks:

	for a quartet with the taxa a, b, c, d there are
	three possible binary trees:
	
		1)  (a,b)-(c,d)
		2)  (a,c)-(b,d)
		3)  (a,d)-(b,c)
	
	For every quartet information about its branching structure is
	stored. With the functions  readquartet  and  writequartet
	this information can be accessed. For every quartet (a,b,c,d)
	with a < b < c < d (taxa) the branching information is encoded
	using 4 bits:
	
	value          8             4             2             1
	        +-------------+-------------+-------------+-------------+
	        |  not used   |   tree 3    |   tree 2    |   tree 1    |
	        +-------------+-------------+-------------+-------------+

	If the branching structure of the taxa corresponds to one of the
	three trees the corresponding bit is set. If the branching structure
	is unclear because two of the three trees have the same maximum
	likelihood value the corresponding two bits are set. If the branching
	structure is completely unknown all the bits are set (the highest
	bit is always cleared because it is not used).

*/

/* allocate memory for quartets */
unsigned char *callocquartets(int taxa)
{
	uli nc, numch;
	unsigned char *qinfo;
	
	/* compute number of quartets */
	Numquartets = (uli) taxa*(taxa-1)*(taxa-2)*(taxa-3)/24;
	if (Numquartets % 2 == 0) { /* even number */
		numch = Numquartets/2;
	} else { /* odd number */
		numch = (Numquartets + 1)/2;
	}
	/* allocate memory */
	qinfo = (unsigned char *) calloc((size_t) numch, sizeof(unsigned char));
	if (qinfo == NULL) maerror("quartetinfo in callocquartets");
	for (nc = 0; nc < numch; nc++) qinfo[nc] = 0;
	return(qinfo);
} /* callocquartets */

/* free quartet memory */
void freequartets()
{	
	free(quartetinfo);
} /* freequartets */

/**************/

/* read quartet info - a < b < c < d */
unsigned char readquartet(int a, int b, int c, int d)
{
	uli qnum;

	if (! ((a < b) && (b < c) && (c < d))) {
		fprintf(stderr, "\n\n\nHALT: PLEASE REPORT ERROR HS2 TO DEVELOPERS! (%d,%d,%d,%d)\n", a,b,c,d);
#		if PARALLEL
			PP_Finalize();
#		endif
		exit (999);

	}
	qnum = (uli) a
			+ (uli) b*(b-1)/2
			+ (uli) c*(c-1)*(c-2)/6
			+ (uli) d*(d-1)*(d-2)*(d-3)/24;
	if (qnum % 2 == 0) { /* even number */
		/* bits 0 to 3 */
		return (quartetinfo[qnum/2] & (unsigned char) 15);
	} else { /* odd number */
		/* bits 4 to 7 */
		return ((quartetinfo[(qnum-1)/2] & (unsigned char) 240)>>4);
	}
} /* readquartet */

/**************/

/* write quartet info - a < b < c < d, 0 <= info <= 15 */
void writequartet(int a, int b, int c, int d, unsigned char info)
{
	uli qnum;

	qnum = (uli) a
			+ (uli) b*(b-1)/2
			+ (uli) c*(c-1)*(c-2)/6
			+ (uli) d*(d-1)*(d-2)*(d-3)/24;
	if (qnum % 2 == 0) { /* even number */
		/* bits 0 to 3 */
		quartetinfo[qnum/2] =
			((quartetinfo[qnum/2] & (unsigned char) 240) |
			(info & (unsigned char) 15));
	} else { /* odd number */
		/* bits 4 to 7 */
		quartetinfo[(qnum-1)/2] =
			((quartetinfo[(qnum-1)/2] & (unsigned char) 15) |
			((info & (unsigned char) 15)<<4));
	}
} /* writequartet */

/**************/
/* prototypes */
int openfiletowrite(FILE **, char[], char[]);
void closefile(FILE *);

/* sorts three doubles in descending order */
void sort3doubles(dvector num, ivector order)
{
	if (num[0] > num[1]) {
		if(num[2] > num[0]) {
			order[0] = 2;
			order[1] = 0;
			order[2] = 1;		
		} else if (num[2] < num[1]) {
			order[0] = 0;
			order[1] = 1;
			order[2] = 2;		
		} else {
			order[0] = 0;
			order[1] = 2;
			order[2] = 1;		
		}
	} else {
		if(num[2] > num[1]) {
			order[0] = 2;
			order[1] = 1;
			order[2] = 0;		
		} else if (num[2] < num[0]) {
			order[0] = 1;
			order[1] = 0;
			order[2] = 2;		
		} else {
			order[0] = 1;
			order[1] = 2;
			order[2] = 0;		
		}
	}
} /* sort3doubles */

/*************************/

/* compute Bayesian weights from log-lkls d1, d2, d3 */
unsigned char loglkl2weight(int    a,
                            int    b,
                            int    c,
                            int    i,
                            double d1,
                            double d2,
                            double d3,
                            int    usebestq)
{
	double onethird;
	unsigned char treebits[3];
	double templog;
	unsigned char tmpweight;
	double temp;
	double temp1, temp2, temp3;
	unsigned char discreteweight[3];

	double tttqweight[3];
	double tttsqdiff[3];
	int tttsqorder[3];
	int tttqworder[3];

	tttqweight[0] = d1;
	tttqweight[1] = d2;
	tttqweight[2] = d3;

	onethird = 1.0/3.0;
	treebits[0] = (unsigned char) 1;
	treebits[1] = (unsigned char) 2;
	treebits[2] = (unsigned char) 4;
	
	/* sort in descending order */
	sort3doubles(tttqweight, tttqworder);

	if (usebestq) {
		tttsqorder[2] = 2;
		discreteweight[tttsqorder[2]] = treebits[tttqworder[0]];
		if (tttqweight[tttqworder[0]] == tttqweight[tttqworder[1]]) {
			discreteweight[tttsqorder[2]] = discreteweight[tttsqorder[2]] || treebits[tttqworder[1]];
			if (tttqweight[tttqworder[1]] == tttqweight[tttqworder[2]]) {
				discreteweight[tttsqorder[2]] = discreteweight[tttsqorder[2]] || treebits[tttqworder[2]];
				discreteweight[tttsqorder[2]] = 7;
			} 
		}
	} else {

		/* compute Bayesian weights */
		templog = tttqweight[tttqworder[1]]-tttqweight[tttqworder[0]];
		if(templog < -TP_MAX_EXP_DIFF)	/* possible, since 1.0+exp(>36) == 1.0 */
			tttqweight[tttqworder[1]] = 0.0;
		else
			tttqweight[tttqworder[1]] = exp(templog);

	 	templog = tttqweight[tttqworder[2]]-tttqweight[tttqworder[0]];
		if(templog < -TP_MAX_EXP_DIFF)	/* possible, since 1.0+exp(>36) == 1.0 */
			tttqweight[tttqworder[2]] = 0.0;
		else
			tttqweight[tttqworder[2]] = exp(templog);

		tttqweight[tttqworder[0]] = 1.0;

		temp = tttqweight[0] + tttqweight[1] + tttqweight[2];

		tttqweight[0] = tttqweight[0]/temp;
		tttqweight[1] = tttqweight[1]/temp;
		tttqweight[2] = tttqweight[2]/temp;

		/* square deviations */
		temp1 = 1.0 - tttqweight[tttqworder[0]];
		tttsqdiff[0] = temp1 * temp1 +
		tttqweight[tttqworder[1]] * tttqweight[tttqworder[1]] +
		tttqweight[tttqworder[2]] * tttqweight[tttqworder[2]];
		discreteweight[0] = treebits[tttqworder[0]];
 
		temp1 = 0.5 - tttqweight[tttqworder[0]];
		temp2 = 0.5 - tttqweight[tttqworder[1]];
		tttsqdiff[1] = temp1 * temp1 + temp2 * temp2 +
		tttqweight[tttqworder[2]] * tttqweight[tttqworder[2]];
		discreteweight[1] = treebits[tttqworder[0]] + treebits[tttqworder[1]];

		temp1 = onethird - tttqweight[tttqworder[0]];
		temp2 = onethird - tttqweight[tttqworder[1]];
		temp3 = onethird - tttqweight[tttqworder[2]];
		tttsqdiff[2] = temp1 * temp1 + temp2 * temp2 + temp3 * temp3;
		discreteweight[2] = (unsigned char) 7;

		/* sort in descending order */
		sort3doubles(tttsqdiff, tttsqorder);
	}

	tmpweight = discreteweight[tttsqorder[2]];
	return(tmpweight);
} /* loglkl2weight */


/*************************/

/* checks out all possible quartets */
void computeallquartets()
{	
	double onethird;
	uli nq;
	unsigned char treebits[3];
#	if ! PARALLEL
		unsigned char tmpweight;
		FILE *lhfp;
		int a, b, c, i;
#	endif

		onethird = 1.0/3.0;
		treebits[0] = (unsigned char) 1;
		treebits[1] = (unsigned char) 2;
		treebits[2] = (unsigned char) 4;
	
	if (show_optn) { /* list all unresolved quartets */
		openfiletowrite(&unresfp, UNRESOLVED, "unresolved quartet trees");
		fprintf(unresfp, "List of all completely unresolved quartets:\n\n");
	}

	nq = 0;
	badqs = 0;
	
	/* start timer - percentage of completed quartets */
	time(&time0);
	time1 = time0;
	mflag = 0;
	
#	if PARALLEL
	{
		schedtype sched; 
		int flag;
		MPI_Status stat;

		int dest = 1;
		uli qaddr  =0;
		uli qamount=0;
		int qblocksent = 0;
		int apr;
		uli Sumquartets;
		uli sq, noq;

		uli tmpfullresqs;
		uli tmppartresqs;
		uli tmpunresqs;
		uli tmpmissingqs;

		Sumquartets = numquarts(Maxspc);
		initsched(&sched, Sumquartets, PP_NumProcs-1, 4);
		qamount=SCHEDALG_ML_STEP(&sched);

		while (qamount > 0) {
			if (PP_emptyslave()) {
				PP_RecvQuartBlock(0, &sq, &noq, quartetinfo, &tmpfullresqs, &tmppartresqs, &tmpunresqs, &tmpmissingqs, &usebestq_optn, &apr);
				qblocksent -= noq;
			}
			dest = PP_getslave();
			PP_SendDoQuartBlock(dest, qaddr, qamount, usebestq_optn, (approxqp ? APPROX : EXACT));
			qblocksent += qamount;
			qaddr += qamount;
			qamount=SCHEDALG_ML_STEP(&sched);

			MPI_Iprobe(MPI_ANY_SOURCE, PP_QUARTBLOCKSPECS, PP_Comm, &flag, &stat);
			while (flag) {
				PP_RecvQuartBlock(0, &sq, &noq, quartetinfo, &tmpfullresqs, &tmppartresqs, &tmpunresqs, &tmpmissingqs, &usebestq_optn, &apr);
				qblocksent -= noq;
				MPI_Iprobe(MPI_ANY_SOURCE, PP_QUARTBLOCKSPECS, PP_Comm, &flag, &stat);
			}
			checktime(&time0, &time1, &time2, qaddr - qblocksent, Sumquartets, &mflag);
		}
		while (qblocksent > 0) {
			PP_RecvQuartBlock(0, &sq, &noq, quartetinfo, &tmpfullresqs, &tmppartresqs, &tmpunresqs, &tmpmissingqs, &usebestq_optn, &apr);
			qblocksent -= noq;
			checktime(&time0, &time1, &time2, qaddr - qblocksent, Sumquartets, &mflag);
		}
	}
#	else /* ! PARALLEL */

		addtimes(GENERAL, &tarr);
		if (savequartlh_optn) {
			openfiletowrite(&lhfp, ALLQUARTLH, "all quartet likelihoods");
			if (saveqlhbin_optn) writetpqfheader(Maxspc, lhfp, 3);
			else                 writetpqfheader(Maxspc, lhfp, 4); 
		}

		for (i = 3; i < Maxspc; i++) 
			for (c = 2; c < i; c++) 
				for (b = 1; b < c; b++)
					for (a = 0; a < b; a++) {
						nq++;

						/* generate message every >TIMECHECK_INTERVAL seconds */
						/* check timer */
						checktime(&time0, &time1, &time2, nq, Numquartets, &mflag);

						/* maximum likelihood values */

						/* exact or approximate maximum likelihood values */
						compute_quartlklhds(a,b,c,i,&qweight[0],&qweight[1],&qweight[2], (approxqp ? APPROX : EXACT));

						if (savequartlh_optn) {
							if (saveqlhbin_optn)
								fwrite(qweight, sizeof(double), 3, lhfp);
							else
								fprintf(lhfp, "(%d,%d,%d,%d)\t%f\t%f\t%f\n", a, b, c, i, 
							qweight[0], qweight[1], qweight[2]); 
						}

						tmpweight = loglkl2weight(a, b, c, i, qweight[0], qweight[1], qweight[2], usebestq_optn);
/* tmpweight = loglkl2weight(a, b, c, i, d1, d2, d3, usebestq_optn); */

						/* determine best discrete weight */
						/* writequartet(a, b, c, i, discreteweight[sqorder[2]]); */
						writequartet(a, b, c, i, tmpweight);


						/* compute sums of topologies per taxon, step by step */
						++(qinfomatr[8][a]);
						++(qinfomatr[8][b]);
						++(qinfomatr[8][c]);
						++(qinfomatr[8][i]);
						++(qinfomatr[tmpweight][a]);
						++(qinfomatr[tmpweight][b]);
						++(qinfomatr[tmpweight][c]);
						++(qinfomatr[tmpweight][i]);

						if ((tmpweight <= 2) || (tmpweight == 4)) {
							fullresqs++;
						} else {
							if (tmpweight == 7) {
								unresqs++;
							} else {
								if (tmpweight == 0) {
									missingqs++;
								} else {
									partresqs++;
								}
							}
						}

						/* counting completely unresolved quartets */
						if (tmpweight == 7) {
							badqs++;
							badtaxon[a]++;
							badtaxon[b]++;
							badtaxon[c]++;
							badtaxon[i]++;
							if (show_optn) {
								fputid10(unresfp, a);
								fprintf(unresfp, "  ");
								fputid10(unresfp, b);
								fprintf(unresfp, "  ");
								fputid10(unresfp, c);
								fprintf(unresfp, "  ");
								fputid(unresfp, i);
								fprintf(unresfp, "\n");
							}
						}
						addtimes(QUARTETS, &tarr);
		}
		if (savequartlh_optn) {
			closefile(lhfp);
		}
		if (show_optn)
			closefile(unresfp);
		if (mflag == 1)
			fprintf(STDOUT, "\n");
#	endif /* PARALLEL */

} /* computeallquartets */

/* trueID (HAS) */
/* check the branching structure between the leaves (not the taxa!)
   A, B, C, and I (A, B, C, I don't need to be ordered). As a result,
   the two leaves that are closer related to each other than to leaf I
   are found in chooseX and chooseY. If the branching structure is
   not uniquely defined, chooseX and chooseY are chosen randomly
   from the possible taxa */
void checkquartet_trueID(int  A,   /* quartet leaf idx in permutation array */
                  int  B,          /* dito.                                 */
                  int  C,          /* dito.                                 */
                  int  I,          /* dito., to be inserted                 */
                  int *trueID,     /* permutation array                     */
                  int *chooseX,    /* (chooseX,chooseY | x,I)               */
                  int *chooseY)    /* chooseX+Y are non-neighbors of I      */
{
	int i, j;              /* counter */
	int a, b;              /* temp variable for sorting */
	int taxon[5];          /* sorting array for taxa from trueID */
	int leaf[5];           /* sorting array for indices in trueID */
	int ipos;              /* position of leaf I in sorted array */
	unsigned char qresult; /* quartet topology */
	int notunique = FALSE; /* non-unique topology */

	/* The relationship between leaves and taxa is defined by trueID */
	taxon[1] = trueID[A]; /* taxon number */
	leaf[1] = A;          /* leaf index in permutation */
	taxon[2] = trueID[B];
	leaf[2] = B;
	taxon[3] = trueID[C];
	leaf[3] = C;
	taxon[4] = trueID[I];
	leaf[4] = I;

	/* sort for taxa */
	/* Source: Numerical Recipes (PIKSR2.C) */
	for (j = 2; j <= 4; j++) {
		a = taxon[j];
		b = leaf[j];
		i = j-1;
		while (i > 0 && taxon[i] > a) {
			taxon[i+1] = taxon[i];
			leaf[i+1] = leaf[i];
			i--;
		}
		taxon[i+1] = a;
		leaf[i+1] = b;
	}

	/* where is leaf I ? */
	ipos = 1;
	while (leaf[ipos] != I) ipos++;

	/* look at sequence quartet */
	qresult = readquartet(taxon[1], taxon[2], taxon[3], taxon[4]);

	/* chooseX and chooseY */
 	/* qresult is not unique, a covered unique qresult is chosen */
	/* and the while loop is circled again (optimizable?) (HAS)  */
	do {
		switch (qresult) {

			/* one single branching structure */

			/* 001 */
			case 1:		if (ipos == 1 || ipos == 2) {
						*chooseX = leaf[3];
						*chooseY = leaf[4];
					} else {
						*chooseX = leaf[1];
						*chooseY = leaf[2];
					}
					notunique = FALSE;
					break;

			/* 010 */
			case 2:		if (ipos == 1 || ipos == 3) {
						*chooseX = leaf[2];
						*chooseY = leaf[4];
					} else {
						*chooseX = leaf[1];
						*chooseY = leaf[3];
					}
					notunique = FALSE;
					break;

			/* 100 */
			case 4:		if (ipos == 1 || ipos == 4) {
						*chooseX = leaf[2];
						*chooseY = leaf[3];
					} else {
						*chooseX = leaf[1];
						*chooseY = leaf[4];
					}
					notunique = FALSE;
					break;

			/* two possible branching structures */		

			/* 011 */
			case 3:		if (randominteger(2)) qresult = 1;
					else qresult = 2;
					notunique = TRUE;
					break;

			/* 101 */
			case 5:		if (randominteger(2)) qresult = 1;
					else qresult = 4;
					notunique = TRUE;
					break;

			/* 110 */
			case 6:		if (randominteger(2)) qresult = 2;
					else qresult = 4;
					notunique = TRUE;
					break;

			/* three possible branching structures */

			/* 111 */
			case 7:		qresult = (1 << randominteger(3)); /* 1, 2, or 4 */
					notunique = TRUE;
					break;

			/* 000 */  /* empty quartet: missing data -> OK, otherwise ERROR */
			case 0:		if (readsubset_optn) {
						*chooseX = -1;
						*chooseY = -1;
					} else {
#						if PARALLEL
							fprintf(STDOUT, "\n\n\n(%2d)HALT: PLEASE REPORT ERROR K1-PARALLEL TO DEVELOPERS : empty (%d,%d,%d,%d) = %ld\n\n\n", 
								PP_Myid, taxon[1], taxon[2], taxon[3], taxon[4],
								quart2num(taxon[1], taxon[2], taxon[3], taxon[4]));
								PP_Finalize();
								exit (999);
#						else
							fprintf(STDOUT, "\n\n\nHALT: PLEASE REPORT ERROR K1 TO DEVELOPERS: empty (%d,%d,%d,%d) = %ld\n\n\n", 
								taxon[1], taxon[2], taxon[3], taxon[4],
								quart2num(taxon[1], taxon[2], taxon[3], taxon[4]));
								exit (999);
#						endif
					}
					notunique = FALSE;
					break;

			default:	/* Program error [checkquartet] */
#					if PARALLEL
						fprintf(STDOUT, "\n\n\n(%2d)HALT: PLEASE REPORT ERROR K2-PARALLEL TO DEVELOPERS (%d,%d,%d,%d) = %ld (%d)\n\n\n", 
							PP_Myid, taxon[1], taxon[2], taxon[3], taxon[4],
							quart2num(taxon[1], taxon[2], taxon[3], taxon[4]), qresult);
							PP_Finalize();
							exit (999);
#					else
						fprintf(STDOUT, "\n\n\nHALT: PLEASE REPORT ERROR K2 TO DEVELOPERS (%d,%d,%d,%d) = %ld (%d)\n\n\n", 
							taxon[1], taxon[2], taxon[3], taxon[4],
							quart2num(taxon[1], taxon[2], taxon[3], taxon[4]), qresult);
							exit (999);
#					endif
						
		} /* switch (qresult) */
	} while (notunique);

	return;
} /* checkquartet_trueID */

/* un-trueID-ed (HAS) */
/* check the branching structure between the leaves (not the taxa!)
   A, B, C, and I (A, B, C, I don't need to be ordered). As a result,
   the two leaves that are closer related to each other than to leaf I
   are found in chooseX and chooseY. If the branching structure is
   not uniquely defined, chooseX and chooseY are chosen randomly
   from the possible taxa */
void checkquartet(int  A,          /* quartet taxon ID                 */
                  int  B,          /* dito.                            */
                  int  C,          /* dito.                            */
                  int  I,          /* dito., to be inserted            */
                  int *chooseX,    /* (chooseX,chooseY | x,I)          */
                  int *chooseY)    /* chooseX+Y are non-neighbors of I */
{
	int i, j;              /* counter */
	int a;                 /* temp variable for sorting */
	int leaf[5];           /* sorting array */
	int ipos;              /* position of leaf I in sorted array */
	unsigned char qresult; /* quartet topology */
	int notunique = FALSE; /* non-unique topology */

	/* The relationship between leaves and taxa is defined by trueID */
	leaf [1] = A; /* taxon ID of leaf 1 */
	leaf [2] = B; /* taxon ID of leaf 2 */
	leaf [3] = C; /* taxon ID of leaf 3 */
	leaf [4] = I; /* taxon ID of leaf 4 */

	/* sort for taxa */
	/* Source: Numerical Recipes (PIKSR2.C) */
	for (j = 2; j <= 4; j++) {
		a = leaf[j];
		i = j-1;
		while (i > 0 && leaf[i] > a) {
			leaf[i+1] = leaf[i];
			i--;
		}
		leaf[i+1] = a;
	}

	/* where is leaf I ? */
	ipos = 1;
	while (leaf[ipos] != I) ipos++;

	/* look at sequence quartet */
	qresult = readquartet(leaf[1], leaf[2], leaf[3], leaf[4]);

	/* chooseX and chooseY */
 	/* qresult is not unique, a covered unique qresult is chosen */
	/* and the while loop is circled again (optimizable?) (HAS)  */
	do {
		switch (qresult) {

			/* one single branching structure */

			/* 001 */
			case 1:		if (ipos == 1 || ipos == 2) {
						*chooseX = leaf[3];
						*chooseY = leaf[4];
					} else {
						*chooseX = leaf[1];
						*chooseY = leaf[2];
					}
					notunique = FALSE;
					break;

			/* 010 */
			case 2:		if (ipos == 1 || ipos == 3) {
						*chooseX = leaf[2];
						*chooseY = leaf[4];
					} else {
						*chooseX = leaf[1];
						*chooseY = leaf[3];
					}
					notunique = FALSE;
					break;

			/* 100 */
			case 4:		if (ipos == 1 || ipos == 4) {
						*chooseX = leaf[2];
						*chooseY = leaf[3];
					} else {
						*chooseX = leaf[1];
						*chooseY = leaf[4];
					}
					notunique = FALSE;
					break;

			/* two possible branching structures */		

			/* 011 */
			case 3:		if (randominteger(2)) qresult = 1;
					else qresult = 2;
					notunique = TRUE;
					break;

			/* 101 */
			case 5:		if (randominteger(2)) qresult = 1;
					else qresult = 4;
					notunique = TRUE;
					break;

			/* 110 */
			case 6:		if (randominteger(2)) qresult = 2;
					else qresult = 4;
					notunique = TRUE;
					break;

			/* three possible branching structures */

			/* 111 */
			case 7:		qresult = (1 << randominteger(3)); /* 1, 2, or 4 */
					notunique = TRUE;
					break;

			/* 000 */  /* empty quartet: missing data -> OK, otherwise ERROR */
			case 0:		if (readsubset_optn) {
						*chooseX = -1;
						*chooseY = -1;
					} else {
#						if PARALLEL
							fprintf(STDOUT, "\n\n\n(%2d)HALT: PLEASE REPORT ERROR K1-PARALLEL TO DEVELOPERS : empty (%d,%d,%d,%d) = %ld\n\n\n", 
								PP_Myid, leaf[1], leaf[2], leaf[3], leaf[4],
								quart2num(leaf[1], leaf[2], leaf[3], leaf[4]));
								PP_Finalize();
								exit (999);
#						else
							fprintf(STDOUT, "\n\n\nHALT: PLEASE REPORT ERROR K1 TO DEVELOPERS: empty (%d,%d,%d,%d) = %ld\n\n\n", 
								leaf[1], leaf[2], leaf[3], leaf[4],
								quart2num(leaf[1], leaf[2], leaf[3], leaf[4]));
								exit (999);
#						endif
					}
					notunique = FALSE;
					break;

			default:	/* Program error [checkquartet] */
#					if PARALLEL
						fprintf(STDOUT, "\n\n\n(%2d)HALT: PLEASE REPORT ERROR K2-PARALLEL TO DEVELOPERS (%d,%d,%d,%d) = %ld (%d)\n\n\n", 
							PP_Myid, leaf[1], leaf[2], leaf[3], leaf[4],
							quart2num(leaf[1], leaf[2], leaf[3], leaf[4]), qresult);
							PP_Finalize();
							exit (999);
#					else
						fprintf(STDOUT, "\n\n\nHALT: PLEASE REPORT ERROR K2 TO DEVELOPERS (%d,%d,%d,%d) = %ld (%d)\n\n\n", 
							leaf[1], leaf[2], leaf[3], leaf[4],
							quart2num(leaf[1], leaf[2], leaf[3], leaf[4]), qresult);
							exit (999);
#					endif
						
		} /* switch (qresult) */
	} while (notunique);

	return;
} /* checkquartet */