ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/fqtrim/fqtrim.cpp
(Generate patch)
# Line 2 | Line 2
2   #include "GStr.h"
3   #include "GHash.hh"
4   #include "GList.hh"
5 + #include <ctype.h>
6 + #include "GAlnExtend.h"
7  
8   #define USAGE "Usage:\n\
9 < fqtrim [-5 <5'adapter>] [-3 <3'adapter>] [-l <minlen>] [-q <minqv>] [-C] [-D]\\\n\
10 <   [-p {64|33}] [-n <rename_prefix>] [-o <trimmed.fq>] [-r <discarded.lst>]\\\n\
11 <   [-Q] <input.fq>\n\
9 > fqtrim [{-5 <5adapter> -3 <3adapter>|-f <adapters_file>}] [-a <min_matchlen>]\\\n\
10 >   [-q <minq> [-t <trim_max_len>]] [-p {64|33}] [-o <outsuffix>]\\\n\
11 >   [-l <minlen>] [-C] [-D] [-Q] [-n <rename_prefix>] [-r <discarded.lst>]\\\n\
12 >    <input.fq>[,<input_mates.fq>\n\
13   \n\
14 < Trim low quality bases at 3' end, optionally trim adapter sequence, filter\n\
15 < for low complexity and collapse duplicate reads\n\
14 > Trim low quality bases at the 3' end and can trim adapter sequence(s), filter\n\
15 > for low complexity and collapse duplicate reads.\n\
16 > If read pairs should be trimmed and kept together (i.e. without discarding\n\
17 > one read in a pair), the two file names should be given delimited by a comma\n\
18 > or a colon character\n\
19   \n\
20   Options:\n\
21   -n  rename all the reads using the <prefix> followed by a read counter;\n\
22      if -C option was given, the suffix \"_x<N>\" is appended, with <N> being\n\
23      the read duplication count\n\
24 < -o  write the trimmed/filtered fastq into <trimmed.fq>(instead of stdout)\n\
24 > -o  unless this parameter is '-', write the trimmed/filtered reads to \n\
25 >    file(s) named <input>.<outsuffix> which will be created in the \n\
26 >    current (working) directory; (writes to stdout if -o- is given);\n\
27 >    a suffix ending with .gz, .gzip or .bz2 will enforce compression\n\
28 > -f  file with adapter sequences to trim, each line having this format:\n\
29 >    <5'-adapter-sequence> <3'-adapter-sequence>\n\
30   -5  trim the given adapter or primer sequence at the 5' end of each read\n\
31      (e.g. -5 CGACAGGTTCAGAGTTCTACAGTCCGACGATC)\n\
32   -3  trim the given adapter sequence at the 3' end of each read\n\
33      (e.g. -3 TCGTATGCCGTCTTCTGCTTG)\n\
34 < -q  trim bases with quality value lower than <minq> (starting the 3' end)\n\
34 > -A  disable polyA/T trimming (enabled by default)\n\
35 > -y  minimum length of exact match to adaptor sequence at the proper end (6)\n\
36 > -q  trim bases with quality value lower than <minq> (starting at the 3' end)\n\
37 > -t  for -q option, maximum trimming at the 3' end is limited to <trim_max_len>\n\
38   -m  maximum percentage of Ns allowed in a read after trimming (default 7)\n\
39   -l  minimum \"clean\" length after trimming that a read must have\n\
40      in order to pass the filter (default: 16)\n\
# Line 34 | Line 48
48   -Q  convert quality values to the other Phred qv type\n\
49   -V  verbose processing\n\
50   "
51 +
52 + //-z  for -o option, the output stream(s) will be first piped into the given\n
53 + //   <zcmd> command, which must output to stdout (e.g. -z 'bzip2 -9 -c')\n
54 +
55 +
56   // example 3' adapter for miRNAs: TCGTATGCCGTCTTCTGCTTG
57  
58 < //For pair ends sequencing:
58 > //For paired reads sequencing:
59   //3' : ACACTCTTTCCCTACACGACGCTCTTCCGATCT
60   //5' : GATCGGAAGAGCGGTTCAGCAGGAATGCCGAG
61 < FILE* f_out=NULL; //stdout if not provided
62 < FILE* f_in=NULL; //input fastq (stdin if not provided)
61 > //FILE* f_out=NULL; //stdout if not provided
62 > //FILE* f_out2=NULL; //for paired reads
63 > //FILE* f_in=NULL; //input fastq (stdin if not provided)
64 > //FILE* f_in2=NULL; //for paired reads
65 >
66   FILE* freport=NULL;
67 +
68   bool debug=false;
69   bool verbose=false;
70   bool doCollapse=false;
71   bool doDust=false;
72 + bool doPolyTrim=true;
73 + bool fastaOutput=false;
74   bool trashReport=false;
75   //bool rawFormat=false;
76   int min_read_len=16;
# Line 53 | Line 78
78   int dust_cutoff=16;
79   bool isfasta=false;
80   bool convert_phred=false;
81 + GStr outsuffix; // -o
82   GStr prefix;
83 < GStr adapter3;
84 < GStr adapter5;
85 <
86 < int qvtrim_min=0;
83 > GStr zcmd;
84 > int num_trimmed5=0;
85 > int num_trimmed3=0;
86 > int num_trimmedN=0;
87 > int num_trimmedQ=0;
88 > int min_trimmed5=INT_MAX;
89 > int min_trimmed3=INT_MAX;
90  
91 + int qvtrim_qmin=0;
92 + int qvtrim_max=0;  //for -q, do not trim at 3'-end more than this number of bases
93   int qv_phredtype=0; // could be 64 or 33 (0 means undetermined yet)
94   int qv_cvtadd=0; //could be -31 or +31
95  
96 < int a3len=0;
97 < int a5len=0;
98 < // adaptor matching metrics -- for extendMatch() function
99 < const int a_m_score=2; //match score
100 < const int a_mis_score=-3; //mismatch
101 < const int a_dropoff_score=7;
102 < const int a_min_score=8; //an exact match of 4 bases at the proper ends WILL be trimmed
103 < const int a_min_chain_score=15; //for gapped alignments
104 <
105 < class CSegChain;
106 <
107 < class CSegPair {
108 <  public:
109 <   GSeg a;
110 <   GSeg b; //the adapter segment
111 <   int score;
112 <   int flags;
113 <   CSegChain* chain;
114 <   CSegPair(int astart=0, int aend=0, int bstart=0, int bend=0, int mscore=0):a(astart,aend),b(bstart, bend) {
115 <      score=mscore;
116 <      if (score==0) score=a.len()*a_m_score;
117 <      flags=0;
118 <      chain=NULL;
88 <      }
89 <   int len() { return  a.len(); }
90 <   bool operator==(CSegPair& d){
91 <      //return (a.start==d.a.start && a.end==d.a.end && b.start==d.b.start && b.end==d.b.end);
92 <      //make equal even segments that are included into one another:
93 <      return (d.a.start>=a.start && d.a.end<=a.end && d.b.start>=b.start && d.b.end<=b.end);
94 <      }
95 <   bool operator>(CSegPair& d){ //ordering based on b (adaptor) start coord and score
96 <     if (b.start==d.b.start) {
97 <        if (score==d.score) {
98 <           //just try to be consistent:
99 <           if (b.end==d.b.end) {
100 <             return (a.start==d.a.start)?(a.end<d.a.end):(a.start<d.a.start);
101 <             }
102 <           return (b.end>d.b.end);
103 <           }
104 <         else return (score<d.score);
105 <        }
106 <     return (b.start>d.b.start);
107 <     }
108 <   bool operator<(CSegPair& d){ //ordering based on b (adaptor) coord
109 <     /*if (b.start==d.b.start && b.end==d.b.end) {
110 <          return (a.start==d.a.start)?(a.end<d.a.end):(a.start<d.a.start);
111 <          }
112 <     return (b.start==d.b.start)?(b.end<d.b.end):(b.start<d.b.start);*/
113 <     if (b.start==d.b.start) {
114 <        if (score==d.score) {
115 <           //just try to be consistent:
116 <           if (b.end==d.b.end) {
117 <             return (a.start==d.a.start)?(a.end>d.a.end):(a.start>d.a.start);
118 <             }
119 <           return (b.end<d.b.end);
120 <           }
121 <         else return (score>d.score);
122 <        }
123 <     return (b.start<d.b.start);
124 <     }
125 < };
126 <
127 < int cmpSegEnds(pointer sa, pointer sb) { //sort by adaptor seg ends AND score
128 < CSegPair& x = *(CSegPair *)sa;
129 < CSegPair& y = *(CSegPair *)sb;
130 < /*
131 < if (x.b.end==y.b.end) {
132 <     if (x.b.start==y.b.start) {
133 <         if (x.a.end==y.a.end) {
134 <            if (x.a.start==y.a.start) return 0;
135 <            return ((x.a.start>y.a.start) ? -1 : 1);
136 <            }
137 <          else {
138 <            return ((x.a.end>y.a.end) ? -1 : 1);
139 <            }
140 <          }
141 <      else {
142 <       return ((x.b.start>y.b.start) ? -1 : 1);
96 > // adaptor matching metrics -- for X-drop ungapped extension
97 > const int match_reward=2;
98 > const int mismatch_penalty=3;
99 > const int Xdrop=8;
100 >
101 > const int poly_m_score=2; //match score
102 > const int poly_mis_score=-3; //mismatch
103 > const int poly_dropoff_score=7;
104 > int poly_minScore=12; //i.e. an exact match of 6 bases at the proper ends WILL be trimmed
105 >
106 > const char *polyA_seed="AAAA";
107 > const char *polyT_seed="TTTT";
108 >
109 > struct CASeqData {
110 >   //positional data for every possible hexamer in an adapter
111 >   GVec<uint16>* pz[64]; //0-based coordinates of all possible hexamers in the adapter sequence
112 >   GVec<uint16>* pzr[64]; //0-based coordinates of all possible hexamers for the reverse complement of the adapter sequence
113 >   GStr seq; //actual adapter sequence data
114 >   GStr seqr; //reverse complement sequence
115 >   CASeqData(bool rev=false):seq(),seqr() {
116 >     for (int i=0;i<63;i++) {
117 >       pz[i]=new GVec<uint16>(1);
118 >       if (rev) pzr[i]=new GVec<uint16>(1);
119         }
120 +   }
121 +
122 +   ~CSeqData() {
123 +     for (int i=0;i<63;i++) {
124 +     delete pz[i];
125 +     if (rev) { delete pzr[i]; }
126       }
127 <    else {
128 <     return ((x.b.end>y.b.end) ? -1 : 1);
147 <     }
148 < */
149 <  if (x.b.end==y.b.end) {
150 <     if (x.score==y.score) {
151 <     if (x.b.start==y.b.start) {
152 <         if (x.a.end==y.a.end) {
153 <            if (x.a.start==y.a.start) return 0;
154 <            return ((x.a.start<y.a.start) ? -1 : 1);
155 <            }
156 <          else {
157 <            return ((x.a.end<y.a.end) ? -1 : 1);
158 <            }
159 <          }
160 <      else {
161 <       return ((x.b.start<y.b.start) ? -1 : 1);
162 <       }
163 <      } else return ((x.score>y.score) ? -1 : 1);
164 <     }
165 <    else {
166 <     return ((x.b.end>y.b.end) ? -1 : 1);
167 <     }
127 >   }
128 > };
129  
130 < }
130 > GVec<CASeqData> adapters5;
131 > GVec<CASeqData> adapters3;
132  
133 < class CSegChain:public GList<CSegPair> {
134 < public:
173 <   uint astart;
174 <   uint aend;
175 <   uint bstart;
176 <   uint bend;
177 <   int score;
178 <   bool endSort;
179 <  CSegChain(bool aln5=false):GList<CSegPair>(true,true,true) {//sorted, free elements, unique
180 <   //as SegPairs are inserted, they will be sorted by a.start coordinate
181 <   score=0;
182 <   astart=MAX_UINT;
183 <   aend=0;
184 <   bstart=MAX_UINT;
185 <   bend=0;
186 <   endSort=aln5;
187 <   if (aln5) { setSorted(cmpSegEnds); }
188 <   }
189 < bool operator==(CSegChain& d) {
190 <   //return (score==d.score);
191 <    return (astart==d.astart && aend==d.aend && bstart==d.bstart && bend==d.bend);
192 <   }
193 < bool operator>(CSegChain& d) { // order based on b (adaptor) coordinate
194 <   //return (score<d.score);
195 <   if (bstart==d.bstart && bend==d.bend) {
196 <          return (astart==d.astart)?(aend>d.aend):(astart>d.astart);
197 <          }
198 <     return (bstart==d.bstart)?(bend>d.bend):(bstart>d.bstart);
199 <   }
200 < bool operator<(CSegChain& d) {
201 <   //return (score>d.score);
202 <   if (bstart==d.bstart && bend==d.bend) {
203 <          return (astart==d.astart)?(aend<d.aend):(astart<d.astart);
204 <          }
205 <     return (bstart==d.bstart)?(bend<d.bend):(bstart<d.bstart);
206 <   }
207 < void addSegPair(CSegPair* segp) {
208 <   if (AddIfNew(segp)!=segp) return;
209 <   score+=segp->score;
210 <   if (astart>segp->a.start) astart=segp->a.start;
211 <   if (aend<segp->a.end) aend=segp->a.end;
212 <   if (bstart>segp->b.start) bstart=segp->b.start;
213 <   if (bend<segp->b.end) bend=segp->b.end;
214 <   }
215 < //for building actual chains:
216 < bool extendChain(CSegPair* segp) { //segp expected to be "Greater Than" current chain
217 <   int bgap=0;
218 <   int agap=0;
219 <   //if (endSort) {
220 <   if (bstart>segp->b.start) {
221 <      bgap = (int)(bstart-segp->b.end);
222 <      if (abs(bgap)>2) return false;
223 <      agap = (int)(astart-segp->a.end);
224 <      if (abs(agap)>2) return false;
225 <      }
226 <     else {
227 <      bgap = (int) (segp->b.start-bend);
228 <      if (abs(bgap)>2) return false;
229 <      agap = (int)(segp->a.start-aend);
230 <      if (abs(agap)>2) return false;
231 <      }
232 <   if (agap*bgap<0) return false;
233 <   addSegPair(segp);
234 <   score-=abs(agap)+abs(bgap);
235 <   return true;
236 <   }
237 < };
133 > CGreedyAlignData* gxmem_l=NULL;
134 > CGreedyAlignData* gxmem_r=NULL;
135  
136   // element in dhash:
137   class FqDupRec {
# Line 273 | Line 170
170    if (!s.is_empty()) {
171        if (s=='-') f=stdout;
172        else {
173 <       f=fopen(s,"w");
173 >       f=fopen(s.chars(),"w");
174         if (f==NULL) GError("Error creating file: %s\n", s.chars());
175         }
176       }
# Line 284 | Line 181
181  
182   GHash<FqDupRec> dhash; //hash to keep track of duplicates
183  
184 + int loadAdapters(const char* fname);
185 +
186 + void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
187 +                       GStr& s, GStr& infname, GStr& infname2);
188 + // uses outsuffix to generate output file names and open file handles as needed
189 +
190 + void writeRead(FILE* f_out, GStr& rname, GStr& rinfo, GStr& rseq, GStr& rqv, int& outcounter);
191 + void trash_report(char trashcode, GStr& rname, FILE* freport);
192 +
193 + bool getFastxRec(GLineReader& fq, GStr& rseq, GStr& rqv,
194 +          GStr& rname, GStr& rinfo, GStr& infname);
195 +
196 + char process_read(GStr& rname, GStr& rseq, GStr& rqv, int &l5, int &l3);
197 + //returns 0 if the read was untouched, 1 if it was trimmed and a trash code if it was trashed
198 +
199   bool ntrim(GStr& rseq, int &l5, int &l3); //returns true if any trimming occured
200   bool qtrim(GStr& qvs, int &l5, int &l3); //return true if any trimming occured
201   int dust(GStr& seq);
202 < bool trim_adapter3(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
202 > bool trim_poly5(GStr &seq, int &l5, int &l3, const char* poly_seed); //returns true if any trimming occured
203 > bool trim_poly3(GStr &seq, int &l5, int &l3, const char* poly_seed);
204   bool trim_adapter5(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
205 + bool trim_adapter3(GStr& seq, int &l5, int &l3);
206  
207   void convertPhred(char* q, int len);
208   void convertPhred(GStr& q);
209  
210   int main(int argc, char * const argv[]) {
211 <  GArgs args(argc, argv, "YQDCVl:d:3:5:m:n:r:p:q:o:");
211 >  GArgs args(argc, argv, "YQDCVAl:d:3:5:m:n:r:p:q:f:t:o:z:a:");
212    int e;
299  int icounter=0; //counter for input reads
300  int outcounter=0; //counter for output reads
213    if ((e=args.isError())>0) {
214        GMessage("%s\nInvalid argument: %s\n", USAGE, argv[e]);
215        exit(224);
216        }
217    debug=(args.getOpt('Y')!=NULL);
218 <  debug=(args.getOpt('V')!=NULL);
218 >  verbose=(args.getOpt('V')!=NULL);
219    convert_phred=(args.getOpt('Q')!=NULL);
220    doCollapse=(args.getOpt('C')!=NULL);
221    doDust=(args.getOpt('D')!=NULL);
222 +  if (args.getOpt('A')) doPolyTrim=false;
223    /*
224    rawFormat=(args.getOpt('R')!=NULL);
225    if (rawFormat) {
# Line 315 | Line 228
228    */
229    prefix=args.getOpt('n');
230    GStr s=args.getOpt('l');
231 <  if (!s.is_empty())
231 >  if (!s.is_empty())
232       min_read_len=s.asInt();
233    s=args.getOpt('m');
234 <  if (!s.is_empty())
234 >  if (!s.is_empty())
235       max_perc_N=s.asDouble();
236    s=args.getOpt('d');
237    if (!s.is_empty()) {
# Line 327 | Line 240
240       }
241    s=args.getOpt('q');
242    if (!s.is_empty()) {
243 <     qvtrim_min=s.asInt();
243 >     qvtrim_qmin=s.asInt();
244 >     }
245 >  s=args.getOpt('t');
246 >  if (!s.is_empty()) {
247 >     qvtrim_max=s.asInt();
248       }
249    s=args.getOpt('p');
250    if (!s.is_empty()) {
# Line 340 | Line 257
257          qv_phredtype=64;
258          qv_cvtadd=-31;
259          }
260 <       else
260 >       else
261           GMessage("%s\nInvalid value for -p option (can only be 64 or 33)!\n",USAGE);
262       }
263 <  if (args.getOpt('3')!=NULL) {
264 <    adapter3=args.getOpt('3');
265 <    adapter3.upper();
266 <    a3len=adapter3.length();
267 <    }
268 <  if (args.getOpt('5')!=NULL) {
269 <    adapter5=args.getOpt('5');
270 <    adapter5.upper();
271 <    a5len=adapter5.length();
263 >  s=args.getOpt('f');
264 >  if (!s.is_empty()) {
265 >   loadAdapters(s.chars());
266 >   }
267 >  bool fileAdapters=adapters5.Count()+adapters3.Count();
268 >  s=args.getOpt('5');
269 >  if (!s.is_empty()) {
270 >    if (fileAdapters)
271 >      GError("Error: options -5 and -f cannot be used together!\n");
272 >    s.upper();
273 >    adapters5.Add(s);
274 >    }
275 >  s=args.getOpt('3');
276 >  if (!s.is_empty()) {
277 >    if (fileAdapters)
278 >      GError("Error: options -3 and -f cannot be used together!\n");
279 >      s.upper();
280 >      adapters3.Add(s);
281      }
282 +  s=args.getOpt('y');
283 +  if (!s.is_empty()) {
284 +     int minmatch=s.asInt();
285 +     poly_minScore=minmatch*poly_m_score;
286 +     }
287 +
288 +  if (args.getOpt('o')!=NULL) outsuffix=args.getOpt('o');
289 +                         else outsuffix="-";
290    trashReport=  (args.getOpt('r')!=NULL);
291 <  if (args.startNonOpt()==0) {
291 >  int fcount=args.startNonOpt();
292 >  if (fcount==0) {
293      GMessage(USAGE);
294      exit(224);
295      }
296 <
297 <  openfw(f_out, args, 'o');
298 <  if (f_out==NULL) f_out=stdout;
296 >   if (fcount>1 && doCollapse) {
297 >    GError("%s Sorry, the -C option only works with a single input.\n", USAGE);
298 >    }
299 >  //openfw(f_out, args, 'o');
300 >  //if (f_out==NULL) f_out=stdout;
301    if (trashReport)
302      openfw(freport, args, 'r');
303    char* infile=NULL;
304 +
305 +  if (adapters5.Count()>0)
306 +    gxmem_l=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop-2);
307 +  if (adapters3.Count()>0)
308 +    gxmem_r=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop);
309 +
310    while ((infile=args.nextNonOpt())!=NULL) {
311 <    GStr infname(infile);
312 <    if (strcmp(infile,"-")==0) {
313 <       f_in=stdin; infname="stdin"; }
314 <     else {
315 <        f_in=fopen(infile,"r");
316 <        if (f_in==NULL)
317 <            GError("Cannot open input file %s!\n",infile);
318 <        }
319 <     GLineReader fq(f_in);
320 <     char* l=NULL;
321 <     while ((l=fq.getLine())!=NULL) {
322 <        GStr rname; //current read name
323 <        GStr rseq;  //current read sequence
324 <        GStr rqv;   //current read quality values
325 <        GStr s;
326 <        /* if (rawFormat) {
327 <          //TODO: implement qseq parsing here
328 <          //if (raw type=N) then continue; //skip invalid/bad records
329 <          
330 <          } //raw qseq format
331 <         else { // FASTQ or FASTA */
332 <          isfasta=(l[0]=='>');
333 <          if (!isfasta && l[0]!='@') GError("Error: fastq record marker not detected!\n");
334 <          s=l;
335 <          rname=&(l[1]);
336 <          icounter++;
337 <          for (int i=0;i<rname.length();i++)
338 <            if (rname[i]<=' ') { rname.cut(i); break; }
339 <          //now get the sequence
340 <          if ((l=fq.getLine())==NULL)
341 <              GError("Error: unexpected EOF after header for %s\n",rname.chars());
342 <          rseq=l; //this must be the DNA line
343 <          while ((l=fq.getLine())!=NULL) {
344 <              //seq can span multiple lines
345 <              if (l[0]=='>' || l[0]=='+') {
346 <                   fq.pushBack();
347 <                   break; //
311 >    //for each input file
312 >    int incounter=0; //counter for input reads
313 >    int outcounter=0; //counter for output reads
314 >    int trash_s=0; //too short from the get go
315 >    int trash_Q=0;
316 >    int trash_N=0;
317 >    int trash_D=0;
318 >    int trash_poly=0;
319 >    int trash_A3=0;
320 >    int trash_A5=0;
321 >    s=infile;
322 >    GStr infname;
323 >    GStr infname2;
324 >    FILE* f_in=NULL;
325 >    FILE* f_in2=NULL;
326 >    FILE* f_out=NULL;
327 >    FILE* f_out2=NULL;
328 >    bool paired_reads=false;
329 >    setupFiles(f_in, f_in2, f_out, f_out2, s, infname, infname2);
330 >    GLineReader fq(f_in);
331 >    GLineReader* fq2=NULL;
332 >    if (f_in2!=NULL) {
333 >       fq2=new GLineReader(f_in2);
334 >       paired_reads=true;
335 >       }
336 >    GStr rseq, rqv, seqid, seqinfo;
337 >    GStr rseq2, rqv2, seqid2, seqinfo2;
338 >    while (getFastxRec(fq, rseq, rqv, seqid, seqinfo, infname)) {
339 >       incounter++;
340 >       int a5=0, a3=0, b5=0, b3=0;
341 >       char tcode=0, tcode2=0;
342 >       tcode=process_read(seqid, rseq, rqv, a5, a3);
343 >       if (fq2!=NULL) {
344 >            getFastxRec(*fq2, rseq2, rqv2, seqid2, seqinfo2, infname2);
345 >            if (seqid.substr(0,seqid.length()-1)!=seqid2.substr(0,seqid2.length()-1)) {
346 >               GError("Error: no paired match for read %s vs %s (%s,%s)\n",
347 >                  seqid.chars(), seqid2.chars(), infname.chars(), infname2.chars());
348 >               }
349 >            tcode2=process_read(seqid2, rseq2, rqv2, b5, b3);
350 >            //decide what to do with this pair and print rseq2 if the pair makes it
351 >            if (tcode>1 && tcode2<=1) {
352 >               //"untrash" rseq
353 >               if (a3-a5+1<min_read_len) {
354 >                   a5=1;
355 >                   if (a3<min_read_len) { a3= GMIN(rseq.length()-1, min_read_len+1); }
356                     }
357 <              rseq+=l;
358 <              } //check for multi-line seq
359 <          if (!isfasta) { //reading fastq quality values, which can also be multi-line
360 <            if ((l=fq.getLine())==NULL)
361 <                GError("Error: unexpected EOF after sequence for %s\n", rname.chars());
362 <            if (l[0]!='+') GError("Error: fastq qv header marker not detected!\n");
363 <            if ((l=fq.getLine())==NULL)
364 <                GError("Error: unexpected EOF after qv header for %s\n", rname.chars());
365 <            rqv=l;
366 <            //if (rqv.length()!=rseq.length())
367 <            //  GError("Error: qv len != seq len for %s\n", rname.chars());
368 <            while (rqv.length()<rseq.length() && ((l=fq.getLine())!=NULL)) {
369 <              rqv+=l; //append to qv string
370 <              }
420 <            }// fastq
421 <        // } //<-- FASTA or FASTQ
422 <        rseq.upper();
423 <        int l5=0;
424 <        int l3=rseq.length()-1;
425 <        if (l3-l5+1<min_read_len) {
426 <           if (trashReport) {
427 <                  fprintf(freport, "%s\ts\t%s\n",rname.chars(), rseq.chars());
428 <                  }
429 <           continue;
430 <           }
431 <        if (ntrim(rseq, l5, l3)) { // N-trimming
432 <           //GMessage("before: %s\n",rseq.chars());
433 <           //GMessage("after : %s (%d)\n",rseq.substr(l5,l3-l5+1).chars(),l3-l5+1);
434 <           if (l3-l5+1<min_read_len) {
435 <             if (trashReport) {
436 <                    fprintf(freport, "%s\tN\t%s\n", rname.chars(), rseq.chars());
437 <                    }
438 <             continue; //invalid read
439 <             }
440 <            //-- keep only the l5..l3 range
441 <           rseq=rseq.substr(l5, l3-l5+1);
442 <           if (!rqv.is_empty())
443 <              rqv=rqv.substr(l5, l3-l5+1);
444 <           l5=0;
445 <           l3=rseq.length()-1;
446 <           }
447 <        if (qvtrim_min!=0 && !rqv.is_empty() && qtrim(rqv, l5, l3)) { // qv-threshold trimming
448 <           if (l3-l5+1<min_read_len) {
449 <             if (trashReport) {
450 <                    fprintf(freport, "%s\tQ\t%s\n", rname.chars(), rseq.chars());
451 <                    }
452 <             continue; //invalid read
453 <             }
454 <            //-- keep only the l5..l3 range
455 <           rseq=rseq.substr(l5, l3-l5+1);
456 <           if (!rqv.is_empty())
457 <              rqv=rqv.substr(l5, l3-l5+1);
458 <           } //qv trimming
459 <        if (a3len>0) {
460 <          if (trim_adapter3(rseq, l5, l3)) {
461 <             if (l3-l5+1<min_read_len) {
462 <                 if (trashReport) {
463 <                     fprintf(freport, "%s\tA3\t%s\n",rname.chars(), rseq.chars());
464 <                     }
465 <                 continue;
466 <                 }
467 <              //-- keep only the l5..l3 range
468 <              rseq=rseq.substr(l5, l3-l5+1);
469 <              if (!rqv.is_empty())
470 <                 rqv=rqv.substr(l5, l3-l5+1);
471 <              }//some adapter was trimmed
472 <           } //adapter trimming
473 <        if (a5len>0) {
474 <          if (trim_adapter5(rseq, l5, l3)) {
475 <             if (l3-l5+1<min_read_len) {
476 <                 if (trashReport) {
477 <                     fprintf(freport, "%s\tA5\t%s\n",rname.chars(), rseq.chars());
478 <                     }
479 <                 continue;
357 >               tcode=1;
358 >               }
359 >             else if (tcode<=1 && tcode2>1) {
360 >               //"untrash" rseq2
361 >               if (b3-b5+1<min_read_len) {
362 >                   b5=1;
363 >                   if (b3<min_read_len) { b3= GMIN((rseq2.length()-1),(min_read_len+1)); }
364 >                   }
365 >               tcode2=1;
366 >               }
367 >            if (tcode<=1) { //trimmed or left intact -- write it!
368 >               if (tcode>0) {
369 >                 rseq2=rseq2.substr(b5,b3-b5+1);
370 >                 if (!rqv2.is_empty()) rqv2=rqv2.substr(b5,b3-b5+1);
371                   }
372 <              //-- keep only the l5..l3 range
373 <              rseq=rseq.substr(l5, l3-l5+1);
374 <              if (!rqv.is_empty())
375 <                 rqv=rqv.substr(l5, l3-l5+1);
376 <              }//some adapter was trimmed
377 <           } //adapter trimming
378 <        if (doCollapse) {
379 <           //keep read for later
380 <           FqDupRec* dr=dhash.Find(rseq.chars());
381 <           if (dr==NULL) { //new entry
382 <                  //if (prefix.is_empty())
383 <                     dhash.Add(rseq.chars(),
384 <                          new FqDupRec(&rqv, rname.chars()));
385 <                  //else dhash.Add(rseq.chars(), new FqDupRec(rqv.chars(),rqv.length()));
372 >               int nocounter=0;
373 >               writeRead(f_out2, seqid2, seqinfo2, rseq2, rqv2, nocounter);
374 >               }
375 >            } //pair read
376 >       if (tcode>1) { //trashed
377 >         #ifdef GDEBUG
378 >         GMessage(" !!!!TRASH => 'N'\n");
379 >         #endif
380 >          if (tcode=='s') trash_s++;
381 >          else if (tcode=='A' || tcode=='T') trash_poly++;
382 >            else if (tcode=='Q') trash_Q++;
383 >              else if (tcode=='N') trash_N++;
384 >               else if (tcode=='D') trash_D++;
385 >                else if (tcode=='3') trash_A3++;
386 >                 else if (tcode=='5') trash_A5++;
387 >          if (trashReport) trash_report(tcode, seqid, freport);
388 >          }
389 >         else if (!doCollapse) { //write it
390 >          if (tcode>0) {
391 >            rseq=rseq.substr(a5,a3-a5+1);
392 >            if (!rqv.is_empty()) rqv=rqv.substr(a5,a3-a5+1);
393 >            }
394 >         #ifdef GDEBUG
395 >            GMessage("  After trimming:\n");
396 >            GMessage("%s\n",rseq.chars());
397 >         #endif
398 >          writeRead(f_out, seqid, seqinfo, rseq, rqv, outcounter);
399 >          }
400 >       } //for each fastq record
401 >    delete fq2;
402 >    FRCLOSE(f_in);
403 >    FRCLOSE(f_in2);
404 >    if (doCollapse) {
405 >       outcounter=0;
406 >       int maxdup_count=1;
407 >       char* maxdup_seq=NULL;
408 >       dhash.startIterate();
409 >       FqDupRec* qd=NULL;
410 >       char* seq=NULL;
411 >       while ((qd=dhash.NextData(seq))!=NULL) {
412 >         GStr rseq(seq);
413 >         //do the dusting here
414 >         if (doDust) {
415 >            int dustbases=dust(rseq);
416 >            if (dustbases>(rseq.length()>>1)) {
417 >               if (trashReport && qd->firstname!=NULL) {
418 >                 fprintf(freport, "%s_x%d\tD\n",qd->firstname, qd->count);
419                   }
420 <              else    
421 <                 dr->add(rqv);
422 <           } //collapsing duplicates
423 <         else { //not collapsing duplicates
424 <           //do the dust filter now
425 <           if (doDust) {
426 <             int dustbases=dust(rseq);
427 <             if (dustbases>(rseq.length()>>1)) {
428 <                if (trashReport) {
429 <                  fprintf(freport, "%s\tD\t%s\n",rname.chars(),rseq.chars());
430 <                  }
431 <                continue;
432 <                }
509 <             }
510 <           //print this record here  
511 <           outcounter++;
512 <           if (isfasta) {
513 <            if (prefix.is_empty())
514 <               fprintf(f_out, ">%s\n%s\n", rname.chars(), rseq.chars());
515 <              else
516 <               fprintf(f_out, ">%s%08d\n%s\n", prefix.chars(), outcounter,
517 <                                  rseq.chars());
420 >               trash_D+=qd->count;
421 >               continue;
422 >               }
423 >            }
424 >         outcounter++;
425 >         if (qd->count>maxdup_count) {
426 >            maxdup_count=qd->count;
427 >            maxdup_seq=seq;
428 >            }
429 >         if (isfasta) {
430 >           if (prefix.is_empty()) {
431 >             fprintf(f_out, ">%s_x%d\n%s\n", qd->firstname, qd->count,
432 >                           rseq.chars());
433               }
434 <           else {  //fastq
435 <            if (convert_phred) convertPhred(rqv);
436 <            if (prefix.is_empty())
522 <               fprintf(f_out, "@%s\n%s\n+\n%s\n", rname.chars(), rseq.chars(),rqv.chars());
523 <              else
524 <               fprintf(f_out, "@%s_%08d\n%s\n+\n%s\n", prefix.chars(), outcounter,
525 <                                  rseq.chars(),rqv.chars() );
434 >           else { //use custom read name
435 >             fprintf(f_out, ">%s%08d_x%d\n%s\n", prefix.chars(), outcounter,
436 >                        qd->count, rseq.chars());
437               }
438 <           } //not collapsing duplicates
439 <        } //for each fastq record
440 <   } //while each input file
441 < FRCLOSE(f_in);
442 < if (doCollapse) {
443 <    outcounter=0;
533 <    int maxdup_count=1;
534 <    char* maxdup_seq=NULL;
535 <    dhash.startIterate();
536 <    FqDupRec* qd=NULL;
537 <    char* seq=NULL;
538 <    while ((qd=dhash.NextData(seq))!=NULL) {
539 <      GStr rseq(seq);
540 <      //do the dusting here
541 <      if (doDust) {
542 <         int dustbases=dust(rseq);
543 <         if (dustbases>(rseq.length()>>1)) {
544 <            if (trashReport && qd->firstname!=NULL) {
545 <              fprintf(freport, "%s_x%d\tD\t%s\n",qd->firstname, qd->count,seq);
546 <              }
547 <            continue;
438 >           }
439 >         else { //fastq format
440 >          if (convert_phred) convertPhred(qd->qv, qd->len);
441 >          if (prefix.is_empty()) {
442 >            fprintf(f_out, "@%s_x%d\n%s\n+\n%s\n", qd->firstname, qd->count,
443 >                           rseq.chars(), qd->qv);
444              }
445 +          else { //use custom read name
446 +            fprintf(f_out, "@%s%08d_x%d\n%s\n+\n%s\n", prefix.chars(), outcounter,
447 +                        qd->count, rseq.chars(), qd->qv);
448 +            }
449 +           }
450 +         }//for each element of dhash
451 +       if (maxdup_count>1) {
452 +         GMessage("Maximum read multiplicity: x %d (read: %s)\n",maxdup_count, maxdup_seq);
453           }
454 <      outcounter++;
455 <      if (qd->count>maxdup_count) {
456 <         maxdup_count=qd->count;
457 <         maxdup_seq=seq;
458 <         }
459 <      if (isfasta) {
460 <        if (prefix.is_empty()) {
461 <          fprintf(f_out, ">%s_x%d\n%s\n", qd->firstname, qd->count,
462 <                        rseq.chars());
463 <          }
464 <        else { //use custom read name
465 <          fprintf(f_out, ">%s%08d_x%d\n%s\n", prefix.chars(), outcounter,
466 <                     qd->count, rseq.chars());
454 >       } //collapse entries
455 >    if (verbose) {
456 >       if (paired_reads) {
457 >           GMessage(">Input files : %s , %s\n", infname.chars(), infname2.chars());
458 >           GMessage("Number of input pairs :%9d\n", incounter);
459 >           GMessage("         Output pairs :%9d\n", outcounter);
460 >           }
461 >         else {
462 >           GMessage(">Input file : %s\n", infname.chars());
463 >           GMessage("Number of input reads :%9d\n", incounter);
464 >           GMessage("         Output reads :%9d\n", outcounter);
465 >           }
466 >       GMessage("------------------------------------\n");
467 >       if (num_trimmed5)
468 >          GMessage("           5' trimmed :%9d  (min. trim: %d)\n", num_trimmed5, min_trimmed5);
469 >       if (num_trimmed3)
470 >          GMessage("           3' trimmed :%9d  (min. trim: %d)\n", num_trimmed3, min_trimmed3);
471 >       GMessage("------------------------------------\n");
472 >       if (trash_s>0)
473 >         GMessage("     Trashed by length:%9d\n", trash_s);
474 >       if (trash_N>0)
475 >         GMessage("         Trashed by N%%:%9d\n", trash_N);
476 >       if (trash_Q>0)
477 >         GMessage("Trashed by low quality:%9d\n", trash_Q);
478 >       if (trash_poly>0)
479 >         GMessage("   Trashed by poly-A/T:%9d\n", trash_poly);
480 >       if (trash_A5>0)
481 >         GMessage(" Trashed by 5' adapter:%9d\n", trash_A5);
482 >       if (trash_A3>0)
483 >         GMessage(" Trashed by 3' adapter:%9d\n", trash_A3);
484 >       }
485 >    if (trashReport) {
486 >          FWCLOSE(freport);
487            }
488 <        }
489 <      else { //fastq format
490 <       if (convert_phred) convertPhred(qd->qv, qd->len);
491 <       if (prefix.is_empty()) {
492 <         fprintf(f_out, "@%s_x%d\n%s\n+\n%s\n", qd->firstname, qd->count,
569 <                        rseq.chars(), qd->qv);
570 <         }
571 <       else { //use custom read name
572 <         fprintf(f_out, "@%s%08d_x%d\n%s\n+\n%s\n", prefix.chars(), outcounter,
573 <                     qd->count, rseq.chars(), qd->qv);
574 <         }
575 <        }
576 <      }//for each element of dhash
577 <    if (maxdup_count>1) {
578 <      GMessage("Maximum read multiplicity: x %d (read: %s)\n",maxdup_count, maxdup_seq);
579 <      }
580 <   } //report collapsed dhash entries
581 < GMessage("Number of input reads: %9d\n", icounter);
582 < GMessage("       Output records: %9d\n", outcounter);
583 < if (trashReport) {
584 <    FWCLOSE(freport);
585 <    }
586 <
587 < FWCLOSE(f_out);
488 >    FWCLOSE(f_out);
489 >    FWCLOSE(f_out2);
490 >   } //while each input file
491 > delete gxmem_l;
492 > delete gxmem_r;
493   //getc(stdin);
494   }
495  
# Line 599 | Line 504
504     const char* seq;
505     bool valid;
506     NData() {
507 +    seqlen=0;
508      NCount=0;
509      end5=0;
510      end3=0;
# Line 629 | Line 535
535       perc_N=(n*100.0)/(end5-end3+1);
536       }
537   };
538 <
538 >
539   static NData feat;
540   int perc_lenN=12; // incremental distance from ends, in percentage of
541            // sequence length, where N-trimming is done (default:12 %) (autolimited to 20)
542 <          
542 >
543   void N_analyze(int l5, int l3, int p5, int p3) {
544   /* assumes feat was filled properly */
545   int old_dif, t5,t3,v;
546   if (l3<l5+2 || p5>p3 ) {
547     feat.end5=l5+1;
548     feat.end3=l3+1;
549 <   return;
549 >   return;
550     }
551  
552   t5=feat.NPos[p5]-l5;
553   t3=l3-feat.NPos[p3];
554   old_dif=p3-p5;
555   v=(int)((((double)(l3-l5))*perc_lenN)/100);
556 < if (v>20) v=20; /* enforce N-search limit for very long reads */
556 > if (v>20) v=20; /* enforce N-search limit for very long reads */
557   if (t5 < v ) {
558     l5=feat.NPos[p5]+1;
559     p5++;
# Line 664 | Line 570
570             feat.end3=l3+1;
571             return;
572             }
573 <    else
573 >    else
574        N_analyze(l5,l3, p5,p3);
575   }
576  
577  
578   bool qtrim(GStr& qvs, int &l5, int &l3) {
579 < if (qvtrim_min==0 || qvs.is_empty()) return false;
579 > if (qvtrim_qmin==0 || qvs.is_empty()) return false;
580   if (qv_phredtype==0) {
581    //try to guess the Phred type
582    int vmin=256, vmax=0;
# Line 683 | Line 589
589    if (qv_phredtype==0) {
590      GError("Error: couldn't determine Phred type, please use the -p33 or -p64 !\n");
591      }
592 <  } //guessing the Phred type
592 >  if (verbose)
593 >    GMessage("Input reads have Phred-%d quality values.\n", (qv_phredtype==33 ? 33 : 64));
594 >  } //guessing Phred type
595   for (l3=qvs.length()-1;l3>2;l3--) {
596 <  if (qvs[l3]-qv_phredtype>=qvtrim_min && qvs[l3-1]-qv_phredtype>=qvtrim_min) break;
596 >  if (qvs[l3]-qv_phredtype>=qvtrim_qmin && qvs[l3-1]-qv_phredtype>=qvtrim_qmin) break;
597    }
598   //just in case, check also the 5' the end (?)
599   for (l5=0;l5<qvs.length()-3;l5++) {
600 <  if (qvs[l5]-qv_phredtype>=qvtrim_min && qvs[l5+1]-qv_phredtype>=qvtrim_min) break;
600 >  if (qvs[l5]-qv_phredtype>=qvtrim_qmin && qvs[l5+1]-qv_phredtype>=qvtrim_qmin) break;
601 >  }
602 > if (qvtrim_max>0) {
603 >  if (qvs.length()-1-l3>qvtrim_max) l3=qvs.length()-1-qvtrim_max;
604 >  if (l5>qvtrim_max) l5=qvtrim_max;
605    }
606   return (l5>0 || l3<qvs.length()-1);
607   }
# Line 699 | Line 611
611   feat.init(rseq);
612   l5=feat.end5-1;
613   l3=feat.end3-1;
614 < N_analyze(feat.end5-1, feat.end3-1, 0, feat.NCount-1);
614 > N_analyze(feat.end5-1, feat.end3-1, 0, feat.NCount-1);
615   if (l5==feat.end5-1 && l3==feat.end3-1) {
616      if (feat.perc_N>max_perc_N) {
617             feat.valid=false;
# Line 717 | Line 629
629     return true;
630     }
631   feat.N_calc();
632 <
632 >
633   if (feat.perc_N>max_perc_N) {
634        feat.valid=false;
635        l3=l5+1;
# Line 729 | Line 641
641   //--------------- dust functions ----------------
642   class DNADuster {
643   public:
644 <  int dustword;
645 <  int dustwindow;
646 <  int dustwindow2;
644 >  int dustword;
645 >  int dustwindow;
646 >  int dustwindow2;
647    int dustcutoff;
648    int mv, iv, jv;
649    int counts[32*32*32];
# Line 826 | Line 738
738                      }
739             }
740           }
741 < //return first;
741 > //return first;
742   }
743   };
744  
# Line 844 | Line 756
756   return ncount;
757   }
758  
759 + struct SLocScore {
760 +  int pos;
761 +  int score;
762 +  SLocScore(int p=0,int s=0) {
763 +    pos=p;
764 +    score=s;
765 +    }
766 +  void set(int p, int s) {
767 +    pos=p;
768 +    score=s;
769 +    }
770 +  void add(int p, int add) {
771 +    pos=p;
772 +    score+=add;
773 +    }
774 + };
775  
776 < // ------------------ adapter matching - simple k-mer seed & extend, no indels for now
777 < //when a k-mer match is found, simply try to extend the alignment using a drop-off scheme
778 < //check minimum score and
779 < //for 3' adapter trimming:
780 < //     require that the right end of the alignment for either the adaptor OR the read must be
781 < //     < 3 distance from its right end
782 < // for 5' adapter trimming:
783 < //     require that the left end of the alignment for either the adaptor OR the read must
784 < //     be at coordinate < 3 from start
785 <
786 < bool extendMatch(const char* a, int alen, int ai,
787 <                 const char* b, int blen, int bi, int mlen, int& l5, int& l3, CSegChain& segs, bool end5=false) {
788 < //so the alignment starts at ai in a, bi in b, with a perfect match of length mlen
789 < #ifdef DEBUG
790 < GStr dbg(b);
863 < #endif
864 < //if (debug) {
865 < //  GMessage(">> in %s\n\textending hit: %s at position %d\n", a, (dbg.substr(bi, mlen)).chars(), ai);
866 < //  }
867 < int a_l=ai; //alignment coordinates on a
868 < int a_r=ai+mlen-1;
869 < int b_l=bi; //alignment coordinates on b
870 < int b_r=bi+mlen-1;
871 < int ai_maxscore=ai;
872 < int bi_maxscore=bi;
873 < int score=mlen*a_m_score;
874 < int maxscore=score;
875 < int mism5score=a_mis_score;
876 < if (end5 && ai<(alen>>1)) mism5score-=2; // increase penalty for mismatches at 5' end
877 < //try to extend to the left first, if possible
878 < while (ai>0 && bi>0) {
879 <   ai--;
880 <   bi--;
881 <   score+= (a[ai]==b[bi])? a_m_score : mism5score;
882 <   if (score>maxscore) {
883 <       ai_maxscore=ai;
884 <       bi_maxscore=bi;
885 <       maxscore=score;
886 <       }
887 <     else if (maxscore-score>a_dropoff_score) break;
888 <   }
889 < a_l=ai_maxscore;
890 < b_l=bi_maxscore;
891 < //if (debug) GMessage("  after l-extend: %*s%s\t\t(score=%d)\n",a_l," ",dbg.substr(b_l,b_r-b_l+1).chars(),maxscore);
892 < //now extend to the right
893 < ai_maxscore=a_r;
894 < bi_maxscore=b_r;
895 < ai=a_r;
896 < bi=b_r;
897 < score=maxscore;
898 < //sometimes there are extra AAAAs at the end of the read, ignore those
899 < if (strcmp(&a[alen-4],"AAAA")==0) {
900 <    alen-=3;
901 <    while (a[alen-1]=='A' && alen>ai) alen--;
902 <    }
903 < while (ai<alen-1 && bi<blen-1) {
904 <   ai++;
905 <   bi++;
906 <   //score+= (a[ai]==b[bi])? a_m_score : a_mis_score;
907 <   if (a[ai]==b[bi]) { //match
908 <      score+=a_m_score;
909 <      if (ai>=alen-2) {
910 <           score+=a_m_score-(alen-ai-1);
911 <           }
776 > bool trim_poly3(GStr &seq, int &l5, int &l3, const char* poly_seed) {
777 > if (!doPolyTrim) return false;
778 > int rlen=seq.length();
779 > l5=0;
780 > l3=rlen-1;
781 > int32 seedVal=*(int32*)poly_seed;
782 > char polyChar=poly_seed[0];
783 > //assumes N trimming was already done
784 > //so a poly match should be very close to the end of the read
785 > // -- find the initial match (seed)
786 > int lmin=GMAX((rlen-16), 0);
787 > int li;
788 > for (li=rlen-4;li>lmin;li--) {
789 >   if (seedVal==*(int*)&(seq[li])) {
790 >      break;
791        }
913    else { //mismatch
914      score+=a_mis_score;
915      }  
916   if (score>maxscore) {
917       ai_maxscore=ai;
918       bi_maxscore=bi;
919       maxscore=score;
920       }
921     else if (maxscore-score>a_dropoff_score) break;
792     }
793 <  a_r=ai_maxscore;
794 <  b_r=bi_maxscore;
795 <  int a_ovh3=alen-a_r-1;
796 <  int b_ovh3=blen-b_r-1;
797 <  int mmovh3=(a_ovh3<b_ovh3)? a_ovh3 : b_ovh3;
798 <  int mmovh5=(a_l<b_l)? a_l : b_l;
799 <  //if (debug) GMessage("  after r-extend: %*s%s\t\t(score=%d)\n",a_l," ",dbg.substr(b_l,b_r-b_l+1).chars(),maxscore);
800 < #ifdef DEBUG
801 <  if (debug) GMessage("     extended to: %*s\n",a_r+1,dbg.substr(b_l,b_r-b_l+1).chars());
802 < #endif
803 <  if (maxscore>=a_min_score && mmovh3<2 && mmovh5<2) {
804 <     if (a_l<a_ovh3) {
805 <        //adapter closer to the left end (typical for 5' adapter)
806 <        l5=a_r+1;
807 <        l3=alen-1;
808 <        }
809 <      else {
810 <        //adapter matching at the right end (typical for 3' adapter)
941 <        l5=0;
942 <        l3=a_l-1;
793 > if (li<=lmin) return false;
794 > //seed found, try to extend it both ways
795 > //extend right
796 > int ri=li+3;
797 > SLocScore loc(ri, poly_m_score<<2);
798 > SLocScore maxloc(loc);
799 > //extend right
800 > while (ri<rlen-1) {
801 >   ri++;
802 >   if (seq[ri]==polyChar) {
803 >                loc.add(ri,poly_m_score);
804 >                }
805 >   else if (seq[ri]=='N') {
806 >                loc.add(ri,0);
807 >                }
808 >   else { //mismatch
809 >        loc.add(ri,poly_mis_score);
810 >        if (maxloc.score-loc.score>poly_dropoff_score) break;
811          }
812 <     return true;
813 <     }
814 < else { //keep this segment pair for later (gapped alignment)
947 <   segs.addSegPair(new CSegPair(a_l+1, a_r+1, b_l+1, b_r+1, maxscore));
948 <   //this will also update min & max coordinates in segs (segs.astart, .aend, .bstart, .bend)
949 <   }
950 <  //do not trim:
951 <  l5=0;
952 <  l3=alen-1;
953 <  return false;
954 < }
955 <
956 < /*
957 < int getWordValue(const char* s, int wlen) {
958 < int r=0;
959 < while (wlen--) { r+=(((int)s[wlen])<<wlen) }
960 < return r;
961 < }
962 < */
963 < int get3mer_value(const char* s) {
964 < return (s[0]<<16)+(s[1]<<8)+s[2];
965 < }
966 <
967 < int w3_match(int qv, const char* str, int slen, int start_index=0) {
968 < if (start_index>=slen || start_index<0) return -1;
969 < for (int i=start_index;i<slen-3;i++) {
970 <   int rv=get3mer_value(str+i);
971 <   if (rv==qv) return i;
972 <   }
973 < return -1;
974 < }
975 <
976 < int w3_rmatch(int qv, const char* str, int slen, int end_index=-1) {
977 < if (end_index>=slen) return -1;
978 < if (end_index<0) end_index=slen-1;
979 < for (int i=end_index-2;i>=0;i--) {
980 <   int rv=get3mer_value(str+i);
981 <   if (rv==qv) return i;
982 <   }
983 < return -1;
984 < }
985 <
986 < int fast4match(int32 qv, const char* str, int slen, int start_index=0) {
987 < if (start_index>=slen || start_index<0) return -1;
988 < for (int i=start_index;i<slen-4;i++) {
989 <   int32* rv=(int32*)(str+i);
990 <   if (*rv==qv) return i;
991 <   }
992 < return -1;
993 < }
994 <
995 < int fast4rmatch(int32 qv, const char* str, int slen, int end_index=-1) {
996 < if (end_index>=slen) return -1;
997 < if (end_index<0) end_index=slen-1;
998 < for (int i=end_index-3;i>=0;i--) {
999 <   int32* rv=(int32*)(str+i);
1000 <   if (*rv==qv) return i;
1001 <   }
1002 < return -1;
1003 < }
1004 <
1005 < #ifdef DEBUG
1006 < void dbgPrintChain(CSegChain& chain, const char* aseq) {
1007 <  GStr s(aseq);
1008 <  for (int i=0;i<chain.Count();i++) {
1009 <   CSegPair& seg=*chain[i];
1010 <   GMessage("  dbg chain seg%d: %*s [%d-%d:%d-%d]\n",i,seg.a.start-1+seg.len(),
1011 <            s.substr(seg.b.start-1, seg.len()).chars(), seg.b.start,seg.b.end,seg.a.start,seg.a.end);
812 >   if (maxloc.score<=loc.score) {
813 >      maxloc=loc;
814 >      }
815     }
816 + ri=maxloc.pos;
817 + if (ri<rlen-6) return false; //no trimming wanted, too far from 3' end
818 + //ri = right boundary for the poly match
819 + //extend left
820 + loc.set(li, maxloc.score);
821 + maxloc.pos=li;
822 + while (li>0) {
823 +    li--;
824 +    if (seq[li]==polyChar) {
825 +                 loc.add(li,poly_m_score);
826 +                 }
827 +    else if (seq[li]=='N') {
828 +                 loc.add(li,0);
829 +                 }
830 +    else { //mismatch
831 +         loc.add(li,poly_mis_score);
832 +         if (maxloc.score-loc.score>poly_dropoff_score) break;
833 +         }
834 +    if (maxloc.score<=loc.score) {
835 +       maxloc=loc;
836 +       }
837 +    }
838 + li=maxloc.pos;
839 + if ((maxloc.score==poly_minScore && ri==rlen-1) ||
840 +    (maxloc.score>poly_minScore && ri>=rlen-3) ||
841 +    (maxloc.score>(poly_minScore*3) && ri>=rlen-8)) {
842 +  //trimming this li-ri match at 3' end
843 +    l3=li-1;
844 +    if (l3<0) l3=0;
845 +    return true;
846 +    }
847 + return false;
848   }
1014 #endif
849  
850 < bool trim_adapter3(GStr& seq, int&l5, int &l3) {
850 > bool trim_poly5(GStr &seq, int &l5, int &l3, const char* poly_seed) {
851 > if (!doPolyTrim) return false;
852   int rlen=seq.length();
853   l5=0;
854   l3=rlen-1;
855 < //first try a full match, we might get lucky
856 < int fi=-1;
857 < if ((fi=seq.index(adapter3))>=0) {
858 <   if (fi<rlen-fi-a3len) {//match is closer to the right end
859 <      l5=fi+a3len;
860 <      l3=rlen-1;
855 > int32 seedVal=*(int32*)poly_seed;
856 > char polyChar=poly_seed[0];
857 > //assumes N trimming was already done
858 > //so a poly match should be very close to the end of the read
859 > // -- find the initial match (seed)
860 > int lmax=GMIN(12, rlen-4);//how far from 5' end to look for 4-mer seeds
861 > int li;
862 > for (li=0;li<=lmax;li++) {
863 >   if (seedVal==*(int*)&(seq[li])) {
864 >      break;
865        }
1027    else {
1028      l5=0;
1029      l3=fi-1;
1030      }
1031   return true;
866     }
867 < #ifdef DEBUG
868 < if (debug) GMessage(">TRIM3 >>   Read: %s\n",seq.chars());
869 < #endif
870 <
871 < //also, for fast detection of other adapter-only reads that start past
872 < // the beginning of the adapter sequence, try to see if the first a3len-4
873 < // bases of the read are a substring of the adapter
874 < if (rlen>a3len-3) {
875 <   GStr rstart=seq.substr(1,a3len-4);
876 <   if ((fi=adapter3.index(rstart))>=0) {
877 <     l3=rlen-1;
878 <     l5=a3len-4;
879 <     while (fi+l5<a3len && l5<l3 && adapter3[fi+l5]==seq[l5]) l5++;
880 <     return true;
881 <     }
882 <  }
883 < CSegChain a3segs; //no chains here, just an ordered collection of segment pairs
884 <  //check the easy cases - 11 bases exact match at the end
885 < int fdlen=11;
886 <  if (a3len<16) {
1053 <   fdlen=a3len>>1;
1054 <   }
1055 < if (fdlen>4) {
1056 <     //check if we're lucky enough to have the last 11 bases of the read a part of the adapter
1057 <     GStr rstart=seq.substr(-fdlen-3,fdlen);
1058 <     if ((fi=adapter3.index(rstart))>=0) {
1059 < #ifdef DEBUG
1060 <       if (debug) GMessage("  W11match found: %*s\n", rlen-3, (adapter3.substr(fi,fdlen)).chars());
1061 < #endif
1062 <       if (extendMatch(seq.chars(), rlen, rlen-fdlen-3,
1063 <                     adapter3.chars(), a3len, fi,  fdlen, l5,l3, a3segs))
1064 <            return true;
1065 <       }
1066 <     //another easy case: first 11 characters of the adaptor found as a substring of the read
1067 <     GStr bstr=adapter3.substr(0, fdlen);
1068 <     if ((fi=seq.rindex(bstr))>=0) {
1069 < #ifdef DEBUG
1070 <       if (debug) GMessage("  A11match found: %*s\n", fi+fdlen, bstr.chars());
1071 < #endif
1072 <       if (extendMatch(seq.chars(), rlen, fi,
1073 <                     adapter3.chars(), a3len, 0,  fdlen, l5,l3, a3segs))
1074 <            return true;
867 > if (li>lmax) return false;
868 > //seed found, try to extend it both ways
869 > //extend left
870 > int ri=li+3; //save rightmost base of the seed
871 > SLocScore loc(li, poly_m_score<<2);
872 > SLocScore maxloc(loc);
873 > while (li>0) {
874 >    li--;
875 >    if (seq[li]==polyChar) {
876 >                 loc.add(li,poly_m_score);
877 >                 }
878 >    else if (seq[li]=='N') {
879 >                 loc.add(li,0);
880 >                 }
881 >    else { //mismatch
882 >         loc.add(li,poly_mis_score);
883 >         if (maxloc.score-loc.score>poly_dropoff_score) break;
884 >         }
885 >    if (maxloc.score<=loc.score) {
886 >       maxloc=loc;
887         }
888 <     } //tried to match 11 bases first
889 <    
890 < //no easy cases, so let's do the wmer hashing for the first 12 bases of the adaptor
891 < //-- only extend if the match is in the 3' (ending) region of the read
892 < int wordSize=3;
893 < int hlen=12;
894 < if (hlen>a3len-wordSize) hlen=a3len-wordSize;
895 < int imin=rlen>>1; //last half of the read, left boundary for the wmer match
896 < if (imin<a3len) { imin=GMIN(a3len, rlen-wordSize); }
897 < imin=rlen-imin;
898 < for (int iw=0;iw<hlen;iw++) {
899 <   //int32* qv=(int32*)(adapter3.chars()+iw);
900 <   int qv=get3mer_value(adapter3.chars()+iw);
901 <   fi=-1;
902 <   //while ((fi=fast4rmatch(*qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
903 <   while ((fi=w3_rmatch(qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
904 <     //GMessage(" ... fi=%d after w3_rmatch() (imin=%d)\n", fi, imin);
905 <
906 < #ifdef DEBUG
1095 <     if (debug) GMessage("    Wmatch found: %*s\n", fi+wordSize, (adapter3.substr(iw,wordSize)).chars());
1096 < #endif
1097 <     if (extendMatch(seq.chars(), rlen, fi, adapter3.chars(),
1098 <                   a3len, iw, wordSize, l5,l3, a3segs)) return true;
1099 <     fi--;
1100 <     if (fi<imin) break;
1101 <     }
1102 <   } //for each wmer in the first hlen bases of the adaptor
1103 < /*
1104 < //couldn't find a good trimming extension, hash 12 more bases of the adapter to collect more segment pairs there
1105 < //but only do this if we already have segment pairs collected in the last 12 bases of the adapter
1106 < if (a3segs.bstart>3 || a3segs.bend<(uint)(hlen-wordSize)) return false;
1107 < int hlen2=a3len-wordSize;
1108 < //if (hlen2>a3len-4) hlen2=a3len-4;
1109 < if (hlen2>hlen) {
1110 < #ifdef DEBUG
1111 <     if (debug && a3segs.Count()>0) {
1112 <        GMessage("  >>>>>2nd. hash: %s\n",seq.chars());
888 >    }
889 > li=maxloc.pos;
890 > if (li>5) return false; //no trimming wanted, too far from 5' end
891 > //li = right boundary for the poly match
892 >
893 > //extend right
894 > loc.set(ri, maxloc.score);
895 > maxloc.pos=ri;
896 > while (ri<rlen-1) {
897 >   ri++;
898 >   if (seq[ri]==polyChar) {
899 >                loc.add(ri,poly_m_score);
900 >                }
901 >   else if (seq[ri]=='N') {
902 >                loc.add(ri,0);
903 >                }
904 >   else { //mismatch
905 >        loc.add(ri,poly_mis_score);
906 >        if (maxloc.score-loc.score>poly_dropoff_score) break;
907          }
908 < #endif
909 <     for (int iw=hlen;iw<hlen2;iw++) {
1116 <         //int* qv=(int32 *)(adapter3.chars()+iw);
1117 <         int qv=get3mer_value(adapter3.chars()+iw);
1118 <         fi=-1;
1119 <         //while ((fi=fast4rmatch(*qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
1120 <         while ((fi=w3_rmatch(qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
1121 <           extendMatch(seq.chars(), rlen, fi, adapter3.chars(),
1122 <                         a3len, iw, wordSize, l5,l3, a3segs);
1123 <           fi--;
1124 <           if (fi<imin) break;
1125 <           }
1126 <         } //for each wmer between hlen2 and hlen bases of the adaptor
1127 <     }
1128 < //lastly, analyze collected a3segs for a possible gapped alignment:
1129 < GList<CSegChain> segchains(false,true,false);
1130 < #ifdef DEBUG
1131 < if (debug && a3segs.Count()>0) {
1132 <   GMessage(">>>>>>>>>   Read: %s\n",seq.chars());
1133 <   }
1134 < #endif
1135 < for (int i=0;i<a3segs.Count();i++) {
1136 <   if (a3segs[i]->chain==NULL) {
1137 <       if (a3segs[i]->b.start>3) continue; //don't start a hopeless chain
1138 <       CSegChain* newchain=new CSegChain();
1139 <       newchain->setFreeItem(false);
1140 <       newchain->addSegPair(a3segs[i]);
1141 <       a3segs[i]->chain=newchain;
1142 <       segchains.Add(newchain); //just to free them when done
1143 <       }
1144 <   for (int j=i+1;j<a3segs.Count();j++) {
1145 <      CSegChain* chain=a3segs[i]->chain;
1146 <      if (chain->extendChain(a3segs[j])) {
1147 <          a3segs[j]->chain=chain;
1148 < #ifdef DEBUG
1149 <          if (debug) dbgPrintChain(*chain, adapter3.chars());
1150 < #endif      
1151 <          //save time by checking here if the extended chain is already acceptable for trimming
1152 <          if (chain->aend>(uint)(rlen-4) && chain->bstart<4 && chain->score>a_min_chain_score) {
1153 <            l5=0;
1154 <            l3=chain->astart-2;
1155 < #ifdef DEBUG
1156 <          if (debug && a3segs.Count()>0) {
1157 <            GMessage(">>> >> trimmed-3: %*s\n",l3-l5+1,seq.substr(l5,l3-l5+1).chars());
1158 <            }
1159 < #endif
1160 <            return true;
1161 <            }
1162 <          } //chain can be extended
908 >   if (maxloc.score<=loc.score) {
909 >      maxloc=loc;
910        }
911 <   } //collect segment alignments into chains
912 < */  
913 < return false; //no adapter parts found
911 >   }
912 > ri=maxloc.pos;
913 > if ((maxloc.score==poly_minScore && li==0) ||
914 >     (maxloc.score>poly_minScore && li<2)
915 >     || (maxloc.score>(poly_minScore*3) && li<8)) {
916 >    //adjust l5 to reflect this trimming of 5' end
917 >    l5=ri+1;
918 >    if (l5>rlen-1) l5=rlen-1;
919 >    return true;
920 >    }
921 > return false;
922 > }
923 >
924 > bool trim_adapter3(GStr& seq, int&l5, int &l3) {
925 > if (adapters3.Count()==0) return false;
926 > int rlen=seq.length();
927 > l5=0;
928 > l3=rlen-1;
929 > bool trimmed=false;
930 > GStr wseq(seq.chars());
931 > int wlen=rlen;
932 > for (int ai=0;ai<adapters3.Count();ai++) {
933 >  if (adapters3[ai].is_empty()) continue;
934 >  int alen=adapters3[ai].length();
935 >  GStr& aseq=adapters3[ai];
936 >  GXAlnInfo* r_bestaln=match_RightEnd(aseq.chars(), alen, wseq.chars(), wlen, gxmem_r, 74);
937 >  if (r_bestaln) {
938 >     trimmed=true;
939 >     //keep unmatched region on the left, if any
940 >     l3-=(wlen-r_bestaln->sl+1);
941 >     delete r_bestaln;
942 >     if (l3<0) l3=0;
943 >     if (l3-l5+1<min_read_len) return true;
944 >     wseq=seq.substr(l5,l3-l5+1);
945 >     wlen=wseq.length();
946 >     }
947 >  }//for each 5' adapter
948 >  return trimmed;
949   }
950  
951   bool trim_adapter5(GStr& seq, int&l5, int &l3) {
952 < //if (debug) GMessage("trim_adapter5 on: %s\n", seq.chars());
952 > if (adapters5.Count()==0) return false;
953   int rlen=seq.length();
954   l5=0;
955   l3=rlen-1;
956 < //try to see if adapter is fully included in the read
957 < int fi=-1;
958 < if ((fi=seq.index(adapter5))>=0) {
959 <   if (fi<rlen-fi-a5len) {//match is closer to the right end
960 <      l5=fi+a5len;
961 <      l3=rlen-1;
962 <      }
963 <    else {
964 <      l5=0;
965 <      l3=fi-1;
956 > bool trimmed=false;
957 > GStr wseq(seq.chars());
958 > int wlen=rlen;
959 > for (int ai=0;ai<adapters5.Count();ai++) {
960 >  if (adapters5[ai].is_empty()) continue;
961 >  int alen=adapters5[ai].length();
962 >  GStr& aseq=adapters5[ai];
963 >  GXAlnInfo* l_bestaln=match_LeftEnd(aseq.chars(), alen, adapters5[ai].pz,
964 >                         wseq.chars(), wlen, gxmem_l, 84);
965 >  if (l_bestaln) {
966 >     trimmed=true;
967 >     l5+=l_bestaln->sr;
968 >     delete l_bestaln;
969 >     if (l5>=rlen) l5=rlen-1;
970 >     if (l3-l5+1<min_read_len) return true;
971 >     wseq=seq.substr(l5,l3-l5+1);
972 >     wlen=wseq.length();
973 >     }
974 >  }//for each 5' adapter
975 >  return trimmed;
976 > }
977 >
978 > //convert qvs to/from phred64 from/to phread33
979 > void convertPhred(GStr& q) {
980 > for (int i=0;i<q.length();i++) q[i]+=qv_cvtadd;
981 > }
982 >
983 > void convertPhred(char* q, int len) {
984 > for (int i=0;i<len;i++) q[i]+=qv_cvtadd;
985 > }
986 >
987 > bool getFastxRec(GLineReader& fq, GStr& rseq, GStr& rqv,
988 >          GStr& rname, GStr& rinfo, GStr& infname) {
989 > rseq="";
990 > rqv="";
991 > rname="";
992 > rinfo="";
993 > if (fq.eof()) return false;
994 > char* l=fq.getLine();
995 > while (l!=NULL && (l[0]==0 || isspace(l[0]))) l=fq.getLine(); //ignore empty lines
996 > if (l==NULL) return false;
997 > /* if (rawFormat) {
998 >      //TODO: implement raw qseq parsing here
999 >      //if (raw type=N) then continue; //skip invalid/bad records
1000 >      } //raw qseq format
1001 > else { // FASTQ or FASTA */
1002 > isfasta=(l[0]=='>');
1003 > if (!isfasta && l[0]!='@') GError("Error: fasta/fastq record marker not found(%s)\n%s\n",
1004 >      infname.chars(), l);
1005 > GStr s(l);
1006 > rname=&(l[1]);
1007 > for (int i=0;i<rname.length();i++)
1008 >    if (rname[i]<=' ') {
1009 >       if (i<rname.length()-2) rinfo=rname.substr(i+1);
1010 >       rname.cut(i);
1011 >       break;
1012 >       }
1013 >  //now get the sequence
1014 > if ((l=fq.getLine())==NULL)
1015 >      GError("Error: unexpected EOF after header for read %s (%s)\n",
1016 >                   rname.chars(), infname.chars());
1017 > rseq=l; //this must be the DNA line
1018 > while ((l=fq.getLine())!=NULL) {
1019 >      //seq can span multiple lines
1020 >      if (l[0]=='>' || l[0]=='+') {
1021 >           fq.pushBack();
1022 >           break; //
1023 >           }
1024 >      rseq+=l;
1025 >      } //check for multi-line seq
1026 > if (!isfasta) { //reading fastq quality values, which can also be multi-line
1027 >    if ((l=fq.getLine())==NULL)
1028 >        GError("Error: unexpected EOF after sequence for %s\n", rname.chars());
1029 >    if (l[0]!='+') GError("Error: fastq qv header marker not detected!\n");
1030 >    if ((l=fq.getLine())==NULL)
1031 >        GError("Error: unexpected EOF after qv header for %s\n", rname.chars());
1032 >    rqv=l;
1033 >    //if (rqv.length()!=rseq.length())
1034 >    //  GError("Error: qv len != seq len for %s\n", rname.chars());
1035 >    while (rqv.length()<rseq.length() && ((l=fq.getLine())!=NULL)) {
1036 >      rqv+=l; //append to qv string
1037        }
1038 <   return true;
1039 <   }
1040 < #ifdef DEBUG
1041 < if (debug) GMessage(">TRIM5 >>   Read: %s\n",seq.chars());
1038 >    }// fastq
1039 > // } //<-- FASTA or FASTQ
1040 > rseq.upper();
1041 > return true;
1042 > }
1043 >
1044 > #ifdef GDEBUG
1045 > void showTrim(GStr& s, int l5, int l3) {
1046 >  if (l5>0) {
1047 >    color_bg(c_red);
1048 >    }
1049 >  for (int i=0;i<s.length()-1;i++) {
1050 >    if (i && i==l5) color_resetbg();
1051 >    fprintf(stderr, "%c", s[i]);
1052 >    if (i==l3) color_bg(c_red);
1053 >   }
1054 >  fprintf(stderr, "%c", s[s.length()-1]);
1055 >  color_reset();
1056 >  fprintf(stderr, "\n");
1057 > }
1058   #endif
1059  
1060 < CSegChain a5segs(true); //list of segment pairs to analyze later if no extendMatch succeeded
1060 > char process_read(GStr& rname, GStr& rseq, GStr& rqv, int &l5, int &l3) {
1061 > //returns 0 if the read was untouched, 1 if it was just trimmed
1062 > // and a trash code if it was trashed
1063 > l5=0;
1064 > l3=rseq.length()-1;
1065 > #ifdef GDEBUG
1066 >   //rseq.reverse();
1067 >   GMessage(">%s\n", rname.chars());
1068 >   GMessage("%s\n",rseq.chars());
1069 > #endif
1070 > if (l3-l5+1<min_read_len) {
1071 >   return 's';
1072 >   }
1073 > GStr wseq(rseq.chars());
1074 > GStr wqv(rqv.chars());
1075 > int w5=l5;
1076 > int w3=l3;
1077 > //first do the q-based trimming
1078 > if (qvtrim_qmin!=0 && !wqv.is_empty() && qtrim(wqv, w5, w3)) { // qv-threshold trimming
1079 >   if (w3-w5+1<min_read_len) {
1080 >     return 'Q'; //invalid read
1081 >     }
1082 >    //-- keep only the w5..w3 range
1083 >   l5=w5;
1084 >   l3=w3;
1085 >   wseq=wseq.substr(w5, w3-w5+1);
1086 >   if (!wqv.is_empty())
1087 >      wqv=wqv.substr(w5, w3-w5+1);
1088 >   } //qv trimming
1089 > // N-trimming on the remaining read seq
1090 > if (ntrim(wseq, w5, w3)) {
1091 >   //GMessage("before: %s\n",wseq.chars());
1092 >   //GMessage("after : %s (%d)\n",wseq.substr(w5,w3-w5+1).chars(),w3-w5+1);
1093 >   l5+=w5;
1094 >   l3-=(wseq.length()-1-w3);
1095 >   if (w3-w5+1<min_read_len) {
1096 >     return 'N'; //to be trashed
1097 >     }
1098 >    //-- keep only the w5..w3 range
1099 >   wseq=wseq.substr(w5, w3-w5+1);
1100 >   if (!wqv.is_empty())
1101 >      wqv=wqv.substr(w5, w3-w5+1);
1102 >   w5=0;
1103 >   w3=wseq.length()-1;
1104 >   }
1105 > char trim_code;
1106 > do {
1107 >  trim_code=0;
1108 >  if (trim_poly5(wseq, w5, w3, polyA_seed)) {
1109 >      trim_code='A';
1110 >      }
1111 >  else if (trim_poly5(wseq, w5, w3, polyT_seed)) {
1112 >      trim_code='T';
1113 >      }
1114 >  else if (trim_adapter5(wseq, w5, w3)) {
1115 >      trim_code='5';
1116 >      }
1117 >  if (trim_code) {
1118 >     #ifdef GDEBUG
1119 >      GMessage("#### TRIM by '%c' code ( w5-w3 = %d-%d ):\n",trim_code, w5,w3);
1120 >      showTrim(wseq, w5, w3);
1121 >     #endif
1122 >     int trimlen=wseq.length()-(w3-w5+1);
1123 >     num_trimmed5++;
1124 >     if (trimlen<min_trimmed5)
1125 >         min_trimmed5=trimlen;
1126 >     l5+=w5;
1127 >     l3-=(wseq.length()-1-w3);
1128 >     if (w3-w5+1<min_read_len) {
1129 >         return trim_code;
1130 >         }
1131 >      //-- keep only the w5..w3 range
1132 >      wseq=wseq.substr(w5, w3-w5+1);
1133 >      if (!wqv.is_empty())
1134 >         wqv=wqv.substr(w5, w3-w5+1);
1135 >      }// trimmed at 5' end
1136 > } while (trim_code);
1137 >
1138 > do {
1139 >  trim_code=0;
1140 >  if (trim_poly3(wseq, w5, w3, polyA_seed)) {
1141 >      trim_code='A';
1142 >      }
1143 >  else if (trim_poly3(wseq, w5, w3, polyT_seed)) {
1144 >      trim_code='T';
1145 >      }
1146 >  else if (trim_adapter3(wseq, w5, w3)) {
1147 >      trim_code='3';
1148 >      }
1149 >  if (trim_code) {
1150 >     #ifdef GDEBUG
1151 >     GMessage("#### TRIM by '%c' code ( w5-w3 = %d-%d ):\n",trim_code, w5,w3);
1152 >     showTrim(wseq, w5, w3);
1153 >     #endif
1154 >     int trimlen=wseq.length()-(w3-w5+1);
1155 >     num_trimmed3++;
1156 >     if (trimlen<min_trimmed3)
1157 >         min_trimmed3=trimlen;
1158 >     l5+=w5;
1159 >     l3-=(wseq.length()-1-w3);
1160 >     if (w3-w5+1<min_read_len) {
1161 >         return trim_code;
1162 >         }
1163 >      //-- keep only the w5..w3 range
1164 >      wseq=wseq.substr(w5, w3-w5+1);
1165 >      if (!wqv.is_empty())
1166 >         wqv=wqv.substr(w5, w3-w5+1);
1167 >      }//trimming at 3' end
1168 > } while (trim_code);
1169 >
1170 >
1171 > if (doCollapse) {
1172 >   //keep read for later
1173 >   FqDupRec* dr=dhash.Find(wseq.chars());
1174 >   if (dr==NULL) { //new entry
1175 >          //if (prefix.is_empty())
1176 >             dhash.Add(wseq.chars(),
1177 >                  new FqDupRec(&wqv, rname.chars()));
1178 >          //else dhash.Add(wseq.chars(), new FqDupRec(wqv.chars(),wqv.length()));
1179 >         }
1180 >      else
1181 >         dr->add(wqv);
1182 >   } //collapsing duplicates
1183 > else { //not collapsing duplicates
1184 >   //apply the dust filter now
1185 >   if (doDust) {
1186 >     int dustbases=dust(wseq);
1187 >     if (dustbases>(wseq.length()>>1)) {
1188 >        return 'D';
1189 >        }
1190 >     }
1191 >   } //not collapsing duplicates
1192 > return (l5>0 || l3<rseq.length()-1) ? 1 : 0;
1193 > }
1194 >
1195 > void printHeader(FILE* f_out, char recmarker, GStr& rname, GStr& rinfo) {
1196 > //GMessage("printing Header..%c%s\n",recmarker, rname.chars());
1197 > if (rinfo.is_empty()) fprintf(f_out, "%c%s\n",recmarker,rname.chars());
1198 >  else fprintf(f_out, "%c%s %s\n",recmarker, rname.chars(), rinfo.chars());
1199 > }
1200  
1201 < //try the easy way out first - look for an exact match of 11 bases
1202 < int fdlen=11;
1203 <  if (a5len<16) {
1204 <   fdlen=a5len>>1;
1205 <   }
1206 < if (fdlen>4) {
1207 <     GStr rstart=seq.substr(1,fdlen); //skip the first base as it's sometimes bogus
1200 <     if ((fi=adapter5.index(rstart))>=0) {
1201 < #ifdef DEBUG
1202 <       if (debug) GMessage("  W11match found: %*s\n", 1+fdlen, (adapter3.substr(fi,fdlen)).chars());
1203 < #endif
1204 <       if (extendMatch(seq.chars(), rlen, 1,
1205 <                     adapter5.chars(), a5len, fi,  fdlen, l5,l3, a5segs, true))
1206 <           return true;
1201 > void writeRead(FILE* f_out, GStr& rname, GStr& rinfo, GStr& rseq, GStr& rqv, int& outcounter) {
1202 >   outcounter++;
1203 >   bool asFasta=(rqv.is_empty() || fastaOutput);
1204 >   if (asFasta) {
1205 >    if (prefix.is_empty()) {
1206 >       printHeader(f_out, '>',rname,rinfo);
1207 >       fprintf(f_out, "%s\n", rseq.chars()); //plain one-line fasta for now
1208         }
1209 <     //another easy case: last 11 characters of the adaptor found as a substring of the read
1210 <     GStr bstr=adapter5.substr(-fdlen);
1211 <     if ((fi=seq.index(bstr))>=0) {
1211 < #ifdef DEBUG
1212 <       if (debug) GMessage("  A11match found: %*s\n", fi+fdlen, bstr.chars());
1213 < #endif
1214 <       if (extendMatch(seq.chars(), rlen, fi,
1215 <                     adapter5.chars(), a5len, a5len-fdlen,  fdlen, l5,l3,a5segs,true))
1216 <          return true;
1209 >      else {
1210 >       fprintf(f_out, ">%s%08d\n%s\n", prefix.chars(), outcounter,
1211 >                          rseq.chars());
1212         }
1218     } //tried to matching at most 11 bases first
1219    
1220 //-- no easy cases, do the wmer hashing for the last 12 bases of the adaptor
1221 //-- only extend a wmer if it matches in the 5' (beginning) region of the read
1222 int wordSize=3;
1223 int hlen=12;
1224 if (hlen>a5len-wordSize) hlen=a5len-wordSize;
1225 int imax=rlen>>1; //first half of the read, right boundary for the wmer match
1226 if (imax<a5len) { imax=GMIN(a5len, rlen-wordSize); }
1227 for (int iw=0;iw<=hlen;iw++) {
1228   int apstart=a5len-iw-wordSize;
1229   fi=0;
1230   //int* qv=(int32 *)(adapter5.chars()+apstart);
1231   int qv=get3mer_value(adapter5.chars()+apstart);
1232   //while ((fi=fast4match(*qv, seq.chars(), rlen, fi))>=0 && fi<=imax) {
1233   while ((fi=w3_match(qv, seq.chars(), rlen, fi))>=0 && fi<=imax) {
1234 #ifdef DEBUG
1235     if (debug) GMessage("    Wmatch found: %*s\n", fi+wordSize, (adapter5.substr(apstart,wordSize)).chars());
1236 #endif
1237     if (extendMatch(seq.chars(), rlen, fi, adapter5.chars(),
1238                a5len, apstart, wordSize, l5,l3, a5segs, true)) return true;
1239     fi++;
1240     if (fi>imax) break;
1213       }
1214 <   } //for each wmer in the last hlen bases of the adaptor
1215 < /*
1216 <
1217 < //couldn't find a good trimming extension, hash 12 more bases of the adapter to collect more segment pairs there
1218 < //but only do this if we already have segment pairs collected in the last 12 bases of the adapter
1219 < if (a5segs.bend<(uint)(a5len-3) || a5segs.bstart>(uint)(a5len-hlen+4)) return false;
1220 < int hlen2=a5len-wordSize;
1221 < //if (hlen2>a5len-wordSize) hlen2=a5len-wordSize;
1222 < #ifdef DEBUG
1251 <      if (debug && a5segs.Count()>0) {
1252 <        GMessage("  >>>>>2nd. hash: %s\n",seq.chars());
1253 <        }
1254 < #endif
1255 < if (hlen2>hlen) {
1256 <     for (int iw=hlen+1;iw<=hlen2;iw++) {
1257 <         int apstart=a5len-iw-wordSize;
1258 <         fi=0;
1259 <         //int* qv=(int32 *)(adapter5.chars()+apstart);
1260 <         int qv=get3mer_value(adapter5.chars()+apstart);
1261 <         //while ((fi=fast4match(*qv, seq.chars(), rlen, fi))>=0 && fi<=imax) {
1262 <         while ((fi=w3_match(qv, seq.chars(), rlen, fi))>=0 && fi<=imax) {
1263 <           extendMatch(seq.chars(), rlen, fi, adapter5.chars(),
1264 <                      a5len, apstart, wordSize, l5,l3, a5segs, true);
1265 <           fi++;
1266 <           if (fi>imax) break;
1267 <           }
1268 <         } //for each wmer between hlen2 and hlen bases of the adaptor
1214 >   else {  //fastq
1215 >    if (convert_phred) convertPhred(rqv);
1216 >    if (prefix.is_empty()) {
1217 >       printHeader(f_out, '@', rname, rinfo);
1218 >       fprintf(f_out, "%s\n+\n%s\n", rseq.chars(), rqv.chars());
1219 >       }
1220 >      else
1221 >       fprintf(f_out, "@%s_%08d\n%s\n+\n%s\n", prefix.chars(), outcounter,
1222 >                          rseq.chars(),rqv.chars() );
1223       }
1224 < if (a5segs.bend<(uint)(a5len-3) || a5segs.bstart>(uint)(a5len-hlen+4)) return false;
1225 < // lastly, analyze collected a5segs for a possible gapped alignment:
1226 < GList<CSegChain> segchains(false,true,false);
1227 < #ifdef DEBUG
1228 < if (debug && a5segs.Count()>0) {
1229 <   GMessage(">>>>>>>>>   Read: %s\n",seq.chars());
1224 > }
1225 >
1226 > void trash_report(char trashcode, GStr& rname, FILE* freport) {
1227 > if (freport==NULL || trashcode<=' ') return;
1228 > if (trashcode=='3' || trashcode=='5') {
1229 >   fprintf(freport, "%s\ta%c\n",rname.chars(),trashcode);
1230     }
1231 < #endif
1232 < for (int i=0;i<a5segs.Count();i++) {
1233 <   if (a5segs[i]->chain==NULL) {
1234 <       if (a5segs[i]->b.end<(int)(a5len-4)) continue; //don't start a hopeless chain
1235 <       CSegChain* newchain=new CSegChain(true);
1236 <       newchain->setFreeItem(false);
1237 <       newchain->addSegPair(a5segs[i]);
1238 <       a5segs[i]->chain=newchain;
1239 <       segchains.Add(newchain); //just to free them when done
1240 <       }
1241 <   for (int j=i+1;j<a5segs.Count();j++) {
1242 <      CSegChain* chain=a5segs[i]->chain;
1243 <      if (chain->extendChain(a5segs[j])) {
1244 <         a5segs[j]->chain=chain;
1245 < #ifdef DEBUG
1246 <         if (debug) dbgPrintChain(*chain, adapter5.chars());
1247 < #endif      
1248 <      //save time by checking here if the extended chain is already acceptable for trimming
1295 <         if (chain->bend>(uint)(a5len-3) && chain->astart<4 && chain->score>a_min_chain_score) {
1296 <            l5=chain->aend;
1297 <            l3=rlen-1;
1298 <            return true;
1299 <            }
1300 <         } //chain can be extended
1301 <      }
1302 <   } //collect segment alignments into chains
1303 < */
1304 < return false; //no adapter parts found
1231 > else {
1232 >   fprintf(freport, "%s\t%c\n",rname.chars(),trashcode);
1233 >   }
1234 > //tcounter++;
1235 > }
1236 >
1237 > GStr getFext(GStr& s, int* xpos=NULL) {
1238 > //s must be a filename without a path
1239 > GStr r("");
1240 > if (xpos!=NULL) *xpos=0;
1241 > if (s.is_empty() || s=="-") return r;
1242 > int p=s.rindex('.');
1243 > int d=s.rindex('/');
1244 > if (p<=0 || p>s.length()-2 || p<s.length()-7 || p<d) return r;
1245 > r=s.substr(p+1);
1246 > if (xpos!=NULL) *xpos=p+1;
1247 > r.lower();
1248 > return r;
1249   }
1250  
1251 < //convert qvs to/from phred64 from/to phread33
1252 < void convertPhred(GStr& q) {
1253 < for (int i=0;i<q.length();i++) q[i]+=qv_cvtadd;
1251 > void baseFileName(GStr& fname) {
1252 > //remove all known extensions, like .txt,fq,fastq,fasta,fa)(.gz .gzip .bz2 .bzip2) .
1253 > int xpos=0;
1254 > GStr fext=getFext(fname, &xpos);
1255 > if (xpos<=1) return;
1256 > bool extdel=false;
1257 > GStr f2;
1258 > if (fext=="z" || fext=="zip") {
1259 >   extdel=true;
1260 >   }
1261 >  else if (fext.length()>=2) {
1262 >   f2=fext.substr(0,2);
1263 >   extdel=(f2=="gz" || f2=="bz");
1264 >   }
1265 > if (extdel) {
1266 >   fname.cut(xpos-1);
1267 >   fext=getFext(fname, &xpos);
1268 >   if (xpos<=1) return;
1269 >   }
1270 > extdel=false;
1271 > if (fext=="f" || fext=="fq" || fext=="txt" || fext=="seq" || fext=="sequence") {
1272 >   extdel=true;
1273 >   }
1274 >  else if (fext.length()>=2) {
1275 >   extdel=(fext.substr(0,2)=="fa");
1276 >   }
1277 > if (extdel) fname.cut(xpos-1);
1278 > GStr fncp(fname);
1279 > fncp.lower();
1280 > fncp.chomp("seq");
1281 > fncp.chomp("sequence");
1282 > fncp.trimR("_.");
1283 > if (fncp.length()<fname.length()) fname.cut(fncp.length());
1284   }
1285  
1286 < void convertPhred(char* q, int len) {
1287 < for (int i=0;i<len;i++) q[i]+=qv_cvtadd;
1286 > FILE* prepOutFile(GStr& infname, GStr& pocmd) {
1287 >  FILE* f_out=NULL;
1288 >  GStr fname(getFileName(infname.chars()));
1289 >  //eliminate known extensions
1290 >  baseFileName(fname);
1291 >  if (outsuffix.is_empty() || outsuffix=="-") { return stdout; }
1292 >    else if (pocmd.is_empty()) {
1293 >               GStr oname(fname);
1294 >               oname.append('.');
1295 >               oname.append(outsuffix);
1296 >               f_out=fopen(oname.chars(),"w");
1297 >               if (f_out==NULL) GError("Error: cannot create '%s'\n",oname.chars());
1298 >               }
1299 >            else {
1300 >              GStr oname(">");
1301 >              oname.append(fname);
1302 >              oname.append('.');
1303 >              oname.append(outsuffix);
1304 >              pocmd.append(oname);
1305 >              f_out=popen(pocmd.chars(), "w");
1306 >              if (f_out==NULL) GError("Error: cannot popen '%s'\n",pocmd.chars());
1307 >              }
1308 > return f_out;
1309 > }
1310 >
1311 > void guess_unzip(GStr& fname, GStr& picmd) {
1312 > GStr fext=getFext(fname);
1313 > if (fext=="gz" || fext=="gzip" || fext=="z") {
1314 >    picmd="gzip -cd ";
1315 >    }
1316 >   else if (fext=="bz2" || fext=="bzip2" || fext=="bz" || fext=="bzip") {
1317 >    picmd="bzip2 -cd ";
1318 >    }
1319   }
1320  
1321 + void addAdapter(GVec<CASeqData>& adapters, GStr& seq) {
1322 + //TODO: prepare CASeqData here, and collect hexamers as well
1323 +
1324 + }
1325 +
1326 +
1327 + int loadAdapters(const char* fname) {
1328 +  GLineReader lr(fname);
1329 +  char* l;
1330 +  while ((l=lr.nextLine())!=NULL) {
1331 +   if (lr.length()<=3 || l[0]=='#') continue;
1332 +   if ( l[0]==' ' || l[0]=='\t' || l[0]==',' ||
1333 +        l[0]==';'|| l[0]==':' ) {
1334 +      int i=1;
1335 +      while (l[i]!=0 && isspace(l[i])) {
1336 +        i++;
1337 +        }
1338 +      if (l[i]!=0) {
1339 +        GStr s(&(l[i]));
1340 +      #ifdef GDEBUG
1341 +          //s.reverse();
1342 +      #endif
1343 +        addAdapter(adapters3, s);
1344 +        continue;
1345 +        }
1346 +      }
1347 +    else {
1348 +      GStr s(l);
1349 +      s.startTokenize("\t ;,:");
1350 +      GStr a5,a3;
1351 +      if (s.nextToken(a5))
1352 +         s.nextToken(a3);
1353 +      a5.upper();
1354 +      a3.upper();
1355 +     #ifdef GDEBUG
1356 +     //   a5.reverse();
1357 +     //   a3.reverse();
1358 +     #endif
1359 +      addAdapter(adapters5, a5);
1360 +      addAdapter(adapters3, a3);
1361 +      }
1362 +   }
1363 +   return adapters5.Count()+adapters3.Count();
1364 + }
1365 +
1366 + void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
1367 +                       GStr& s, GStr& infname, GStr& infname2) {
1368 + // uses outsuffix to generate output file names and open file handles as needed
1369 + infname="";
1370 + infname2="";
1371 + f_in=NULL;
1372 + f_in2=NULL;
1373 + f_out=NULL;
1374 + f_out2=NULL;
1375 + //analyze outsuffix intent
1376 + GStr pocmd;
1377 + if (outsuffix=="-") {
1378 +    f_out=stdout;
1379 +    }
1380 +   else {
1381 +    GStr ox=getFext(outsuffix);
1382 +    if (ox.length()>2) ox=ox.substr(0,2);
1383 +    if (ox=="gz") pocmd="gzip -9 -c ";
1384 +        else if (ox=="bz") pocmd="bzip2 -9 -c ";
1385 +    }
1386 + if (s=="-") {
1387 +    f_in=stdin;
1388 +    infname="stdin";
1389 +    f_out=prepOutFile(infname, pocmd);
1390 +    return;
1391 +    } // streaming from stdin
1392 + s.startTokenize(",:");
1393 + s.nextToken(infname);
1394 + bool paired=s.nextToken(infname2);
1395 + if (fileExists(infname.chars())==0)
1396 +    GError("Error: cannot find file %s!\n",infname.chars());
1397 + GStr fname(getFileName(infname.chars()));
1398 + GStr picmd;
1399 + guess_unzip(fname, picmd);
1400 + if (picmd.is_empty()) {
1401 +   f_in=fopen(infname.chars(), "r");
1402 +   if (f_in==NULL) GError("Error opening file '%s'!\n",infname.chars());
1403 +   }
1404 +  else {
1405 +   picmd.append(infname);
1406 +   f_in=popen(picmd.chars(), "r");
1407 +   if (f_in==NULL) GError("Error at popen %s!\n", picmd.chars());
1408 +   }
1409 + if (f_out==stdout) {
1410 +   if (paired) GError("Error: output suffix required for paired reads\n");
1411 +   return;
1412 +   }
1413 + f_out=prepOutFile(infname, pocmd);
1414 + if (!paired) return;
1415 + if (doCollapse) GError("Error: sorry, -C option cannot be used with paired reads!\n");
1416 + // ---- paired reads:-------------
1417 + if (fileExists(infname2.chars())==0)
1418 +     GError("Error: cannot find file %s!\n",infname2.chars());
1419 + picmd="";
1420 + GStr fname2(getFileName(infname2.chars()));
1421 + guess_unzip(fname2, picmd);
1422 + if (picmd.is_empty()) {
1423 +   f_in2=fopen(infname2.chars(), "r");
1424 +   if (f_in2==NULL) GError("Error opening file '%s'!\n",infname2.chars());
1425 +   }
1426 +  else {
1427 +   picmd.append(infname2);
1428 +   f_in2=popen(picmd.chars(), "r");
1429 +   if (f_in2==NULL) GError("Error at popen %s!\n", picmd.chars());
1430 +   }
1431 + f_out2=prepOutFile(infname2, pocmd);
1432 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines