File: BCSequenceReader.m

package info (click to toggle)
biococoa 2.2.2-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,184 kB
  • sloc: objc: 21,348; makefile: 17; ansic: 4
file content (1696 lines) | stat: -rw-r--r-- 54,906 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
//
//  BCSequenceReader.m
//  BioCocoa
//
//  Created by Koen van der Drift on 10/16/04.
//  Copyright (c) 2003-2009 The BioCocoa Project.
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions
//  are met:
//  1. Redistributions of source code must retain the above copyright
//  notice, this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright
//  notice, this list of conditions and the following disclaimer in the
//  documentation and/or other materials provided with the distribution.
//  3. The name of the author may not be used to endorse or promote products
//  derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
//  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
//  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
//  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#import "BCSequenceReader.h"
#import "BCUtilStrings.h"
#import "BCSequence.h"
#import "BCAnnotation.h"
#import "BCSymbolSet.h"
#import "BCSequenceArray.h"

#import "BCFoundationDefines.h"
#import "BCInternal.h"

@implementation BCSequenceReader


- (BCSequenceArray *)readFileUsingPath:(NSString *)filePath
{
	BCSequenceArray	*result = nil;
	
    if([NSHFSTypeOfFile(filePath) isEqualToString: @"'xDNA'"])
	{
		result = [self readStriderFile: filePath];
	}
	
	else if([NSHFSTypeOfFile(filePath) isEqualToString: @"'GCKc'"] || [NSHFSTypeOfFile(filePath) isEqualToString: @"'GCKs'"])
	{
		result = [self readGCKFile: filePath];
	}
	else if ([NSHFSTypeOfFile(filePath) isEqualToString: @"'PROT'"] || [NSHFSTypeOfFile(filePath) isEqualToString: @"'NUCL'"])
	{
		result = [self readMacVectorFile: filePath];
	}
	else	// TEXT file
	{
		NSMutableString	*sequenceFileContents;

		// First test for EXDNA
		if([[filePath pathExtension] isEqualToString: @"exdna"])
		{
			sequenceFileContents = [NSMutableString stringWithContentsOfFile: [filePath stringByAppendingPathComponent: @"sequence.txt"]];
		}
		else
		{
			if ([[NSFileManager defaultManager] fileExistsAtPath: filePath])
			{
				sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
			}
			else
			{
			 // were actually dealing with a string input here, not a file
				sequenceFileContents = [NSMutableString stringWithString: filePath];
			}
		}
	
		result = [self readFileUsingText: sequenceFileContents];
	}
	
	return result;
}

- (BCSequenceArray *)readFileUsingPath:(NSString *)filePath format:(BCFileFormat)aFormat
{
	BCSequenceArray	*result = nil;
  NSMutableString *sequenceFileContents;

  switch (aFormat) {
    case BCFastaFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
			result = [self readFastaFile: sequenceFileContents];
      break;
    case BCSwissProtFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
      result = [self readSwissProtFile: sequenceFileContents];
      break;
    case BCPDBFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
      result = [self readPDBFile: sequenceFileContents];
      break;
    case BCNCBIFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
      result = [self readNCBIFile: sequenceFileContents];
      break;
    case BCClustalFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
      result = [self readClustalFile: sequenceFileContents];
      break;
    case BCStriderFileFormat:
      result = [self readStriderFile: filePath];
      break;
    case BCGCKFileFormat:
      result = [self readGCKFile: filePath];
      break;
    case BCMacVectorFileFormat:
      result = [self readMacVectorFile: filePath];
      break;
    case BCGDEFFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
      result = [self readGDEFile: sequenceFileContents];
      break;
    case BCPirFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
			result = [self readPirFile: sequenceFileContents];
      break;
    case BCMSFFileFormat:
      break;
    case BCPhylipFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
      result = [self readPhylipFile: sequenceFileContents];
      break;
    case BCNonaFileFormat:
      break;
    case BCHenningFileFormat:
      break;
    case BCFASTQFileFormat:
      sequenceFileContents = [NSMutableString stringWithContentsOfFile: filePath];
			result = [self readFASTQFile: sequenceFileContents];
      break;
  }

  return result;
}

- (BCSequenceArray *)readFileUsingData:(NSData *)dataFile
{
	NSString	*entryString = [[NSString alloc] initWithData: dataFile encoding: NSASCIIStringEncoding];	// or NSUTF8StringEncoding ?

	return [self readFileUsingText: [entryString autorelease]];
}

- (BCSequenceArray *)readFileUsingText:(NSString *)entryString
{
	BCSequenceArray	*result = nil;

 // RTF?
	
	if ([entryString hasCaseInsensitivePrefix: @"{\\rtf1"])
	{
	 // convert rtf string to a plain text string
		NSAttributedString *rtfstring = [[NSAttributedString alloc] initWithRTF: [entryString dataUsingEncoding: NSUTF8StringEncoding] documentAttributes: nil];
		entryString = [rtfstring string];
		[rtfstring release];
	}
	
	//		// should we also filter for HTML? Probably the best way to test whether we are dealing for a html file is to check for the last
	//		// html tag, which is alway </html>. Looking for the first tag won't work, since that varies too much.
	
	//		if ([entryString hasCaseInsensitiveSuffix: @"</html>"])
	//		{
	//			NSAttributedString *htmlstring = [[NSAttributedString alloc] initWithHTML: [NSData dataWithContentsOfFile: entryString] documentAttributes: nil];
	//			[sequenceFileContents setString: [htmlstring string]];
	//			[htmlstring release];
	//		}


 // DETERMINE TYPE
	
	if ([entryString hasCaseInsensitivePrefix:@"#NEXUS"] || [entryString hasCaseInsensitivePrefix:@"#PAUP"])
	{
		//result = [self readNexusFileAndBlocks: entryString];
	}
	
	else if ([entryString hasCaseInsensitivePrefix: @"proc/"])
	{
		//result = [self readNonaFile: entryString];
	}   

	else if ([entryString hasCaseInsensitivePrefix: @"xread"])
	{
		//result = [self readHennigFile: entryString];
	}    

	else if ([entryString hasCaseInsensitivePrefix: @"CLUSTAL"])
	{
		result = [self readClustalFile: entryString];
	}
	
	else if ([entryString hasCaseInsensitivePrefix: @"!!NA_"] || [entryString hasCaseInsensitivePrefix: @"!!AA_"] )
	{
		//result = [self readMSFFile: entryString];
	}
	
	else if ([entryString hasPrefix:@">"])
	{
		if ([entryString characterAtIndex: 3] == ';')
		{
			result = [self readPirFile: entryString];
		}
		else
		{
			result = [self readFastaFile: entryString];
		}
	}
	
	else if ([entryString hasPrefix:@"HEADER"])
	{
		result = [self readPDBFile: entryString];
	}
	
	else if ([entryString hasPrefix:@"LOCUS"])
	{
		result = [self readNCBIFile: entryString];
	}
	
	else if ([entryString hasPrefix:@"#"])
	{
		result = [self readGDEFile: entryString];
	}
	
	else if ([entryString hasPrefix:@"ID"])
	{
		result = [self readSwissProtFile: entryString];
	}
	
	else if ([entryString stringBeginsWithTwoNumbers])	
	{
		result = [self readPhylipFile: entryString];
	}

	else
	{
		result = [self readRawFile: entryString];		// Assumes sequences are in plain format
	}
	
	return result;
}

- (BCSequenceArray *) readFastaFile:(NSString *)entryString
{
#if 1
	BCSequenceArray	*result;
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

  int cnt = [entryString length];
  
	result = [[BCSequenceArray alloc] init];

	//printf("Allocating %d bytes.\n", cnt + 1);
  char *seq1 = (char *)malloc(sizeof(char) * (cnt + 1));
  if (!seq1) {
    NSLog(@"Not enough memory to load sequence file.\n");
    return nil;
  }
  bzero(seq1, cnt + 1);

  //printf("Loading file.\n");
	NSUInteger start, end, next; 
	NSRange range; 
  BCAnnotation *d = nil;
  int seqLen = 0;
  const char *dataBuffer = [entryString UTF8String];
	unsigned stringLength = [entryString length]; 
	range.location = 0; 
	range.length = 1; 
	do { 
		[entryString getLineStart:&start end:&next contentsEnd:&end forRange:range]; 

		range.location = start; 
		range.length = end-start; 

    if ([entryString characterAtIndex: start] == '>') {
      // FASTA header, separate sequences

      // save the previous sequence that just ended
      if (d) {
        NSData *finalData = [NSData dataWithBytes: seq1 length: seqLen];
        BCSequence *newSequence = [[BCSequence alloc] initWithData: finalData symbolSet: nil];
        [newSequence addAnnotation: d];
        [result addSequence: newSequence];
      }
      seqLen = 0;

      // FASTA header annotation
      ++range.location;
      --range.length;
      d = [BCAnnotation annotationWithName: @">" content: [entryString substringWithRange: range]];

    } else {
      // sequence segment
      memcpy(&(seq1[seqLen]), &(dataBuffer[range.location]), range.length);
      seqLen += range.length;
    }

		range.location = next; 
		range.length = 1; 
	} while (next < stringLength); 

  // save the last sequence
  NSData *finalData = [NSData dataWithBytes: seq1 length: seqLen];
  free(seq1);
  BCSequence *newSequence = [[BCSequence alloc] initWithData: finalData symbolSet: nil];
  [newSequence addAnnotation: d];
	[result addSequence: newSequence];
  [pool release];
#else
	BCSequence		*newSequence;
	NSMutableArray	*linesArray, *annotationsArray;
	BCSequenceArray	*result;
	NSString		*line, *sequenceString;
	int				i, j;

	linesArray = [entryString splitLines];
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	
	for (i = 0; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex: i];

		if ([line hasPrefix: @">"] )
		{
			[annotationsArray addObject: [BCAnnotation annotationWithName: @">" content: [line substringFromIndex: 1]]];		

			line = [linesArray objectAtIndex: ++i];

			sequenceString = @"";
		
		// until the next sequence
			while (![line hasPrefix:@">"] )
			{			
				sequenceString = [sequenceString stringByAppendingString: [line stringByRemovingWhitespace]];

				i++;
				
				if ( i < [linesArray count])
				{
					line = [linesArray objectAtIndex: i];
				}
				else
					break;
			}

		// we don't know what the sequence type is going to be, so we will let the
		// creation code figure that out
			newSequence = [BCSequence sequenceWithString: sequenceString];

			for (j = 0; j < [annotationsArray count]; j++)
			{
				[newSequence addAnnotation: [annotationsArray objectAtIndex:j]];
			}

			[result addSequence: newSequence];
			[annotationsArray removeAllObjects];

			i--;
		}
	}
#endif

	return result;
}


- (BCSequenceArray *) readSwissProtFile:(NSString *)entryString
{
// TODO: need to make a nested annotation for the reference entries

	NSString			*line, *sequenceString;
	NSMutableArray		*linesArray, *annotationsArray;
	BCSequenceArray		*result;
	BCSequence			*newSequence;
	int					i, j;
	
	linesArray = [entryString splitLines];
	annotationsArray = [NSMutableArray array];
	result = [[BCSequenceArray alloc] init];
	    
	for (i = 0; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex: i];

		if (![line hasPrefix:@"SQ"])
		{
			if ( ![line hasPrefix:@"XX"])
			{
				[annotationsArray addObject:[BCAnnotation annotationWithName: [line substringToIndex: 2] 
							content: [line substringFromIndex: 3]]];
			}
		}
		else
		{
		  // will extract the sequence here
			line = [linesArray objectAtIndex: ++i];
			sequenceString = @"";
					
			while (![line hasPrefix:@"//"] )
			{			
				sequenceString = [sequenceString stringByAppendingString:[line stringByRemovingWhitespace]];
				line = [linesArray objectAtIndex: ++i];
			}
		}
	}
	
	if ( [sequenceString length])
	{
	 // if it's an embl file it could be a dna or rna sequence,
	 // so don't set symbolset to protein, even though it's called the swiss prot format
	 
		newSequence = [BCSequence sequenceWithString: sequenceString];
		
		for (j = 0; j < [annotationsArray count]; j++)
		{
			[newSequence addAnnotation:[annotationsArray objectAtIndex:j]];
		}
		
		[result addSequence: newSequence];
		[annotationsArray removeAllObjects];
	}
	
	return result;
}


- (BCSequenceArray *)readPDBFile:(NSString *)entryString
{
	NSString			*line, *sequenceString;
	NSMutableArray	*linesArray, *annotationsArray;
	BCSequenceArray	*result;
	BCSequence			*newSequence;
	int					i, j;

	linesArray = [entryString splitLines];
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	
	sequenceString  = @"";
	
	for (i = 0; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex:i];

		if ( ![line hasPrefix:@"SEQRES"] )
		{
			[annotationsArray addObject:[BCAnnotation annotationWithName: [line substringToIndex: 10] 
				content: [line substringFromIndex: 11]]];		
		}
		else
        {
			sequenceString = [sequenceString stringByAppendingString:[line substringWithRange:NSMakeRange(19, 52)]];
        }
	}
	
	if ( [sequenceString length])
	{
		newSequence = [BCSequence sequenceWithThreeLetterString: sequenceString symbolSet: [BCSymbolSet proteinSymbolSet]];
	 
		for (j = 0; j < [annotationsArray count]; j++)
		{
			[newSequence addAnnotation:[annotationsArray objectAtIndex:j]];
		}
		
		[result addSequence: newSequence];
		[annotationsArray removeAllObjects];
	}
	
	return result;
}


- (BCSequenceArray *)readNCBIFile:(NSString *)entryString
{
	NSString		*line, *sequenceString;
	NSMutableArray	*linesArray, *annotationsArray;
	BCSequenceArray	*result;
	BCSequence		*newSequence;
	int				i, j;
	
	linesArray = [entryString splitLines];
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	
	sequenceString = @"";
	
	for (i = 0; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex:i];
		
		if (![line hasPrefix:@"ORIGIN"] )
		{		
			[annotationsArray addObject:[BCAnnotation annotationWithName: [line substringToIndex:10] 
				content: [line substringFromIndex:11]]];
		}
        else
		{
			line = [linesArray objectAtIndex: ++i];
			
			while (![line hasPrefix:@"//"] )
			{			
				sequenceString = [sequenceString stringByAppendingString:[[line substringFromIndex:10] stringByRemovingWhitespace]];
				line = [linesArray objectAtIndex: ++i];
			}

			if ( [sequenceString length])
			{
				newSequence = [BCSequence sequenceWithString: sequenceString];
				
				for (j = 0; j < [annotationsArray count]; j++)
				{
					[newSequence addAnnotation:[annotationsArray objectAtIndex:j]];
				}
				
				[result addSequence: newSequence];
				[annotationsArray removeAllObjects];
			}
        }
	}
	
	return result;
}

- (BCSequenceArray *)readStriderFile:(NSString *)textFile
{
/*
	Binary file format, read in header, determine features and sequence -> create dictionary.
*/
	STRIDER_HEADER *signature;
	
	BCSequence		*newSequence;
	BCSequenceArray	*result;
	NSString		*sequenceString;
	NSMutableArray	*annotationsArray;
	int				i;
	
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	sequenceString = @"";

	NSData *data  = [NSData dataWithContentsOfFile: textFile];

 // Memory alloc and read in struct
    signature = malloc(sizeof(STRIDER_HEADER));
    [data getBytes: signature length: sizeof(STRIDER_HEADER)];
	
 // Sequence
    NSData *seqdata = [data subdataWithRange: NSMakeRange(sizeof(STRIDER_HEADER), CFSwapInt32BigToHost(signature->nLength))];
    sequenceString = [sequenceString stringByAppendingString: [NSString stringWithBytes: [seqdata bytes] length: [seqdata length] encoding: NSASCIIStringEncoding]];
	[annotationsArray addObject: [BCAnnotation annotationWithName: @"name" content: [[textFile lastPathComponent]stringByDeletingPathExtension]]];		
	
 // Comments
    if(signature->com_length > 0)
	{
        NSData *comdata = [data subdataWithRange: NSMakeRange([data length] - CFSwapInt32BigToHost(signature->com_length), CFSwapInt32BigToHost(signature->com_length))];
		NSString *comments = [[NSString alloc] initWithBytes: [comdata bytes] length: [comdata length] encoding: NSASCIIStringEncoding];
		[annotationsArray addObject: [BCAnnotation annotationWithName: @"comments" content: comments]];		
		[comments release];
    }

	if ( [sequenceString length])
	{
		newSequence = [BCSequence sequenceWithString: sequenceString];
		
		for (i = 0; i < [annotationsArray count]; i++)
		{
			[newSequence addAnnotation: [annotationsArray objectAtIndex: i]];
		}
		
		[result addSequence: newSequence];
		[annotationsArray removeAllObjects];
	}    

 // Clean up
    free(signature);
    
    return result;
}



- (BCSequenceArray *)readGCKFile:(NSString *)textFile
{
/*
	Binary file format, read in header, determine features and sequence -> create dictionary.
	Same as DNA strider but comments are ignored
*/
 
	GCK_HEADER *signature;
	
	BCSequence		*newSequence;
	BCSequenceArray	*result;
	NSString		*sequenceString;
	NSMutableArray	*annotationsArray;
	int				i;
	
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	sequenceString = @"";
	
	NSData *data  = [NSData dataWithContentsOfFile: textFile];
	
 // Memory alloc and read in struct
    signature = malloc(sizeof(GCK_HEADER));
    [data getBytes: signature length: sizeof(GCK_HEADER)];
	
 // Sequence
    NSData *seqdata = [data subdataWithRange: NSMakeRange(sizeof(GCK_HEADER), CFSwapInt32BigToHost(signature->nLength))];
    sequenceString = [sequenceString stringByAppendingString: [NSString stringWithBytes: [seqdata bytes] length: [seqdata length] encoding: NSASCIIStringEncoding]];
	[annotationsArray addObject: [BCAnnotation annotationWithName: @"name" content: [[textFile lastPathComponent]stringByDeletingPathExtension]]];		
	
	if ( [sequenceString length])
	{
		newSequence = [BCSequence sequenceWithString: sequenceString];
		
		for (i = 0; i < [annotationsArray count]; i++)
		{
			[newSequence addAnnotation: [annotationsArray objectAtIndex: i]];
		}
		
		[result addSequence: newSequence];
		[annotationsArray removeAllObjects];
	}
    
 // Clean up
    free(signature);
    
    return result;
}

- (BCSequenceArray *)readMacVectorFile:(NSString *)textFile
{
	MACVECTOR_HEADER *signature;
	
	BCSequence		*newSequence;
	BCSequenceArray *result;
	NSMutableArray	*annotationsArray;
	NSString		*alphabet;
	unsigned char	*seqBuffer;
	int i, s;
	
	NSMutableString	*sequenceString = [NSMutableString string];
	
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	
	
	NSData *data = [NSData dataWithContentsOfFile: textFile];
	
	// get header data
	signature = malloc(sizeof(MACVECTOR_HEADER));
	[data getBytes: signature length: sizeof(MACVECTOR_HEADER)];
	
	/* 
		define the alphabet so that we can read proteins, DNA and RNA
		I'm not sure this is the most elegant way to do things...
		It works, anyway.
		Bytes in MacVector files corresponds to letters in alphabet
		The idea is to use the alphabet as an array so that 
		when one reads, say 0x02, has just to get character at index
		2 in the alphabet...
	 */
	
  if (signature->seqType)
	{
		// Protein
		alphabet = @"-ACDEFGHIKLMNPQRSTVWYB*X";
	}
	else if (signature->ntType == 1) 
	{
		// RNA, there are no T's, only U's
		alphabet = @"-ACMGRSVUWYHKDBN";
	}
	else 
	{
		// DNA
		alphabet = @"-ACMGRSVTWYHKDBN";
	}
	
	// get the length in a variable, so that we don't have to convert every time...
	s = CFSwapInt32BigToHost(signature->seqLength);
	
	// read the sequence into a data object
	NSData *seqdata = [data subdataWithRange:NSMakeRange(sizeof(MACVECTOR_HEADER),s)];

	//	Now I need to read the data bytes
	//seqBuffer = malloc(s);
	seqBuffer = (unsigned char *)[seqdata bytes];
	for (i = 0; i < s; i++)
	{
		//	append each character
		[sequenceString appendFormat:@"%c", [alphabet characterAtIndex:seqBuffer[i]]];
	}

	/* 
		What follows is copied from the method above, readGCKFile
		I've only commented lines that have to do with reading
		annotations.
	*/
	
	if ([sequenceString length])
	{
		newSequence = [BCSequence sequenceWithString: sequenceString];
		
		[result addSequence: newSequence];
	}
	
	free(signature);

	return result;
}


-(BCSequenceArray *)readClustalFile:(NSString *)entryString
{
/*
	The clustal format can have a sequence that is displayed over several lines, each starting with an identifier:

	CLUSTAL_FORMAT W(1.60) multiple sequence alignment


	JC2395          NVSDVNLNK---YIWRTAEKMK---ICDAKKFARQHKIPESKIDEIEHNSPQDAAE----
	KPEL_DROME      MAIRLLPLPVRAQLCAHLDAL-----DVWQQLATAVKLYPDQVEQISSQKQRGRS-----
	FASA_MOUSE      NASNLSLSK---YIPRIAEDMT---IQEAKKFARENNIKEGKIDEIMHDSIQDTAE----


	JC2395          -------------------------QKIQLLQCWYQSHGKT--GACQALIQGLRKANRCD
	KPEL_DROME      -------------------------ASNEFLNIWGGQYN----HTVQTLFALFKKLKLHN
	FASA_MOUSE      -------------------------QKVQLLLCWYQSHGKS--DAYQDLIKGLKKAECRR


	JC2395          IAEEIQAM
	KPEL_DROME      AMRLIKDY
	FASA_MOUSE      TLDKFQDM

	so the algorithm is:

	scan name, until space. scan sequencestring
	store name-sequence pair in a dictionary
	scan next line, if key exists, append string, otherwise, add new key-value pair

	If done, gone through dictionary, and extract the name and sequence
	make BCSequence, and add name as an attribute

	store BCSequence in array to return
*/

	int					i;
	NSString			*line, *name, *sequenceString, *tempString;
	NSMutableArray		*linesArray;
	NSScanner			*lineScanner;
	BCSequence			*newSequence;
	NSCharacterSet		*alignmentSet, *symbolSet;
	BCSequenceArray		*result;
	NSMutableDictionary	*sequenceDictionary;
	NSRange				sequenceRange;
	
	alignmentSet = [NSCharacterSet characterSetWithCharactersInString: @"*:."];
	symbolSet = [[NSCharacterSet whitespaceCharacterSet] invertedSet];	// or actually all BCSymbolSets!
	sequenceDictionary = [NSMutableDictionary dictionary];
	
	result = [[BCSequenceArray alloc] init];
	linesArray = [entryString splitLines];

 // remove empty lines
    for (i = [linesArray count] - 1; i >= 0 ; i--)
	{
        if ([[linesArray objectAtIndex: i] isEqualTo: @""])
		{
            [linesArray removeObjectAtIndex: i];
        }
    }

 // since this is an alignment, we need to determine where the first whitespace is that belongs to the sequence
 	
	for (i = 1; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex: i];
		
	 // we now have the first sequence line, let's determine where the sequence starts.
		
	 // first scan past the name
		lineScanner = [NSScanner scannerWithString: line];
		[lineScanner scanUpToString:@" " intoString: nil];
		
	 // put the left-over in a tempstring
		tempString = [line substringFromIndex: [lineScanner scanLocation]];
		
	 // now check where the first non-whitecharacter is
		sequenceRange = [tempString rangeOfCharacterFromSet: symbolSet];
		
	 // add the scanLocation - this is where the sequence starts
		sequenceRange.location += [lineScanner scanLocation];
		
	 // found it, no need to continue	
		break;
	}

	for (i = 1; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex:i];
		
	 // scan the name   
		lineScanner = [NSScanner scannerWithString: line];
		[lineScanner scanUpToString: @" " intoString: &name];
		
	 // the rest of the line after the whitespace is the sequence
		sequenceString = [line substringFromIndex: sequenceRange.location];
		
	 // make sure we actually have a string
		if ( [sequenceString length])
		{
			// if it's the alignment line, name it "alignment"
			if ( [sequenceString stringContainsCharactersFromSet: alignmentSet] )
			{
				name = [NSString stringWithString: @"alignment"];
			}
			
			if ( [sequenceDictionary objectForKey: name] )
			{
				tempString = (NSMutableString*)[[sequenceDictionary objectForKey: name]
								stringByAppendingString:sequenceString];
				
				[sequenceDictionary setObject: tempString forKey: name];				
			}
			else
			{
				[sequenceDictionary setObject: sequenceString forKey: name];				
			}
		}
	}

 // now replace the sequencestrings in the dictionary with BCSequenceObjects
	NSEnumerator *enumerator = [sequenceDictionary keyEnumerator];

	while ( (name = [enumerator nextObject]) )
	{
		sequenceString = [[sequenceDictionary objectForKey: name] stringByRemovingWhitespace];
		
		newSequence = [BCSequence sequenceWithString:sequenceString];
		[newSequence addAnnotation: [BCAnnotation annotationWithName: @"name" content: name]];
		
		[result addSequence: newSequence];
	}	

	return result;
}


-(BCSequenceArray *)readGDEFile:(NSString *)entryString
{
/*
	#sf170-A3

	atgggaccagagtctaaagccatgtgtaaagttaacccctctctgcgttactttaaattgtagccat-

	#br20-B1

	atgggatcaaagcctaaagccttgtgtaaagttaaccccactctgtgttactttaaattgcattgatttgaa
*/
	
	NSString		*line, *sequenceString;
	NSMutableArray	*linesArray, *annotationsArray;
	BCSequenceArray	*result;
	BCSequence		*newSequence;
	int				i, j;
	
	linesArray = [entryString splitLines];
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	
	sequenceString = @"";
	
 // remove empty lines
    for (i = [linesArray count] - 1; i >= 0 ; i--)
	{
        if ([[linesArray objectAtIndex: i] isEqualTo: @""])
		{
            [linesArray removeObjectAtIndex: i];
        }
    }

	for (i = 0; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex:i];

		if ([line hasPrefix: @"#"] )
		{
			[annotationsArray addObject:[BCAnnotation annotationWithName: @"name" content: line]];
			
			line = [linesArray objectAtIndex: ++i];

			sequenceString = @"";
			
			// until the next sequence
			while (![line hasPrefix: @"#"] )
			{
				sequenceString = [sequenceString stringByAppendingString: [line stringByRemovingWhitespace]];
				
				i++;
				
				if ( i < [linesArray count])
				{
					line = [linesArray objectAtIndex: i];
				}
				else
					break;
			}
				
			// we don't know what the sequence type is going to be, so we will let the
			// creation code figure that out
			newSequence = [BCSequence sequenceWithString: sequenceString];
			
			for (j = 0; j < [annotationsArray count]; j++)
			{
				[newSequence addAnnotation: [annotationsArray objectAtIndex:j]];
			}
			
			[result addSequence: newSequence];
			[annotationsArray removeAllObjects];
			
			i--;
		}
	}
	
	return result;
}

-(BCSequenceArray *)readPirFile:(NSString *)entryString
{
/*
	>P1;CRAB_ANAPL
	ALPHA CRYSTALLIN B CHAIN (ALPHA(B)-CRYSTALLIN).
	MDITIHNPLI RRPLFSWLAP SRIFDQIFGE HLQESELLPA SPSLSPFLMR 
	SPIFRMPSWL ETGLSEMRLE KDKFSVNLDV KHFSPEELKV KVLGDMVEIH 
	GKHEERQDEH GFIAREFNRK YRIPADVDPL TITSSLSLDG VLTVSAPRKQ 
	SDVPERSIPI TREEKPAIAG AQRK*

	>P1;CRAB_BOVIN
	ALPHA CRYSTALLIN B CHAIN (ALPHA(B)-CRYSTALLIN).
	MDIAIHHPWI RRPFFPFHSP SRLFDQFFGE HLLESDLFPA STSLSPFYLR 
	PPSFLRAPSW IDTGLSEMRL EKDRFSVNLD VKHFSPEELK VKVLGDVIEV 
	HGKHEERQDE HGFISREFHR KYRIPADVDP LAITSSLSSD GVLTVNGPRK 
	QASGPERTIP ITREEKPAVT AAPKK*
*/
 
	NSString		*line, *sequenceString;
	NSMutableArray	*linesArray, *annotationsArray;
	BCSequenceArray	*result;
	BCSequence		*newSequence;
	int				i, j;
	
	linesArray = [entryString splitLines];
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	
	sequenceString = @"";
	
 // remove empty lines
    for (i = [linesArray count] - 1; i >= 0 ; i--)
	{
        if ([[linesArray objectAtIndex: i] isEqualTo: @""])
		{
            [linesArray removeObjectAtIndex: i];
        }
    }

	for (i = 0; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex: i];
		
		if ([line hasPrefix: @">"] )
		{
			[annotationsArray addObject:[BCAnnotation annotationWithName: @"name" content: [line substringFromIndex: 4]]];
			line = [linesArray objectAtIndex: ++i];
			
			[annotationsArray addObject:[BCAnnotation annotationWithName: @"description" content: line]];
			line = [linesArray objectAtIndex: ++i];

			sequenceString = @"";
			
		 // until the next sequence
			while (![line hasPrefix: @">"] )
			{
				if ( [line hasSuffix: @"*"])
				{
					line = [line stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"*"]];
				}
				
				sequenceString = [sequenceString stringByAppendingString: [line stringByRemovingWhitespace]];
				
				i++;
				
				if ( i < [linesArray count])
				{
					line = [linesArray objectAtIndex: i];
				}
				else
					break;
			} 
			
		 // we don't know what the sequence type is going to be, so we will let the
		 // creation code figure that out
			newSequence = [BCSequence sequenceWithString: sequenceString];
						
			for (j = 0; j < [annotationsArray count]; j++)
			{
				[newSequence addAnnotation: [annotationsArray objectAtIndex:j]];
			}
			
			[result addSequence: newSequence];
			[annotationsArray removeAllObjects];

			i--;
		}
	}
	
	return result;
}


-(BCSequenceArray *)readMSFFile:(NSString *)entryString
{
/*
	msf formatted multiple sequence files are most often created when using programs of the GCG suite. 
	msf files include the sequence name and the sequence itself, which is usually aligned with other sequences in the file.
	You can specify a single sequence or many sequences within an msf file.

	An example of part of an msf file, created using the GCG multiple sequence alignment program:

	!!AA_MULTIPLE_ALIGNMENT 1.0
	PileUp of: @hsp70.list

	Symbol comparison table: GenRunData:blosum62.cmp CompCheck: 6430

	GapWeight: 8
	GapLengthWeight: 2

	hsp70.msf MSF: 743 Type: P October 6, 1998 18:23 Check: 7784 ..

	Name: S11448 Len: 743 Check: 3635 Weight: 1.00
	Name: S06443 Len: 743 Check: 5861 Weight: 1.00
	Name: S29261 Len: 743 Check: 7748 Weight: 1.00

	//

	1                                                   50
	S11448 ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~MTFD GAIGIDLGTT YSCVGVWQNE
	S06443 ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~MTFD GAIGIDLGTT YSCVGVWQNE
	S29261 ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~MG KIIGIDLGTT NSCVAIMDGT

	Some of the hallmarks of a msf formatted sequence are the same as a single sequence gcg format file:

	Begins with the line (all uppercase) !!NA_MULTIPLE_ALIGNMENT 1.0 for nucleic acid sequences or !!AA_MULTIPLE_ALIGNMENT 1.0 for amino acid sequences. 
	Do not edit or delete the file type if its present.(optional)
	A description line which contains informative text describing what is in the file. 
	You can add this information to the top of the MSF file using a text editor.(optional)
	A dividing line which contains the number of bases or residues in the sequence, when the file was created, and importantly, two dots (..) 
	which act as a divider between the descriptive information and the following sequence information.(required)

	msf files contain some other information as well:

	Name/Weight: The name of each sequence included in the alignment, as well as its length and checksum (both non-editable) and weight (editable).(required)
	Separating Line. Must include two slashes (//) to divide the name/weight information from the sequence alignment.(required)
	Multiple Sequence Alignment. Each sequence named in the above Name/Weight lines is included. The alignment allows you to view the relationship among sequences. 
											
*/											

	BCSequenceArray	*result = nil;
	
	return result;
}


-(BCSequenceArray *)readPhylipFile:(NSString *)entryString
{
/*
	The first line of the input file contains the number of species and the number of characters separated by blanks. 
	The information for each species follows, starting with a ten-character species name (which can include punctuation marks and blanks), 
	and continuing with the characters for that species. 
	Phylip format files can be interleaved, as in the example below, or sequential.
	More information about phylip format is available from the authors at University of Washington. An example phylip format file:
 
	5 100
	Rabbit    ?????????? ?????????C CAATCTACAC ACGGG-GTAG GGATTACATA
	Human     AGCCACACCC TAGGGTTGGC CAATCTACTC CCAGGAGCAG GGAGGGCAGG
	Opossum   AGCCACACCC CAACCTTAGC CAATAGACAT CCAGAAGCCC AAAAGGCAAG
	Chicken   GCCCGGGGAA GAGGAGGGGC CCGGCGG-AG GCGATAAAAG TGGGGACACA
	Frog      GGATGGAGAA TTAGAGCACT TGTTCTTTTT GCAGAAGCTC AGAATAAACG

	TTTGGATGGT AG---GATAT GGGCCTACCA TGGCGTTAAC GGGT-AACGY
	TTTCGACGGT AA---GGTAT TGGCTTACCG TGGCAATGAC AGGT-GACGG
	TTTCGACGGT AA---GGTAT TGGCTTACCG TGGCAATGAC AGGT-GACGY
	TTTCGACGGT AA---GGTAT TGGCTTACCG TGGCAATGAC AGGT-GACGG
	TTTCGATGGT AA---GGTAT TGGCTTACCG TGGCAATGAC AGGT-GACGG
*/
 	 
	NSString		*line, *sequenceString, *firstLine;
	NSMutableArray	*linesArray, *annotationsArray, *namesArray, *sequenceArray;
	NSScanner		*lineScanner;
	BCSequenceArray	*result;
	BCSequence		*newSequence;
	int				i, j, numSequences, sequenceIndex;	

	linesArray = [entryString splitLines];
	result = [[BCSequenceArray alloc] init];
	annotationsArray = [NSMutableArray array];
	namesArray = [NSMutableArray array];
	sequenceArray = [NSMutableArray array];
	
	sequenceString = @"";
	
 // remove empty lines
    for (i = [linesArray count] - 1; i >= 0 ; i--)
	{
        if ([[linesArray objectAtIndex: i] isEqualTo: @""])
		{
            [linesArray removeObjectAtIndex: i];
        }
    }
	
	firstLine = [linesArray objectAtIndex: 0];
	lineScanner = [NSScanner scannerWithString: firstLine];
	[lineScanner scanInt: &numSequences];
	
	j = 0;
	
	for ( i = 1; i < [linesArray count]; i++)
	{		
		if ( i <= numSequences )
		{
			line = [linesArray objectAtIndex: i];
			
			[namesArray	addObject: [line substringToIndex: 9]];
			[sequenceArray addObject: [[line substringFromIndex: 10] stringByRemovingWhitespace]];
		}
		else
		{
			line = [linesArray objectAtIndex: i];

			sequenceIndex = i - ( j * numSequences ) - 1;
			sequenceString = [sequenceArray objectAtIndex: sequenceIndex];
			sequenceString = [sequenceString stringByAppendingString: [line stringByRemovingWhitespace]];
			[sequenceArray replaceObjectAtIndex: sequenceIndex withObject: sequenceString];
		}

		if ( i % numSequences == 0 )
		{
			j++;
		}
	}

 // finally, populate the BCSequenceArray	
	for (i = 0; i < numSequences; i++)
	{
		newSequence = [BCSequence sequenceWithString: (NSString *)[sequenceArray objectAtIndex: i]];
		[newSequence addAnnotation: [BCAnnotation annotationWithName: @"name" content: (NSString *)[namesArray objectAtIndex: i]]];
		
		[result addSequence: newSequence];
	}
	
	return result;
}

- (BCSequenceArray *)readRawFile:(NSString *)entryString
 {
	NSString		*line, *sequenceString;
	NSMutableArray	*linesArray;
	BCSequenceArray	*result;
	BCSequence		*newSequence;
	int				i;	

	linesArray = [entryString splitLines];
	result = [[BCSequenceArray alloc] init];

	sequenceString = @"";

	// remove empty lines
	for (i = [linesArray count] - 1; i >= 0 ; i--)
	{
		if ([[linesArray objectAtIndex: i] isEqualTo: @""])
		{
			[linesArray removeObjectAtIndex: i];
		}
	}

	for (i = 1; i < [linesArray count]; i++)
	{
		line = [linesArray objectAtIndex: i];
		sequenceString = [sequenceString stringByAppendingString: [line stringByRemovingWhitespace]];
	}

	newSequence = [BCSequence sequenceWithString: sequenceString];
	[result addSequence: newSequence];

	return result;
}

/*
	FASTQ format, sequence and Phred qualities

	Here is format information from the following web site:

	http://maq.sourceforge.net/fastq.shtml

	Example

@EAS54_6_R1_2_1_413_324
CCCTTCTTGTCTTCAGCGTTTCTCC
+
;;3;;;;;;;;;;;;7;;;;;;;88
@EAS54_6_R1_2_1_540_792
TTGGCAGGCCAAGGCCGATGGATCA
+
;;;;;;;;;;;7;;;;;-;;;3;83
@EAS54_6_R1_2_1_443_348
GTTGCTTCTGGCGTGGGTGGGGGGG
+EAS54_6_R1_2_1_443_348
;;;;;;;;;;;9;7;;.7;393333
  
	FASTQ Format Specification

	Notations

	<fastq>, <blocks> and so on represents non-terminal symbols.
	Characters in red are regex-like operators.
	'\n' stands for the Return key.

	Syntax

	<fastq>	:=	<block>+
	<block>	:=	@<seqname>\n<seq>\n+[<seqname>]\n<qual>\n
	<seqname>	:=	[A-Za-z0-9_.:-]+
	<seq>	:=	[A-Za-z\n\.~]+
	<qual>	:=	[!-~\n]+

	Requirements

	* The <seqname> following '+' is optional, but if it appears right after '+',
	it should be identical to the <seqname> following '@'.

	* The length of <seq> is identical the length of <qual>. Each character in <qual> represents
	the phred quality of the corresponding nucleotide in <seq>.

	* If the Phred quality is $Q, which is a non-negative integer, the corresponding quality
	character can be calculated with the following Perl code:
		$q = chr(($Q<=93? $Q : 93) + 33);
	where chr() is the Perl function to convert an integer to a character based on the ASCII table.

	* Conversely, given a character $q, the corresponding Phred quality can be calculated with:
		$Q = ord($q) - 33;
	where ord() gives the ASCII code of a character.

	Solexa/Illumina Read Format

	The syntax of Solexa/Illumina read format is almost identical to the FASTQ format, but the
	qualities are scaled differently. Given a character $sq, the following Perl code gives the Phred quality $Q:

		$Q = 10 * log(1 + 10 ** (ord($sq) - 64) / 10.0)) / log(10);

*/

- (BCSequenceArray *) readFASTQFile:(NSString *)entryString
{
	BCSequenceArray	*result;
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	result = [[BCSequenceArray alloc] init];
	
	NSUInteger start, end, next; 
	NSRange range; 
	BCAnnotation *identity = nil;
	BCAnnotation *quality = nil;
	NSData *seqData;
	unsigned stringLength = [entryString length]; 
	BOOL readingHeader = YES;
	BOOL readingSequence = NO;

	range.location = 0; 
	range.length = 1;
	do { 
		[entryString getLineStart:&start end:&next contentsEnd:&end forRange:range]; 
		
		range.location = start; 
		range.length = end-start; 

		// Have to differentiate between looking for header lines because the
		// quality segments can start with the 
		if (readingHeader) {

			if ([entryString characterAtIndex: start] == '@') {
				// FASTQ sequences header

				// save the previous sequence that just ended
				if (identity) {
					BCSequence *newSequence = [[BCSequence alloc] initWithData: seqData symbolSet: nil];
					[newSequence addAnnotation: identity];
					[newSequence addAnnotation: quality];
					[result addSequence: newSequence];
				}
			
				// FASTQ header annotation
				++range.location;
				--range.length;
				identity = [BCAnnotation annotationWithName: BCAnnotationIdentity
					content: [entryString substringWithRange: range]];

				readingHeader = NO;
				readingSequence = YES;
			}

			if ([entryString characterAtIndex: start] == '+') {
				// FASTQ quality header
				readingHeader = NO;
				readingSequence = NO;
			}

		} else {

			if (readingSequence) {
				// sequence segment
				seqData = [[entryString substringWithRange: range] dataUsingEncoding: NSUTF8StringEncoding];
				//printf("%s\n", [seqData bytes]);
				readingHeader = YES;
			} else {
				// quality segment
				quality = [BCAnnotation annotationWithName: @"quality"
					content: [entryString substringWithRange: range]];
				//printf("%s\n", [[entryString substringWithRange: range] UTF8String]);
				readingHeader = YES;
			}
		}

		range.location = next; 
		range.length = 1; 
	} while (next < stringLength); 
	
	// save the last sequence
	BCSequence *newSequence = [[BCSequence alloc] initWithData: seqData symbolSet: nil];
	[newSequence addAnnotation: identity];
	[newSequence addAnnotation: quality];
	[result addSequence: newSequence];

	[pool release];
	
	return result;
}



// TO BE CONVERTED TO BCSEQUENCEARRAY FORMAT:
/*
 
 - (NSDictionary *)readNexusFile:(NSString *)textFile
 {
	 Nexus interleaved format, also known as PAUP format is the default output for the PAUP suite of phylogeny programs 
	 and is designed to represent DNA sequence only. 
	 The entry is headed by the #NEXUS comment line followed on the next line by the application and creation date. 
	 There is a blank line between this information and the start of the sequence data including the number of sequences 
	 (in this case 1), length, datatype and representation on missing bases (n) and gaps (-). 
	 Each of these information lines is ended with a semi-colon (;). 
	 A further blank line separates this information from the matrix comment. 
	 The sequence is represented on the succeeding lines starting with the sequence identifier and a block of 50 bases. 
	 The end of the sequence is denoted by a semi-colon (;). There follows a blank line and further comment lines ending with a semi-colon (;).
	
	#NEXUS
		 [TITLE: Written by EMBOSS 28/06/04]
		 
		 begin data;
		 dimensions ntax=1 nchar=450;
		 format interleave datatype=DNA missing=N gap=-;
		 
		 matrix
			 BT006818             atggctgatcagctgaccgaagaacagattgctgaattcaaggaagcctt
			 
			 BT006818             ctccctatttgataaagatggcgatggcaccatcacaacaaaggaacttg
			 
			 BT006818             gaactgtcatgaggtcactgggtcagaacccaacagaagctgaattgcag
			 
			 BT006818             gatatgatcaatgaagtggatgctgatggtaatggcaccattgacttccc
			 
			 BT006818             cgaatttttgactatgatggctagaaaaatgaaagatacagatagtgaag
			 
			 BT006818             aagaaatccgtgaggcattccgagtctttgacaaggatggcaatggttat
			 
			 BT006818             atcagtgcagcagaactacgtcacgtcatgacaaacttaggagaaaaact
			 
			 BT006818             aacagatgaagaagtagatgaaatgatcagagaagcagatattgatggag
			 
			 BT006818             acggacaagtcaactatgaagaattcgtacagatgatgactgcaaaatag
			 ;
		 
		 end;
		 begin assumptions;
		 options deftype=unord;
		 end;
		 
	int i;
	 NSScanner *matrixScanner, *itemScanner, *commentScanner, *treeScanner;
	 NSString *comments = @"";
	 NSString *treeString = @"";
	 NSString *stringWithMacLineBreaks;
	 NSMutableString *item, *sequence, *tempSequence, *matrix, *bracketsString;
	 NSMutableArray *linesArray, *bracketsArray;
	 NSMutableDictionary *matrixDictionary = [NSMutableDictionary dictionary];
	 NSMutableDictionary *nexusDictionary = [NSMutableDictionary dictionary];
	 NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:10];
	 NSMutableArray *treesArray = [NSMutableArray arrayWithCapacity:10];
	 
	 //Extract the Nexus file's main comments
	 commentScanner = [[NSScanner alloc] initWithString:textFile];
	 [commentScanner scanUpToString:@"[!" intoString:nil];
	 [commentScanner scanString:@"[!" intoString:nil];
	 [commentScanner scanUpToString:@"]" intoString:&comments];
	 [commentScanner release];
	 //Put the comments in the nexusDictionary
	 if (![comments isEqualTo:@""]) {
		 [nexusDictionary setObject:comments forKey:@"comments"];
	 }
	 
	 
	 //Check whether a treeblock exists and extract it
	 if ([textFile rangeOfString:@"begin trees;" options:NSCaseInsensitiveSearch||NSBackwardsSearch].length != 0) {
		 treeScanner = [[NSScanner alloc] initWithString:textFile];
		 [treeScanner scanUpToString:@"begin trees;" intoString:nil];
		 [treeScanner scanString:@"begin trees;" intoString:nil];
		 [treeScanner scanUpToString:@"end;" intoString:&treeString];
		 [treeScanner release];
		 treesArray = [NSMutableArray arrayWithArray:[treeString componentsSeparatedByString:@";"]];
		 //Put the trees in the treesArray
		 if ([treesArray count] > 0) {
			 [treesArray removeObjectAtIndex:0];
			 [treesArray removeObjectAtIndex:[treesArray count]-1];
			 //NSLog(@"%@", treesArray);
			 [nexusDictionary setObject:treesArray forKey:@"trees"];
		 }
	 }
	 
	 
	 //Remove other comments (in sequences) between the []
	 bracketsString = [NSMutableString stringWithString:textFile];
	 [bracketsString replaceOccurrencesOfString:@"[" withString:@"!!!*" options:NULL range:NSMakeRange(0, [bracketsString length])];
	 [bracketsString replaceOccurrencesOfString:@"]" withString:@"!!!" options:NULL range:NSMakeRange(0, [bracketsString length])];
	 bracketsArray = (NSMutableArray *)[bracketsString componentsSeparatedByString:@"!!!"];
	 for (i = 0; i < [bracketsArray count]; i++) {
		 if ([[bracketsArray objectAtIndex:i]hasPrefix:@"*"]){
			 [bracketsArray removeObjectAtIndex:i];
		 }
	 }
	 matrix = (NSMutableString *)[bracketsArray componentsJoinedByString:@""];
	 
	 
	 //Isolate the matrix
	 matrixScanner = [[NSScanner alloc] initWithString:matrix];
	 [matrixScanner scanUpToString:@"matrix" intoString:nil];
	 [matrixScanner scanUpToString:@";" intoString:&matrix];
	 [matrixScanner release];
	 
	 
	 //Convert all line breaks to Mac line breaks (\r)
	 stringWithMacLineBreaks = [self convertLineBreaksToMac:matrix];
	 //Isolate individual lines based on \r
	 linesArray = (NSMutableArray *)[stringWithMacLineBreaks componentsSeparatedByString:@"\r"];
	 
	 
	 //Trim lines from surrounding whitespaces and remove empty lines
	 for (i = 0; i < [linesArray count]; i++) {
		 [linesArray insertObject:[[linesArray objectAtIndex:i]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] atIndex:i];
		 [linesArray removeObjectAtIndex:i+1];
		 if ([[linesArray objectAtIndex:i]isEqualTo:@""]) {
			 [linesArray removeObjectAtIndex:i];
			 i--;
		 }
	 }
	 
	 
	 //Read item names and sequences and put them in the matrixDictionary
	 for (i = 1; i < [linesArray count]; i++) {
		 itemScanner = [[NSScanner alloc] initWithString:[linesArray objectAtIndex:i]];
		 [itemScanner scanUpToString:@" " intoString:&item];
		 sequence = (NSMutableString *)[[linesArray objectAtIndex:i]substringFromIndex:[itemScanner scanLocation]];
		 
		 if ([matrixDictionary objectForKey:item]) {	//If the item already exists
			 tempSequence = [NSMutableString stringWithString:[[matrixDictionary objectForKey:item] stringByAppendingString:sequence]];
			 [matrixDictionary setObject:tempSequence forKey:item];
			 
		 }
		 else {						//If the item does not yet exist
			 [matrixDictionary setObject:sequence forKey:item];
			 [itemArray addObject:item]; //Put the item name in the itemArray
		 }
		 [itemScanner release];
	 }
	 
	 
	 //Remove spaces and tabs from the sequences in the matrixDictionary
	 for (i = 0; i < [itemArray count]; i++) {
		 tempSequence = [NSMutableString stringWithString:[matrixDictionary objectForKey:[itemArray objectAtIndex:i]]];
		 [tempSequence replaceOccurrencesOfString:@" " withString:@"" options:NULL range:NSMakeRange(0, [tempSequence length])];
		 [tempSequence replaceOccurrencesOfString:@"\t" withString:@"" options:NULL range:NSMakeRange(0, [tempSequence length])];
		 [matrixDictionary setObject:tempSequence forKey:[itemArray objectAtIndex:i]];
	 }
	 
	 //Put the matrixDictionary and the items Array in the nexusDictionary
	 [nexusDictionary setObject:matrixDictionary forKey:@"matrix"];
	 [nexusDictionary setObject:itemArray forKey:@"items"];
	 [nexusDictionary setObject:@"nexus" forKey:@"fileType"];
	 
	 return nexusDictionary;
 }
 
 
 - (NSDictionary *)readNexusFileAndBlocks:(NSString *)textFile
 {
	 int i;
	 NSMutableDictionary *dict;
	 NSScanner *scanner;
	 NSArray *blocksArray;
	 NSString *blockName, *blockContents;
	 NSMutableDictionary *blocksDictionary = [NSMutableDictionary dictionary];
	 dict = (NSMutableDictionary*)[self readNexusFile:textFile];
	 
	 //Separate every block
	 blocksArray = [textFile componentsSeparatedByString:@"BEGIN "];
	 //Use the block name as the key and the contents as the value
	 for (i = 1; i < [blocksArray count]; i++) {
		 scanner = [[NSScanner alloc] initWithString:[blocksArray objectAtIndex:i]];
		 [scanner scanUpToString:@";" intoString:&blockName];
		 [scanner scanUpToString:@"end;" intoString:&blockContents];
		 [scanner release];
		 [blocksDictionary setObject:blockContents forKey:blockName];
	 }
	 [dict setObject:blocksDictionary forKey:@"blocks"];
	 return dict;
 }

 - (NSDictionary *)readNonaFile:(NSString *)textFile
 {
	 int i, j;
	 NSScanner *itemScanner;
	 NSString *stringWithMacLineBreaks;
	 NSMutableString *item, *sequence, *tempSequence;
	 NSMutableArray *linesArray;
	 NSMutableDictionary *matrixDictionary = [NSMutableDictionary dictionary];
	 NSMutableDictionary *phylipDictionary = [NSMutableDictionary dictionary];
	 NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:10];
	 j = 0;
	 
	 //Convert all line breaks to Mac line breaks (\r)
	 stringWithMacLineBreaks = [self convertLineBreaksToMac:textFile];
	 //Isolate individual lines based on \r
	 linesArray = (NSMutableArray*)[stringWithMacLineBreaks componentsSeparatedByString:@"\r"];
	 
	 //Remove empty lines
	 for (i = 0; i < [linesArray count]; i++) {
		 NSString *string = [linesArray objectAtIndex:i];
		 if ((![string stringContainsOneSpace] && [string length] < 20) || [string isEqualToString:@""] || [string stringBeginsWithTwoNumbers] || [string stringContainsHyphen]) {
			 [linesArray removeObjectAtIndex:i];
			 i--;
		 }
	 }
	 
	 //Read item names and sequences and put them in the matrixDictionary.
	 for (i = 0; i < [linesArray count]; i++) {
		 
		 if ([[linesArray objectAtIndex:i] hasPrefix:@" "]) {	//If the item name is not present
			 sequence = [linesArray objectAtIndex:i];
			 tempSequence = (NSMutableString*)[[matrixDictionary objectForKey:[itemArray objectAtIndex:j]] stringByAppendingString:sequence];
			 [matrixDictionary setObject:tempSequence forKey:[itemArray objectAtIndex:j]];
			 j++;
			 
			 if (j == [itemArray count]) { j = 0;}
		 }
		 else {							//If the item name precedes the sequence
			 itemScanner = [[NSScanner alloc] initWithString:[linesArray objectAtIndex:i]];
			 [itemScanner scanUpToString:@" " intoString:&item];
			 sequence = (NSMutableString*)[[linesArray objectAtIndex:i]substringFromIndex:[itemScanner scanLocation]];
			 [matrixDictionary setObject:sequence forKey:item];
			 [itemArray addObject:item];
			 //NSLog(@"Adding item %@", item);
			 [itemScanner release];
		 }
	 }
	 
	 //Remove spaces and tabs from the sequences in the matrixDictionary
	 for (i = 0; i < [itemArray count]; i++) {
		 tempSequence = [NSMutableString stringWithString:[matrixDictionary objectForKey:[itemArray objectAtIndex:i]]];
		 [tempSequence replaceOccurrencesOfString:@" " withString:@"" options:(unsigned)NULL range:NSMakeRange(0, [tempSequence length])];
		 [tempSequence replaceOccurrencesOfString:@"\t" withString:@"" options:(unsigned)NULL range:NSMakeRange(0, [tempSequence length])];
		 [matrixDictionary setObject:tempSequence forKey:[itemArray objectAtIndex:i]];
	 }
	 
	 //Put the matrixDictionary and the items Array in the nonaDictionary
	 [phylipDictionary setObject:matrixDictionary forKey:@"matrix"];
	 [phylipDictionary setObject:itemArray forKey:@"items"];
	 [phylipDictionary setObject:@"Nona" forKey:@"fileType"];
	 
	 return phylipDictionary;
 }
 
 
 - (NSDictionary *)readHennigFile:(NSString *)textFile
 {

 Designed for DNA data, the Hennig86 format translates each base into a number where A = 0; T = 1; G = 2; C =3. 
 The start is denoted by the comment xread and is followed on a separate line
 by the application and creation date of the file enclosed in single quotes separated from the text by whitespace. 
 A separate line records the sequence length and number of sequence files represented (in this case 1). 
 Immediately below this line is the identifier line and below this the sequence in numerical form. 
 The end of the entry is denoted by a semi-colon (;). The entire sequence is displayed on a single line.
 
 xread
 ' Written by EMBOSS 28/06/04 '
 450 1
 BT006818
 012231201302312033200200302011231200113002200233113133310111201000201223201223033013030030002200311220031213012022130312221302003330030200231200112302201012013001200212201231201221001223033011203113333200111112031012012231020000012000201030201021200200200013321202230113320213111203002201223001221101013021230230200310321303213012030003110220200000310030201200200210201200012013020200230201011201220203220300213003101200200113210302012012031230000102
 ;

	 int i, j;
	 NSScanner *itemScanner;
	 NSString *stringWithMacLineBreaks;
	 NSMutableString *item, *sequence, *tempSequence;
	 NSMutableArray *linesArray;
	 NSMutableDictionary *matrixDictionary = [NSMutableDictionary dictionary];
	 NSMutableDictionary *phylipDictionary = [NSMutableDictionary dictionary];
	 NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:10];
	 j = 0;
	 
	 //Convert all line breaks to Mac line breaks (\r)
	 stringWithMacLineBreaks = [self convertLineBreaksToMac:textFile];
	 //Isolate individual lines based on \r
	 linesArray = (NSMutableArray*)[stringWithMacLineBreaks componentsSeparatedByString:@"\r"];
	 
	 //Remove empty lines
	 for (i = 0; i < [linesArray count]; i++) {
		 NSString *string = [linesArray objectAtIndex:i];
		 if ((![string stringContainsOneSpace] && [string length] < 20) || [string isEqualToString:@""] || [string stringBeginsWithTwoNumbers] || [string stringContainsHyphen]) {
			 [linesArray removeObjectAtIndex:i];
			 i--;
		 }
	 }
	 
	 //Read item names and sequences and put them in the matrixDictionary.
	 for (i = 0; i < [linesArray count]; i++) {
		 
		 if ([[linesArray objectAtIndex:i] hasPrefix:@" "]) {	//If the item name is not present
			 sequence = [linesArray objectAtIndex:i];
			 tempSequence = (NSMutableString*)[[matrixDictionary objectForKey:[itemArray objectAtIndex:j]] stringByAppendingString:sequence];
			 [matrixDictionary setObject:tempSequence forKey:[itemArray objectAtIndex:j]];
			 j++;
			 
			 if (j == [itemArray count]) { j = 0;}
		 }
		 else {							//If the item name precedes the sequence
			 itemScanner = [[NSScanner alloc] initWithString:[linesArray objectAtIndex:i]];
			 [itemScanner scanUpToString:@" " intoString:&item];
			 sequence = (NSMutableString*)[[linesArray objectAtIndex:i]substringFromIndex:[itemScanner scanLocation]];
			 [matrixDictionary setObject:sequence forKey:item];
			 [itemArray addObject:item];
			 //NSLog(@"Adding item %@", item);
			 [itemScanner release];
		 }
	 }
	 
	 //Remove spaces and tabs from the sequences in the matrixDictionary
	 for (i = 0; i < [itemArray count]; i++) {
		 tempSequence = [NSMutableString stringWithString:[matrixDictionary objectForKey:[itemArray objectAtIndex:i]]];
		 [tempSequence replaceOccurrencesOfString:@" " withString:@"" options:(unsigned)NULL range:NSMakeRange(0, [tempSequence length])];
		 [tempSequence replaceOccurrencesOfString:@"\t" withString:@"" options:(unsigned)NULL range:NSMakeRange(0, [tempSequence length])];
		 [matrixDictionary setObject:tempSequence forKey:[itemArray objectAtIndex:i]];
	 }
	 
	 //Put the matrixDictionary and the items Array in the nonaDictionary
	 [phylipDictionary setObject:matrixDictionary forKey:@"matrix"];
	 [phylipDictionary setObject:itemArray forKey:@"items"];
	 [phylipDictionary setObject:@"Hennig86" forKey:@"fileType"];
	 
	 return phylipDictionary;
 }
*/ 

@end