1306579f0d9cd174391bae9474329cf2d0612af5
[SXSI/TextCollection.git] / incbwt / utils / extract_text.cpp
1 #include <cstdlib>
2 #include <fstream>
3 #include <iostream>
4
5 #include "../misc/definitions.h"
6
7
8 using namespace CSA;
9
10
11 std::string gapChars = " =-_";
12
13 void
14 concatenateStrain(std::string &text, std::ifstream &file, usint strain)
15 {
16   file.clear();
17   file.seekg(0, std::ios::beg);
18
19   std::string line;
20   while(!file.eof())
21   {
22     getline(file, line);
23     if(line.empty() || line[0] == '>') { continue; }
24     char t = toupper(line[strain * 2]);
25     if(gapChars.find(t) == std::string::npos) { text.push_back(t); }
26   }
27 }
28
29
30 int
31 main(int argc, char** argv)
32 {
33   std::cout << "Extracting concatenated text from alignment" << std::endl;
34   if(argc < 3)
35   {
36     std::cout << "Usage: extract_text alignment_file output_file" << std::endl;
37     return 1;
38   }
39
40   std::cout << "Alignment file: " << argv[1] << std::endl;
41   std::ifstream alignment_file(argv[1], std::ios_base::binary);
42   if(!alignment_file)
43   {
44     std::cerr << "Error opening alignment file!" << std::endl;
45     return 2;
46   }
47
48   std::cout << "Output file: " << argv[2] << std::endl;
49   std::ofstream output_file(argv[2], std::ios_base::binary);
50   if(!output_file)
51   {
52     std::cerr << "Error creating output file!" << std::endl;
53     return 3;
54   }
55   std::cout << std::endl;
56
57   std::string line;
58   std::getline(alignment_file, line); // Skipping header line.
59   std::getline(alignment_file, line);
60   usint strains = line.size() / 2 - 1;
61   std::cout << "Number of strains: " << strains << std::endl;
62
63   line.clear();
64   concatenateStrain(line, alignment_file, 0);
65   usint n = line.size();
66   std::cout << "Reference sequence length: " << n << std::endl;
67
68   for(usint i = 1; i <= strains; i++)
69   {
70     concatenateStrain(line, alignment_file, i);
71   }
72   usint N = line.size() + 1;
73   std::cout << "Total length: " << N << std::endl;
74
75   output_file.write(line.c_str(), N - 1);
76   char end = '\0';
77   output_file.write(&end, 1);
78
79   output_file.close();
80   alignment_file.close();
81   return 0;
82 }