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   FILE* freport=NULL;
66 +
67   bool debug=false;
68   bool verbose=false;
69   bool doCollapse=false;
70   bool doDust=false;
71 + bool doPolyTrim=true;
72 + bool fastaOutput=false;
73   bool trashReport=false;
74   //bool rawFormat=false;
75   int min_read_len=16;
# Line 53 | Line 77
77   int dust_cutoff=16;
78   bool isfasta=false;
79   bool convert_phred=false;
80 + GStr outsuffix; // -o
81   GStr prefix;
82 < GStr adapter3;
83 < GStr adapter5;
84 <
85 < int qvtrim_min=0;
82 > GStr zcmd;
83 > int num_trimmed5=0;
84 > int num_trimmed3=0;
85 > int num_trimmedN=0;
86 > int num_trimmedQ=0;
87 > int min_trimmed5=INT_MAX;
88 > int min_trimmed3=INT_MAX;
89  
90 + int qvtrim_qmin=0;
91 + int qvtrim_max=0;  //for -q, do not trim at 3'-end more than this number of bases
92   int qv_phredtype=0; // could be 64 or 33 (0 means undetermined yet)
93   int qv_cvtadd=0; //could be -31 or +31
94  
95 < int a3len=0;
96 < int a5len=0;
97 < // adaptor matching metrics -- for extendMatch() function
98 < const int a_m_score=2; //match score
99 < const int a_mis_score=-3; //mismatch
100 < const int a_dropoff_score=7;
101 < const int a_min_score=8; //an exact match of 4 bases at the proper ends WILL be trimmed
102 < const int a_min_chain_score=15; //for gapped alignments
103 <
104 < class CSegChain;
105 <
106 < class CSegPair {
107 <  public:
108 <   GSeg a;
79 <   GSeg b; //the adapter segment
80 <   int score;
81 <   int flags;
82 <   CSegChain* chain;
83 <   CSegPair(int astart=0, int aend=0, int bstart=0, int bend=0, int mscore=0):a(astart,aend),b(bstart, bend) {
84 <      score=mscore;
85 <      if (score==0) score=a.len()*a_m_score;
86 <      flags=0;
87 <      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);
143 <       }
144 <     }
145 <    else {
146 <     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 <     }
168 <
169 < }
95 > // adaptor matching metrics -- for X-drop ungapped extension
96 > const int match_reward=2;
97 > const int mismatch_penalty=3;
98 > const int Xdrop=8;
99 >
100 > const int poly_m_score=2; //match score
101 > const int poly_mis_score=-3; //mismatch
102 > const int poly_dropoff_score=7;
103 > int poly_minScore=12; //i.e. an exact match of 6 bases at the proper ends WILL be trimmed
104 >
105 > const char *polyA_seed="AAAA";
106 > const char *polyT_seed="TTTT";
107 > GVec<GStr> adapters5;
108 > GVec<GStr> adapters3;
109  
110 < class CSegChain:public GList<CSegPair> {
111 < 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 < };
110 > CGreedyAlignData* gxmem_l=NULL;
111 > CGreedyAlignData* gxmem_r=NULL;
112  
113   // element in dhash:
114   class FqDupRec {
# Line 273 | Line 147
147    if (!s.is_empty()) {
148        if (s=='-') f=stdout;
149        else {
150 <       f=fopen(s,"w");
150 >       f=fopen(s.chars(),"w");
151         if (f==NULL) GError("Error creating file: %s\n", s.chars());
152         }
153       }
# Line 284 | Line 158
158  
159   GHash<FqDupRec> dhash; //hash to keep track of duplicates
160  
161 + int loadAdapters(const char* fname);
162 +
163 + void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
164 +                       GStr& s, GStr& infname, GStr& infname2);
165 + // uses outsuffix to generate output file names and open file handles as needed
166 +
167 + void writeRead(FILE* f_out, GStr& rname, GStr& rinfo, GStr& rseq, GStr& rqv, int& outcounter);
168 + void trash_report(char trashcode, GStr& rname, FILE* freport);
169 +
170 + bool getFastxRec(GLineReader& fq, GStr& rseq, GStr& rqv,
171 +          GStr& rname, GStr& rinfo, GStr& infname);
172 +
173 + char process_read(GStr& rname, GStr& rseq, GStr& rqv, int &l5, int &l3);
174 + //returns 0 if the read was untouched, 1 if it was trimmed and a trash code if it was trashed
175 +
176   bool ntrim(GStr& rseq, int &l5, int &l3); //returns true if any trimming occured
177   bool qtrim(GStr& qvs, int &l5, int &l3); //return true if any trimming occured
178   int dust(GStr& seq);
179 < bool trim_adapter3(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
179 > bool trim_poly5(GStr &seq, int &l5, int &l3, const char* poly_seed); //returns true if any trimming occured
180 > bool trim_poly3(GStr &seq, int &l5, int &l3, const char* poly_seed);
181   bool trim_adapter5(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
182 + bool trim_adapter3(GStr& seq, int &l5, int &l3);
183  
184   void convertPhred(char* q, int len);
185   void convertPhred(GStr& q);
186  
187   int main(int argc, char * const argv[]) {
188 <  GArgs args(argc, argv, "YQDCVl:d:3:5:m:n:r:p:q:o:");
188 >  GArgs args(argc, argv, "YQDCVAl:d:3:5:m:n:r:p:q:f:t:o:z:a:");
189    int e;
299  int icounter=0; //counter for input reads
300  int outcounter=0; //counter for output reads
190    if ((e=args.isError())>0) {
191        GMessage("%s\nInvalid argument: %s\n", USAGE, argv[e]);
192        exit(224);
193        }
194    debug=(args.getOpt('Y')!=NULL);
195 <  debug=(args.getOpt('V')!=NULL);
195 >  verbose=(args.getOpt('V')!=NULL);
196    convert_phred=(args.getOpt('Q')!=NULL);
197    doCollapse=(args.getOpt('C')!=NULL);
198    doDust=(args.getOpt('D')!=NULL);
199 +  if (args.getOpt('A')) doPolyTrim=false;
200    /*
201    rawFormat=(args.getOpt('R')!=NULL);
202    if (rawFormat) {
# Line 327 | Line 217
217       }
218    s=args.getOpt('q');
219    if (!s.is_empty()) {
220 <     qvtrim_min=s.asInt();
220 >     qvtrim_qmin=s.asInt();
221 >     }
222 >  s=args.getOpt('t');
223 >  if (!s.is_empty()) {
224 >     qvtrim_max=s.asInt();
225       }
226    s=args.getOpt('p');
227    if (!s.is_empty()) {
# Line 343 | Line 237
237         else
238           GMessage("%s\nInvalid value for -p option (can only be 64 or 33)!\n",USAGE);
239       }
240 <  if (args.getOpt('3')!=NULL) {
241 <    adapter3=args.getOpt('3');
242 <    adapter3.upper();
243 <    a3len=adapter3.length();
244 <    }
245 <  if (args.getOpt('5')!=NULL) {
246 <    adapter5=args.getOpt('5');
247 <    adapter5.upper();
248 <    a5len=adapter5.length();
240 >  s=args.getOpt('f');
241 >  if (!s.is_empty()) {
242 >   loadAdapters(s.chars());
243 >   }
244 >  bool fileAdapters=adapters5.Count()+adapters3.Count();
245 >  s=args.getOpt('5');
246 >  if (!s.is_empty()) {
247 >    if (fileAdapters)
248 >      GError("Error: options -5 and -f cannot be used together!\n");
249 >    s.upper();
250 >    adapters5.Add(s);
251      }
252 +  s=args.getOpt('3');
253 +  if (!s.is_empty()) {
254 +    if (fileAdapters)
255 +      GError("Error: options -3 and -f cannot be used together!\n");
256 +      s.upper();
257 +      adapters3.Add(s);
258 +    }
259 +  s=args.getOpt('y');
260 +  if (!s.is_empty()) {
261 +     int minmatch=s.asInt();
262 +     poly_minScore=minmatch*poly_m_score;
263 +     }
264 +  
265 +  if (args.getOpt('o')!=NULL) outsuffix=args.getOpt('o');
266 +                         else outsuffix="-";
267    trashReport=  (args.getOpt('r')!=NULL);
268 <  if (args.startNonOpt()==0) {
268 >  int fcount=args.startNonOpt();
269 >  if (fcount==0) {
270      GMessage(USAGE);
271      exit(224);
272      }
273 <
274 <  openfw(f_out, args, 'o');
275 <  if (f_out==NULL) f_out=stdout;
273 >   if (fcount>1 && doCollapse) {
274 >    GError("%s Sorry, the -C option only works with a single input.\n", USAGE);
275 >    }
276 >  //openfw(f_out, args, 'o');
277 >  //if (f_out==NULL) f_out=stdout;
278    if (trashReport)
279      openfw(freport, args, 'r');
280    char* infile=NULL;
281 +
282 +  if (adapters5.Count()>0)
283 +    gxmem_l=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop-2);
284 +  if (adapters3.Count()>0)
285 +    gxmem_r=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop);
286 +
287    while ((infile=args.nextNonOpt())!=NULL) {
288 <    GStr infname(infile);
289 <    if (strcmp(infile,"-")==0) {
290 <       f_in=stdin; infname="stdin"; }
291 <     else {
292 <        f_in=fopen(infile,"r");
293 <        if (f_in==NULL)
294 <            GError("Cannot open input file %s!\n",infile);
295 <        }
296 <     GLineReader fq(f_in);
297 <     char* l=NULL;
298 <     while ((l=fq.getLine())!=NULL) {
299 <        GStr rname; //current read name
300 <        GStr rseq;  //current read sequence
301 <        GStr rqv;   //current read quality values
302 <        GStr s;
303 <        /* if (rawFormat) {
304 <          //TODO: implement qseq parsing here
305 <          //if (raw type=N) then continue; //skip invalid/bad records
306 <          
307 <          } //raw qseq format
308 <         else { // FASTQ or FASTA */
309 <          isfasta=(l[0]=='>');
310 <          if (!isfasta && l[0]!='@') GError("Error: fastq record marker not detected!\n");
311 <          s=l;
312 <          rname=&(l[1]);
313 <          icounter++;
314 <          for (int i=0;i<rname.length();i++)
315 <            if (rname[i]<=' ') { rname.cut(i); break; }
316 <          //now get the sequence
317 <          if ((l=fq.getLine())==NULL)
318 <              GError("Error: unexpected EOF after header for %s\n",rname.chars());
319 <          rseq=l; //this must be the DNA line
320 <          while ((l=fq.getLine())!=NULL) {
321 <              //seq can span multiple lines
322 <              if (l[0]=='>' || l[0]=='+') {
323 <                   fq.pushBack();
324 <                   break; //
288 >    //for each input file
289 >    int incounter=0; //counter for input reads
290 >    int outcounter=0; //counter for output reads
291 >    int trash_s=0; //too short from the get go
292 >    int trash_Q=0;
293 >    int trash_N=0;
294 >    int trash_D=0;
295 >    int trash_poly=0;
296 >    int trash_A3=0;
297 >    int trash_A5=0;
298 >    s=infile;
299 >    GStr infname;
300 >    GStr infname2;
301 >    FILE* f_in=NULL;
302 >    FILE* f_in2=NULL;
303 >    FILE* f_out=NULL;
304 >    FILE* f_out2=NULL;
305 >    bool paired_reads=false;
306 >    setupFiles(f_in, f_in2, f_out, f_out2, s, infname, infname2);
307 >    GLineReader fq(f_in);
308 >    GLineReader* fq2=NULL;
309 >    if (f_in2!=NULL) {
310 >       fq2=new GLineReader(f_in2);
311 >       paired_reads=true;
312 >       }
313 >    GStr rseq, rqv, seqid, seqinfo;
314 >    GStr rseq2, rqv2, seqid2, seqinfo2;
315 >    while (getFastxRec(fq, rseq, rqv, seqid, seqinfo, infname)) {
316 >       incounter++;
317 >       int a5=0, a3=0, b5=0, b3=0;
318 >       char tcode=0, tcode2=0;
319 >       tcode=process_read(seqid, rseq, rqv, a5, a3);
320 >       if (fq2!=NULL) {
321 >            getFastxRec(*fq2, rseq2, rqv2, seqid2, seqinfo2, infname2);
322 >            if (seqid.substr(0,seqid.length()-1)!=seqid2.substr(0,seqid2.length()-1)) {
323 >               GError("Error: no paired match for read %s vs %s (%s,%s)\n",
324 >                  seqid.chars(), seqid2.chars(), infname.chars(), infname2.chars());
325 >               }
326 >            tcode2=process_read(seqid2, rseq2, rqv2, b5, b3);
327 >            //decide what to do with this pair and print rseq2 if the pair makes it
328 >            if (tcode>1 && tcode2<=1) {
329 >               //"untrash" rseq
330 >               if (a3-a5+1<min_read_len) {
331 >                   a5=1;
332 >                   if (a3<min_read_len) { a3= GMIN(rseq.length()-1, min_read_len+1); }
333                     }
334 <              rseq+=l;
335 <              } //check for multi-line seq
336 <          if (!isfasta) { //reading fastq quality values, which can also be multi-line
337 <            if ((l=fq.getLine())==NULL)
338 <                GError("Error: unexpected EOF after sequence for %s\n", rname.chars());
339 <            if (l[0]!='+') GError("Error: fastq qv header marker not detected!\n");
340 <            if ((l=fq.getLine())==NULL)
341 <                GError("Error: unexpected EOF after qv header for %s\n", rname.chars());
342 <            rqv=l;
343 <            //if (rqv.length()!=rseq.length())
344 <            //  GError("Error: qv len != seq len for %s\n", rname.chars());
345 <            while (rqv.length()<rseq.length() && ((l=fq.getLine())!=NULL)) {
346 <              rqv+=l; //append to qv string
347 <              }
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;
334 >               tcode=1;
335 >               }
336 >             else if (tcode<=1 && tcode2>1) {
337 >               //"untrash" rseq2
338 >               if (b3-b5+1<min_read_len) {
339 >                   b5=1;
340 >                   if (b3<min_read_len) { b3= GMIN((rseq2.length()-1),(min_read_len+1)); }
341 >                   }
342 >               tcode2=1;
343 >               }
344 >            if (tcode<=1) { //trimmed or left intact -- write it!
345 >               if (tcode>0) {
346 >                 rseq2=rseq2.substr(b5,b3-b5+1);
347 >                 if (!rqv2.is_empty()) rqv2=rqv2.substr(b5,b3-b5+1);
348                   }
349 <              //-- keep only the l5..l3 range
350 <              rseq=rseq.substr(l5, l3-l5+1);
351 <              if (!rqv.is_empty())
352 <                 rqv=rqv.substr(l5, l3-l5+1);
353 <              }//some adapter was trimmed
354 <           } //adapter trimming
355 <        if (doCollapse) {
356 <           //keep read for later
357 <           FqDupRec* dr=dhash.Find(rseq.chars());
358 <           if (dr==NULL) { //new entry
359 <                  //if (prefix.is_empty())
360 <                     dhash.Add(rseq.chars(),
361 <                          new FqDupRec(&rqv, rname.chars()));
362 <                  //else dhash.Add(rseq.chars(), new FqDupRec(rqv.chars(),rqv.length()));
349 >               int nocounter=0;
350 >               writeRead(f_out2, seqid2, seqinfo2, rseq2, rqv2, nocounter);
351 >               }
352 >            } //pair read
353 >       if (tcode>1) { //trashed
354 >         #ifdef GDEBUG
355 >         GMessage(" !!!!TRASH => 'N'\n");
356 >         #endif
357 >          if (tcode=='s') trash_s++;
358 >          else if (tcode=='A' || tcode=='T') trash_poly++;
359 >            else if (tcode=='Q') trash_Q++;
360 >              else if (tcode=='N') trash_N++;
361 >               else if (tcode=='D') trash_D++;
362 >                else if (tcode=='3') trash_A3++;
363 >                 else if (tcode=='5') trash_A5++;
364 >          if (trashReport) trash_report(tcode, seqid, freport);
365 >          }
366 >         else if (!doCollapse) { //write it
367 >          if (tcode>0) {
368 >            rseq=rseq.substr(a5,a3-a5+1);
369 >            if (!rqv.is_empty()) rqv=rqv.substr(a5,a3-a5+1);
370 >            }
371 >         #ifdef GDEBUG
372 >            GMessage("  After trimming:\n");
373 >            GMessage("%s\n",rseq.chars());
374 >         #endif
375 >          writeRead(f_out, seqid, seqinfo, rseq, rqv, outcounter);
376 >          }
377 >       } //for each fastq record
378 >    delete fq2;
379 >    FRCLOSE(f_in);
380 >    FRCLOSE(f_in2);
381 >    if (doCollapse) {
382 >       outcounter=0;
383 >       int maxdup_count=1;
384 >       char* maxdup_seq=NULL;
385 >       dhash.startIterate();
386 >       FqDupRec* qd=NULL;
387 >       char* seq=NULL;
388 >       while ((qd=dhash.NextData(seq))!=NULL) {
389 >         GStr rseq(seq);
390 >         //do the dusting here
391 >         if (doDust) {
392 >            int dustbases=dust(rseq);
393 >            if (dustbases>(rseq.length()>>1)) {
394 >               if (trashReport && qd->firstname!=NULL) {
395 >                 fprintf(freport, "%s_x%d\tD\n",qd->firstname, qd->count);
396                   }
397 <              else    
398 <                 dr->add(rqv);
399 <           } //collapsing duplicates
400 <         else { //not collapsing duplicates
401 <           //do the dust filter now
402 <           if (doDust) {
403 <             int dustbases=dust(rseq);
404 <             if (dustbases>(rseq.length()>>1)) {
405 <                if (trashReport) {
406 <                  fprintf(freport, "%s\tD\t%s\n",rname.chars(),rseq.chars());
407 <                  }
408 <                continue;
409 <                }
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());
397 >               trash_D+=qd->count;
398 >               continue;
399 >               }
400 >            }
401 >         outcounter++;
402 >         if (qd->count>maxdup_count) {
403 >            maxdup_count=qd->count;
404 >            maxdup_seq=seq;
405 >            }
406 >         if (isfasta) {
407 >           if (prefix.is_empty()) {
408 >             fprintf(f_out, ">%s_x%d\n%s\n", qd->firstname, qd->count,
409 >                           rseq.chars());
410               }
411 <           else {  //fastq
412 <            if (convert_phred) convertPhred(rqv);
413 <            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() );
411 >           else { //use custom read name
412 >             fprintf(f_out, ">%s%08d_x%d\n%s\n", prefix.chars(), outcounter,
413 >                        qd->count, rseq.chars());
414               }
415 <           } //not collapsing duplicates
416 <        } //for each fastq record
417 <   } //while each input file
418 < FRCLOSE(f_in);
419 < if (doCollapse) {
420 <    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;
415 >           }
416 >         else { //fastq format
417 >          if (convert_phred) convertPhred(qd->qv, qd->len);
418 >          if (prefix.is_empty()) {
419 >            fprintf(f_out, "@%s_x%d\n%s\n+\n%s\n", qd->firstname, qd->count,
420 >                           rseq.chars(), qd->qv);
421              }
422 +          else { //use custom read name
423 +            fprintf(f_out, "@%s%08d_x%d\n%s\n+\n%s\n", prefix.chars(), outcounter,
424 +                        qd->count, rseq.chars(), qd->qv);
425 +            }
426 +           }
427 +         }//for each element of dhash
428 +       if (maxdup_count>1) {
429 +         GMessage("Maximum read multiplicity: x %d (read: %s)\n",maxdup_count, maxdup_seq);
430           }
431 <      outcounter++;
432 <      if (qd->count>maxdup_count) {
433 <         maxdup_count=qd->count;
434 <         maxdup_seq=seq;
435 <         }
436 <      if (isfasta) {
437 <        if (prefix.is_empty()) {
438 <          fprintf(f_out, ">%s_x%d\n%s\n", qd->firstname, qd->count,
439 <                        rseq.chars());
440 <          }
441 <        else { //use custom read name
442 <          fprintf(f_out, ">%s%08d_x%d\n%s\n", prefix.chars(), outcounter,
443 <                     qd->count, rseq.chars());
431 >       } //collapse entries
432 >    if (verbose) {
433 >       if (paired_reads) {
434 >           GMessage(">Input files : %s , %s\n", infname.chars(), infname2.chars());
435 >           GMessage("Number of input pairs :%9d\n", incounter);
436 >           GMessage("         Output pairs :%9d\n", outcounter);
437 >           }
438 >         else {
439 >           GMessage(">Input file : %s\n", infname.chars());
440 >           GMessage("Number of input reads :%9d\n", incounter);
441 >           GMessage("         Output reads :%9d\n", outcounter);
442 >           }
443 >       GMessage("------------------------------------\n");
444 >       if (num_trimmed5)
445 >          GMessage("           5' trimmed :%9d  (min. trim: %d)\n", num_trimmed5, min_trimmed5);
446 >       if (num_trimmed3)
447 >          GMessage("           3' trimmed :%9d  (min. trim: %d)\n", num_trimmed3, min_trimmed3);
448 >       GMessage("------------------------------------\n");
449 >       if (trash_s>0)
450 >         GMessage("     Trashed by length:%9d\n", trash_s);
451 >       if (trash_N>0)
452 >         GMessage("         Trashed by N%%:%9d\n", trash_N);
453 >       if (trash_Q>0)
454 >         GMessage("Trashed by low quality:%9d\n", trash_Q);
455 >       if (trash_poly>0)
456 >         GMessage("   Trashed by poly-A/T:%9d\n", trash_poly);
457 >       if (trash_A5>0)
458 >         GMessage(" Trashed by 5' adapter:%9d\n", trash_A5);
459 >       if (trash_A3>0)
460 >         GMessage(" Trashed by 3' adapter:%9d\n", trash_A3);
461 >       }
462 >    if (trashReport) {
463 >          FWCLOSE(freport);
464            }
465 <        }
466 <      else { //fastq format
467 <       if (convert_phred) convertPhred(qd->qv, qd->len);
468 <       if (prefix.is_empty()) {
469 <         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);
465 >    FWCLOSE(f_out);
466 >    FWCLOSE(f_out2);
467 >   } //while each input file
468 > delete gxmem_l;
469 > delete gxmem_r;
470   //getc(stdin);
471   }
472  
# Line 670 | Line 552
552  
553  
554   bool qtrim(GStr& qvs, int &l5, int &l3) {
555 < if (qvtrim_min==0 || qvs.is_empty()) return false;
555 > if (qvtrim_qmin==0 || qvs.is_empty()) return false;
556   if (qv_phredtype==0) {
557    //try to guess the Phred type
558    int vmin=256, vmax=0;
# Line 683 | Line 565
565    if (qv_phredtype==0) {
566      GError("Error: couldn't determine Phred type, please use the -p33 or -p64 !\n");
567      }
568 <  } //guessing the Phred type
568 >  if (verbose)
569 >    GMessage("Input reads have Phred-%d quality values.\n", (qv_phredtype==33 ? 33 : 64));
570 >  } //guessing Phred type
571   for (l3=qvs.length()-1;l3>2;l3--) {
572 <  if (qvs[l3]-qv_phredtype>=qvtrim_min && qvs[l3-1]-qv_phredtype>=qvtrim_min) break;
572 >  if (qvs[l3]-qv_phredtype>=qvtrim_qmin && qvs[l3-1]-qv_phredtype>=qvtrim_qmin) break;
573    }
574   //just in case, check also the 5' the end (?)
575   for (l5=0;l5<qvs.length()-3;l5++) {
576 <  if (qvs[l5]-qv_phredtype>=qvtrim_min && qvs[l5+1]-qv_phredtype>=qvtrim_min) break;
576 >  if (qvs[l5]-qv_phredtype>=qvtrim_qmin && qvs[l5+1]-qv_phredtype>=qvtrim_qmin) break;
577 >  }
578 > if (qvtrim_max>0) {
579 >  if (qvs.length()-1-l3>qvtrim_max) l3=qvs.length()-1-qvtrim_max;
580 >  if (l5>qvtrim_max) l5=qvtrim_max;
581    }
582   return (l5>0 || l3<qvs.length()-1);
583   }
# Line 844 | Line 732
732   return ncount;
733   }
734  
847
848 // ------------------ adapter matching - simple k-mer seed & extend, no indels for now
849 //when a k-mer match is found, simply try to extend the alignment using a drop-off scheme
850 //check minimum score and
851 //for 3' adapter trimming:
852 //     require that the right end of the alignment for either the adaptor OR the read must be
853 //     < 3 distance from its right end
854 // for 5' adapter trimming:
855 //     require that the left end of the alignment for either the adaptor OR the read must
856 //     be at coordinate < 3 from start
857
858 bool extendMatch(const char* a, int alen, int ai,
859                 const char* b, int blen, int bi, int mlen, int& l5, int& l3, CSegChain& segs, bool end5=false) {
860 //so the alignment starts at ai in a, bi in b, with a perfect match of length mlen
861 #ifdef DEBUG
862 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           }
912      }
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;
922   }
923  a_r=ai_maxscore;
924  b_r=bi_maxscore;
925  int a_ovh3=alen-a_r-1;
926  int b_ovh3=blen-b_r-1;
927  int mmovh3=(a_ovh3<b_ovh3)? a_ovh3 : b_ovh3;
928  int mmovh5=(a_l<b_l)? a_l : b_l;
929  //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);
930 #ifdef DEBUG
931  if (debug) GMessage("     extended to: %*s\n",a_r+1,dbg.substr(b_l,b_r-b_l+1).chars());
932 #endif
933  if (maxscore>=a_min_score && mmovh3<2 && mmovh5<2) {
934     if (a_l<a_ovh3) {
935        //adapter closer to the left end (typical for 5' adapter)
936        l5=a_r+1;
937        l3=alen-1;
938        }
939      else {
940        //adapter matching at the right end (typical for 3' adapter)
941        l5=0;
942        l3=a_l-1;
943        }
944     return true;
945     }
946 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 */
735   int get3mer_value(const char* s) {
736   return (s[0]<<16)+(s[1]<<8)+s[2];
737   }
# Line 983 | Line 755
755   return -1;
756   }
757  
758 < int fast4match(int32 qv, const char* str, int slen, int start_index=0) {
759 < if (start_index>=slen || start_index<0) return -1;
760 < for (int i=start_index;i<slen-4;i++) {
761 <   int32* rv=(int32*)(str+i);
762 <   if (*rv==qv) return i;
763 <   }
764 < return -1;
765 < }
758 > struct SLocScore {
759 >  int pos;
760 >  int score;
761 >  SLocScore(int p=0,int s=0) {
762 >    pos=p;
763 >    score=s;
764 >    }
765 >  void set(int p, int s) {
766 >    pos=p;
767 >    score=s;
768 >    }
769 >  void add(int p, int add) {
770 >    pos=p;
771 >    score+=add;
772 >    }
773 > };
774  
775 < int fast4rmatch(int32 qv, const char* str, int slen, int end_index=-1) {
776 < if (end_index>=slen) return -1;
777 < if (end_index<0) end_index=slen-1;
778 < for (int i=end_index-3;i>=0;i--) {
779 <   int32* rv=(int32*)(str+i);
780 <   if (*rv==qv) return i;
775 > bool trim_poly3(GStr &seq, int &l5, int &l3, const char* poly_seed) {
776 > if (!doPolyTrim) return false;
777 > int rlen=seq.length();
778 > l5=0;
779 > l3=rlen-1;
780 > int32 seedVal=*(int32*)poly_seed;
781 > char polyChar=poly_seed[0];
782 > //assumes N trimming was already done
783 > //so a poly match should be very close to the end of the read
784 > // -- find the initial match (seed)
785 > int lmin=GMAX((rlen-16), 0);
786 > int li;
787 > for (li=rlen-4;li>lmin;li--) {
788 >   if (seedVal==*(int*)&(seq[li])) {
789 >      break;
790 >      }
791     }
792 < return -1;
793 < }
794 <
795 < #ifdef DEBUG
796 < void dbgPrintChain(CSegChain& chain, const char* aseq) {
797 <  GStr s(aseq);
798 <  for (int i=0;i<chain.Count();i++) {
799 <   CSegPair& seg=*chain[i];
800 <   GMessage("  dbg chain seg%d: %*s [%d-%d:%d-%d]\n",i,seg.a.start-1+seg.len(),
801 <            s.substr(seg.b.start-1, seg.len()).chars(), seg.b.start,seg.b.end,seg.a.start,seg.a.end);
792 > if (li<=lmin) return false;
793 > //seed found, try to extend it both ways
794 > //extend right
795 > int ri=li+3;
796 > SLocScore loc(ri, poly_m_score<<2);
797 > SLocScore maxloc(loc);
798 > //extend right
799 > while (ri<rlen-2) {
800 >   ri++;
801 >   if (seq[ri]==polyChar) {
802 >                loc.add(ri,poly_m_score);
803 >                }
804 >   else if (seq[ri]=='N') {
805 >                loc.add(ri,0);
806 >                }
807 >   else { //mismatch
808 >        loc.add(ri,poly_mis_score);
809 >        if (maxloc.score-loc.score>poly_dropoff_score) break;
810 >        }
811 >   if (maxloc.score<=loc.score) {
812 >      maxloc=loc;
813 >      }
814     }
815 + ri=maxloc.pos;
816 + if (ri<rlen-6) return false; //no trimming wanted, too far from 3' end
817 + //ri = right boundary for the poly match
818 + //extend left
819 + loc.set(li, maxloc.score);
820 + maxloc.pos=li;
821 + while (li>0) {
822 +    li--;
823 +    if (seq[li]==polyChar) {
824 +                 loc.add(li,poly_m_score);
825 +                 }
826 +    else if (seq[li]=='N') {
827 +                 loc.add(li,0);
828 +                 }
829 +    else { //mismatch
830 +         loc.add(li,poly_mis_score);
831 +         if (maxloc.score-loc.score>poly_dropoff_score) break;
832 +         }
833 +    if (maxloc.score<=loc.score) {
834 +       maxloc=loc;
835 +       }
836 +    }
837 + li=maxloc.pos;
838 + if ((maxloc.score==poly_minScore && ri==rlen-1) ||
839 +    (maxloc.score>poly_minScore && ri>=rlen-3) ||
840 +    (maxloc.score>(poly_minScore*3) && ri>=rlen-8)) {
841 +  //trimming this li-ri match at 3' end
842 +    l3=li-1;
843 +    if (l3<0) l3=0;
844 +    return true;
845 +    }
846 + return false;
847   }
1014 #endif
848  
849 < bool trim_adapter3(GStr& seq, int&l5, int &l3) {
849 > bool trim_poly5(GStr &seq, int &l5, int &l3, const char* poly_seed) {
850 > if (!doPolyTrim) return false;
851   int rlen=seq.length();
852   l5=0;
853   l3=rlen-1;
854 < //first try a full match, we might get lucky
855 < int fi=-1;
856 < if ((fi=seq.index(adapter3))>=0) {
857 <   if (fi<rlen-fi-a3len) {//match is closer to the right end
858 <      l5=fi+a3len;
859 <      l3=rlen-1;
854 > int32 seedVal=*(int32*)poly_seed;
855 > char polyChar=poly_seed[0];
856 > //assumes N trimming was already done
857 > //so a poly match should be very close to the end of the read
858 > // -- find the initial match (seed)
859 > int lmax=GMIN(12, rlen-4);//how far from 5' end to look for 4-mer seeds
860 > int li;
861 > for (li=0;li<=lmax;li++) {
862 >   if (seedVal==*(int*)&(seq[li])) {
863 >      break;
864        }
1027    else {
1028      l5=0;
1029      l3=fi-1;
1030      }
1031   return true;
865     }
866 < #ifdef DEBUG
867 < if (debug) GMessage(">TRIM3 >>   Read: %s\n",seq.chars());
868 < #endif
869 <
870 < //also, for fast detection of other adapter-only reads that start past
871 < // the beginning of the adapter sequence, try to see if the first a3len-4
872 < // bases of the read are a substring of the adapter
873 < if (rlen>a3len-3) {
874 <   GStr rstart=seq.substr(1,a3len-4);
875 <   if ((fi=adapter3.index(rstart))>=0) {
876 <     l3=rlen-1;
877 <     l5=a3len-4;
878 <     while (fi+l5<a3len && l5<l3 && adapter3[fi+l5]==seq[l5]) l5++;
879 <     return true;
880 <     }
881 <  }
882 < CSegChain a3segs; //no chains here, just an ordered collection of segment pairs
883 <  //check the easy cases - 11 bases exact match at the end
884 < int fdlen=11;
885 <  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;
866 > if (li>lmax) return false;
867 > //seed found, try to extend it both ways
868 > //extend left
869 > int ri=li+3; //save rightmost base of the seed
870 > SLocScore loc(li, poly_m_score<<2);
871 > SLocScore maxloc(loc);
872 > while (li>0) {
873 >    li--;
874 >    if (seq[li]==polyChar) {
875 >                 loc.add(li,poly_m_score);
876 >                 }
877 >    else if (seq[li]=='N') {
878 >                 loc.add(li,0);
879 >                 }
880 >    else { //mismatch
881 >         loc.add(li,poly_mis_score);
882 >         if (maxloc.score-loc.score>poly_dropoff_score) break;
883 >         }
884 >    if (maxloc.score<=loc.score) {
885 >       maxloc=loc;
886         }
887 <     } //tried to match 11 bases first
888 <    
889 < //no easy cases, so let's do the wmer hashing for the first 12 bases of the adaptor
890 < //-- only extend if the match is in the 3' (ending) region of the read
891 < int wordSize=3;
892 < int hlen=12;
893 < if (hlen>a3len-wordSize) hlen=a3len-wordSize;
894 < int imin=rlen>>1; //last half of the read, left boundary for the wmer match
895 < if (imin<a3len) { imin=GMIN(a3len, rlen-wordSize); }
896 < imin=rlen-imin;
897 < for (int iw=0;iw<hlen;iw++) {
898 <   //int32* qv=(int32*)(adapter3.chars()+iw);
899 <   int qv=get3mer_value(adapter3.chars()+iw);
900 <   fi=-1;
901 <   //while ((fi=fast4rmatch(*qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
902 <   while ((fi=w3_rmatch(qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
903 <     //GMessage(" ... fi=%d after w3_rmatch() (imin=%d)\n", fi, imin);
904 <
905 < #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());
887 >    }
888 > li=maxloc.pos;
889 > if (li>5) return false; //no trimming wanted, too far from 5' end
890 > //li = right boundary for the poly match
891 >
892 > //extend right
893 > loc.set(ri, maxloc.score);
894 > maxloc.pos=ri;
895 > while (ri<rlen-2) {
896 >   ri++;
897 >   if (seq[ri]==polyChar) {
898 >                loc.add(ri,poly_m_score);
899 >                }
900 >   else if (seq[ri]=='N') {
901 >                loc.add(ri,0);
902 >                }
903 >   else { //mismatch
904 >        loc.add(ri,poly_mis_score);
905 >        if (maxloc.score-loc.score>poly_dropoff_score) break;
906          }
907 < #endif
908 <     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
907 >   if (maxloc.score<=loc.score) {
908 >      maxloc=loc;
909        }
910 <   } //collect segment alignments into chains
911 < */  
912 < return false; //no adapter parts found
910 >   }
911 > ri=maxloc.pos;
912 > if ((maxloc.score==poly_minScore && li==0) ||
913 >     (maxloc.score>poly_minScore && li<2)
914 >     || (maxloc.score>(poly_minScore*3) && li<8)) {
915 >    //adjust l5 to reflect this trimming of 5' end
916 >    l5=ri+1;
917 >    if (l5>rlen-1) l5=rlen-1;
918 >    return true;
919 >    }
920 > return false;
921 > }
922 >
923 > bool trim_adapter3(GStr& seq, int&l5, int &l3) {
924 > if (adapters3.Count()==0) return false;
925 > int rlen=seq.length();
926 > l5=0;
927 > l3=rlen-1;
928 > bool trimmed=false;
929 > GStr wseq(seq.chars());
930 > int wlen=rlen;
931 > for (int ai=0;ai<adapters3.Count();ai++) {
932 >  if (adapters3[ai].is_empty()) continue;
933 >  int alen=adapters3[ai].length();
934 >  GStr& aseq=adapters3[ai];
935 >  GXAlnInfo* r_bestaln=match_RightEnd(aseq.chars(), alen, wseq.chars(), wlen, gxmem_r, 74);
936 >  if (r_bestaln) {
937 >     trimmed=true;
938 >     //keep unmatched region on the left, if any
939 >     l3-=(wlen-r_bestaln->sl+1);
940 >     delete r_bestaln;
941 >     if (l3<0) l3=0;
942 >     if (l3-l5+1<min_read_len) return true;
943 >     wseq=seq.substr(l5,l3-l5+1);
944 >     wlen=wseq.length();
945 >     }
946 >  }//for each 5' adapter
947 >  return trimmed;
948   }
949  
950   bool trim_adapter5(GStr& seq, int&l5, int &l3) {
951 < //if (debug) GMessage("trim_adapter5 on: %s\n", seq.chars());
951 > if (adapters5.Count()==0) return false;
952   int rlen=seq.length();
953   l5=0;
954   l3=rlen-1;
955 < //try to see if adapter is fully included in the read
956 < int fi=-1;
957 < if ((fi=seq.index(adapter5))>=0) {
958 <   if (fi<rlen-fi-a5len) {//match is closer to the right end
959 <      l5=fi+a5len;
960 <      l3=rlen-1;
961 <      }
962 <    else {
963 <      l5=0;
964 <      l3=fi-1;
955 > bool trimmed=false;
956 > GStr wseq(seq.chars());
957 > int wlen=rlen;
958 > for (int ai=0;ai<adapters5.Count();ai++) {
959 >  if (adapters5[ai].is_empty()) continue;
960 >  int alen=adapters5[ai].length();
961 >  GStr& aseq=adapters5[ai];
962 >  GXAlnInfo* l_bestaln=match_LeftEnd(aseq.chars(), alen, wseq.chars(), wlen, gxmem_l, 84);
963 >  if (l_bestaln) {
964 >     trimmed=true;
965 >     l5+=l_bestaln->sr;
966 >     delete l_bestaln;
967 >     if (l5>=rlen) l5=rlen-1;
968 >     if (l3-l5+1<min_read_len) return true;
969 >     wseq=seq.substr(l5,l3-l5+1);
970 >     wlen=wseq.length();
971 >     }
972 >  }//for each 5' adapter
973 >  return trimmed;
974 > }
975 >
976 > //convert qvs to/from phred64 from/to phread33
977 > void convertPhred(GStr& q) {
978 > for (int i=0;i<q.length();i++) q[i]+=qv_cvtadd;
979 > }
980 >
981 > void convertPhred(char* q, int len) {
982 > for (int i=0;i<len;i++) q[i]+=qv_cvtadd;
983 > }
984 >
985 > bool getFastxRec(GLineReader& fq, GStr& rseq, GStr& rqv,
986 >          GStr& rname, GStr& rinfo, GStr& infname) {
987 > rseq="";
988 > rqv="";
989 > rname="";
990 > rinfo="";
991 > if (fq.eof()) return false;
992 > char* l=fq.getLine();
993 > while (l!=NULL && (l[0]==0 || isspace(l[0]))) l=fq.getLine(); //ignore empty lines
994 > if (l==NULL) return false;
995 > /* if (rawFormat) {
996 >      //TODO: implement raw qseq parsing here
997 >      //if (raw type=N) then continue; //skip invalid/bad records
998 >      } //raw qseq format
999 > else { // FASTQ or FASTA */
1000 > isfasta=(l[0]=='>');
1001 > if (!isfasta && l[0]!='@') GError("Error: fasta/fastq record marker not found(%s)\n%s\n",
1002 >      infname.chars(), l);
1003 > GStr s(l);
1004 > rname=&(l[1]);
1005 > for (int i=0;i<rname.length();i++)
1006 >    if (rname[i]<=' ') {
1007 >       if (i<rname.length()-2) rinfo=rname.substr(i+1);
1008 >       rname.cut(i);
1009 >       break;
1010 >       }
1011 >  //now get the sequence
1012 > if ((l=fq.getLine())==NULL)
1013 >      GError("Error: unexpected EOF after header for read %s (%s)\n",
1014 >                   rname.chars(), infname.chars());
1015 > rseq=l; //this must be the DNA line
1016 > while ((l=fq.getLine())!=NULL) {
1017 >      //seq can span multiple lines
1018 >      if (l[0]=='>' || l[0]=='+') {
1019 >           fq.pushBack();
1020 >           break; //
1021 >           }
1022 >      rseq+=l;
1023 >      } //check for multi-line seq
1024 > if (!isfasta) { //reading fastq quality values, which can also be multi-line
1025 >    if ((l=fq.getLine())==NULL)
1026 >        GError("Error: unexpected EOF after sequence for %s\n", rname.chars());
1027 >    if (l[0]!='+') GError("Error: fastq qv header marker not detected!\n");
1028 >    if ((l=fq.getLine())==NULL)
1029 >        GError("Error: unexpected EOF after qv header for %s\n", rname.chars());
1030 >    rqv=l;
1031 >    //if (rqv.length()!=rseq.length())
1032 >    //  GError("Error: qv len != seq len for %s\n", rname.chars());
1033 >    while (rqv.length()<rseq.length() && ((l=fq.getLine())!=NULL)) {
1034 >      rqv+=l; //append to qv string
1035        }
1036 <   return true;
1037 <   }
1038 < #ifdef DEBUG
1039 < if (debug) GMessage(">TRIM5 >>   Read: %s\n",seq.chars());
1036 >    }// fastq
1037 > // } //<-- FASTA or FASTQ
1038 > rseq.upper();
1039 > return true;
1040 > }
1041 >
1042 > #ifdef GDEBUG
1043 > void showTrim(GStr& s, int l5, int l3) {
1044 >  if (l5>0) {
1045 >    color_bg(c_red);
1046 >    }
1047 >  for (int i=0;i<s.length()-1;i++) {
1048 >    if (i && i==l5) color_resetbg();
1049 >    fprintf(stderr, "%c", s[i]);
1050 >    if (i==l3) color_bg(c_red);
1051 >   }
1052 >  fprintf(stderr, "%c", s[s.length()-1]);
1053 >  color_reset();
1054 >  fprintf(stderr, "\n");
1055 > }
1056   #endif
1057  
1058 < CSegChain a5segs(true); //list of segment pairs to analyze later if no extendMatch succeeded
1058 > char process_read(GStr& rname, GStr& rseq, GStr& rqv, int &l5, int &l3) {
1059 > //returns 0 if the read was untouched, 1 if it was just trimmed
1060 > // and a trash code if it was trashed
1061 > l5=0;
1062 > l3=rseq.length()-1;
1063 > #ifdef GDEBUG
1064 >   //rseq.reverse();
1065 >   GMessage(">%s\n", rname.chars());
1066 >   GMessage("%s\n",rseq.chars());
1067 > #endif
1068 > if (l3-l5+1<min_read_len) {
1069 >   return 's';
1070 >   }
1071 > GStr wseq(rseq.chars());
1072 > GStr wqv(rqv.chars());
1073 > int w5=l5;
1074 > int w3=l3;
1075 > //first do the q-based trimming
1076 > if (qvtrim_qmin!=0 && !wqv.is_empty() && qtrim(wqv, w5, w3)) { // qv-threshold trimming
1077 >   if (w3-w5+1<min_read_len) {
1078 >     return 'Q'; //invalid read
1079 >     }
1080 >    //-- keep only the w5..w3 range
1081 >   l5=w5;
1082 >   l3=w3;
1083 >   wseq=wseq.substr(w5, w3-w5+1);
1084 >   if (!wqv.is_empty())
1085 >      wqv=wqv.substr(w5, w3-w5+1);
1086 >   } //qv trimming
1087 > // N-trimming on the remaining read seq
1088 > if (ntrim(wseq, w5, w3)) {
1089 >   //GMessage("before: %s\n",wseq.chars());
1090 >   //GMessage("after : %s (%d)\n",wseq.substr(w5,w3-w5+1).chars(),w3-w5+1);
1091 >   l5+=w5;
1092 >   l3-=(wseq.length()-1-w3);
1093 >   if (w3-w5+1<min_read_len) {
1094 >     return 'N'; //to be trashed
1095 >     }
1096 >    //-- keep only the w5..w3 range
1097 >   wseq=wseq.substr(w5, w3-w5+1);
1098 >   if (!wqv.is_empty())
1099 >      wqv=wqv.substr(w5, w3-w5+1);
1100 >   w5=0;
1101 >   w3=wseq.length()-1;
1102 >   }
1103 > char trim_code;
1104 > do {
1105 >  trim_code=0;
1106 >  if (trim_poly5(wseq, w5, w3, polyA_seed)) {
1107 >      trim_code='A';
1108 >      }
1109 >  else if (trim_poly5(wseq, w5, w3, polyT_seed)) {
1110 >      trim_code='T';
1111 >      }
1112 >  else if (trim_adapter5(wseq, w5, w3)) {
1113 >      trim_code='5';
1114 >      }
1115 >  if (trim_code) {
1116 >     #ifdef GDEBUG
1117 >      GMessage("#### TRIM by '%c' code ( w5-w3 = %d-%d ):\n",trim_code, w5,w3);
1118 >      showTrim(wseq, w5, w3);
1119 >     #endif
1120 >     int trimlen=wseq.length()-(w3-w5+1);
1121 >     num_trimmed5++;
1122 >     if (trimlen<min_trimmed5)
1123 >         min_trimmed5=trimlen;
1124 >     l5+=w5;
1125 >     l3-=(wseq.length()-1-w3);
1126 >     if (w3-w5+1<min_read_len) {
1127 >         return trim_code;
1128 >         }
1129 >      //-- keep only the w5..w3 range
1130 >      wseq=wseq.substr(w5, w3-w5+1);
1131 >      if (!wqv.is_empty())
1132 >         wqv=wqv.substr(w5, w3-w5+1);
1133 >      }// trimmed at 5' end
1134 > } while (trim_code);
1135 >
1136 > do {
1137 >  trim_code=0;
1138 >  if (trim_poly3(wseq, w5, w3, polyA_seed)) {
1139 >      trim_code='A';
1140 >      }
1141 >  else if (trim_poly3(wseq, w5, w3, polyT_seed)) {
1142 >      trim_code='T';
1143 >      }
1144 >  else if (trim_adapter3(wseq, w5, w3)) {
1145 >      trim_code='3';
1146 >      }
1147 >  if (trim_code) {
1148 >     #ifdef GDEBUG
1149 >     GMessage("#### TRIM by '%c' code ( w5-w3 = %d-%d ):\n",trim_code, w5,w3);
1150 >     showTrim(wseq, w5, w3);
1151 >     #endif
1152 >     int trimlen=wseq.length()-(w3-w5+1);
1153 >     num_trimmed3++;
1154 >     if (trimlen<min_trimmed3)
1155 >         min_trimmed3=trimlen;
1156 >     l5+=w5;
1157 >     l3-=(wseq.length()-1-w3);
1158 >     if (w3-w5+1<min_read_len) {
1159 >         return trim_code;
1160 >         }
1161 >      //-- keep only the w5..w3 range
1162 >      wseq=wseq.substr(w5, w3-w5+1);
1163 >      if (!wqv.is_empty())
1164 >         wqv=wqv.substr(w5, w3-w5+1);
1165 >      }//trimming at 3' end
1166 > } while (trim_code);
1167 >
1168 >
1169 > if (doCollapse) {
1170 >   //keep read for later
1171 >   FqDupRec* dr=dhash.Find(wseq.chars());
1172 >   if (dr==NULL) { //new entry
1173 >          //if (prefix.is_empty())
1174 >             dhash.Add(wseq.chars(),
1175 >                  new FqDupRec(&wqv, rname.chars()));
1176 >          //else dhash.Add(wseq.chars(), new FqDupRec(wqv.chars(),wqv.length()));
1177 >         }
1178 >      else
1179 >         dr->add(wqv);
1180 >   } //collapsing duplicates
1181 > else { //not collapsing duplicates
1182 >   //apply the dust filter now
1183 >   if (doDust) {
1184 >     int dustbases=dust(wseq);
1185 >     if (dustbases>(wseq.length()>>1)) {
1186 >        return 'D';
1187 >        }
1188 >     }
1189 >   } //not collapsing duplicates
1190 > return (l5>0 || l3<rseq.length()-1) ? 1 : 0;
1191 > }
1192 >
1193 > void printHeader(FILE* f_out, char recmarker, GStr& rname, GStr& rinfo) {
1194 > //GMessage("printing Header..%c%s\n",recmarker, rname.chars());
1195 > if (rinfo.is_empty()) fprintf(f_out, "%c%s\n",recmarker,rname.chars());
1196 >  else fprintf(f_out, "%c%s %s\n",recmarker, rname.chars(), rinfo.chars());
1197 > }
1198  
1199 < //try the easy way out first - look for an exact match of 11 bases
1200 < int fdlen=11;
1201 <  if (a5len<16) {
1202 <   fdlen=a5len>>1;
1203 <   }
1204 < if (fdlen>4) {
1205 <     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;
1199 > void writeRead(FILE* f_out, GStr& rname, GStr& rinfo, GStr& rseq, GStr& rqv, int& outcounter) {
1200 >   outcounter++;
1201 >   bool asFasta=(rqv.is_empty() || fastaOutput);
1202 >   if (asFasta) {
1203 >    if (prefix.is_empty()) {
1204 >       printHeader(f_out, '>',rname,rinfo);
1205 >       fprintf(f_out, "%s\n", rseq.chars()); //plain one-line fasta for now
1206         }
1207 <     //another easy case: last 11 characters of the adaptor found as a substring of the read
1208 <     GStr bstr=adapter5.substr(-fdlen);
1209 <     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;
1207 >      else {
1208 >       fprintf(f_out, ">%s%08d\n%s\n", prefix.chars(), outcounter,
1209 >                          rseq.chars());
1210         }
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;
1211       }
1212 <   } //for each wmer in the last hlen bases of the adaptor
1213 < /*
1214 <
1215 < //couldn't find a good trimming extension, hash 12 more bases of the adapter to collect more segment pairs there
1216 < //but only do this if we already have segment pairs collected in the last 12 bases of the adapter
1217 < if (a5segs.bend<(uint)(a5len-3) || a5segs.bstart>(uint)(a5len-hlen+4)) return false;
1218 < int hlen2=a5len-wordSize;
1219 < //if (hlen2>a5len-wordSize) hlen2=a5len-wordSize;
1220 < #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
1212 >   else {  //fastq
1213 >    if (convert_phred) convertPhred(rqv);
1214 >    if (prefix.is_empty()) {
1215 >       printHeader(f_out, '@', rname, rinfo);
1216 >       fprintf(f_out, "%s\n+\n%s\n", rseq.chars(), rqv.chars());
1217 >       }
1218 >      else
1219 >       fprintf(f_out, "@%s_%08d\n%s\n+\n%s\n", prefix.chars(), outcounter,
1220 >                          rseq.chars(),rqv.chars() );
1221       }
1222 < if (a5segs.bend<(uint)(a5len-3) || a5segs.bstart>(uint)(a5len-hlen+4)) return false;
1223 < // lastly, analyze collected a5segs for a possible gapped alignment:
1224 < GList<CSegChain> segchains(false,true,false);
1225 < #ifdef DEBUG
1226 < if (debug && a5segs.Count()>0) {
1227 <   GMessage(">>>>>>>>>   Read: %s\n",seq.chars());
1222 > }
1223 >
1224 > void trash_report(char trashcode, GStr& rname, FILE* freport) {
1225 > if (freport==NULL || trashcode<=' ') return;
1226 > if (trashcode=='3' || trashcode=='5') {
1227 >   fprintf(freport, "%s\ta%c\n",rname.chars(),trashcode);
1228     }
1229 < #endif
1230 < for (int i=0;i<a5segs.Count();i++) {
1231 <   if (a5segs[i]->chain==NULL) {
1232 <       if (a5segs[i]->b.end<(int)(a5len-4)) continue; //don't start a hopeless chain
1233 <       CSegChain* newchain=new CSegChain(true);
1234 <       newchain->setFreeItem(false);
1235 <       newchain->addSegPair(a5segs[i]);
1236 <       a5segs[i]->chain=newchain;
1237 <       segchains.Add(newchain); //just to free them when done
1238 <       }
1239 <   for (int j=i+1;j<a5segs.Count();j++) {
1240 <      CSegChain* chain=a5segs[i]->chain;
1241 <      if (chain->extendChain(a5segs[j])) {
1242 <         a5segs[j]->chain=chain;
1243 < #ifdef DEBUG
1244 <         if (debug) dbgPrintChain(*chain, adapter5.chars());
1245 < #endif      
1246 <      //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
1229 > else {
1230 >   fprintf(freport, "%s\t%c\n",rname.chars(),trashcode);
1231 >   }
1232 > //tcounter++;
1233 > }
1234 >
1235 > GStr getFext(GStr& s, int* xpos=NULL) {
1236 > //s must be a filename without a path
1237 > GStr r("");
1238 > if (xpos!=NULL) *xpos=0;
1239 > if (s.is_empty() || s=="-") return r;
1240 > int p=s.rindex('.');
1241 > int d=s.rindex('/');
1242 > if (p<=0 || p>s.length()-2 || p<s.length()-7 || p<d) return r;
1243 > r=s.substr(p+1);
1244 > if (xpos!=NULL) *xpos=p+1;
1245 > r.lower();
1246 > return r;
1247   }
1248  
1249 < //convert qvs to/from phred64 from/to phread33
1250 < void convertPhred(GStr& q) {
1251 < for (int i=0;i<q.length();i++) q[i]+=qv_cvtadd;
1249 > void baseFileName(GStr& fname) {
1250 > //remove all known extensions, like .txt,fq,fastq,fasta,fa)(.gz .gzip .bz2 .bzip2) .
1251 > int xpos=0;
1252 > GStr fext=getFext(fname, &xpos);
1253 > if (xpos<=1) return;
1254 > bool extdel=false;
1255 > GStr f2;
1256 > if (fext=="z" || fext=="zip") {
1257 >   extdel=true;
1258 >   }
1259 >  else if (fext.length()>=2) {
1260 >   f2=fext.substr(0,2);
1261 >   extdel=(f2=="gz" || f2=="bz");
1262 >   }
1263 > if (extdel) {
1264 >   fname.cut(xpos-1);
1265 >   fext=getFext(fname, &xpos);
1266 >   if (xpos<=1) return;
1267 >   }
1268 > extdel=false;
1269 > if (fext=="f" || fext=="fq" || fext=="txt" || fext=="seq" || fext=="sequence") {
1270 >   extdel=true;
1271 >   }
1272 >  else if (fext.length()>=2) {
1273 >   extdel=(fext.substr(0,2)=="fa");
1274 >   }
1275 > if (extdel) fname.cut(xpos-1);
1276 > GStr fncp(fname);
1277 > fncp.lower();
1278 > fncp.chomp("seq");
1279 > fncp.chomp("sequence");
1280 > fncp.trimR("_.");
1281 > if (fncp.length()<fname.length()) fname.cut(fncp.length());
1282   }
1283  
1284 < void convertPhred(char* q, int len) {
1285 < for (int i=0;i<len;i++) q[i]+=qv_cvtadd;
1284 > FILE* prepOutFile(GStr& infname, GStr& pocmd) {
1285 >  FILE* f_out=NULL;
1286 >  GStr fname(getFileName(infname.chars()));
1287 >  //eliminate known extensions
1288 >  baseFileName(fname);
1289 >  if (outsuffix.is_empty() || outsuffix=="-") { return stdout; }
1290 >    else if (pocmd.is_empty()) {
1291 >               GStr oname(fname);
1292 >               oname.append('.');
1293 >               oname.append(outsuffix);
1294 >               f_out=fopen(oname.chars(),"w");
1295 >               if (f_out==NULL) GError("Error: cannot create '%s'\n",oname.chars());
1296 >               }
1297 >            else {
1298 >              GStr oname(">");
1299 >              oname.append(fname);
1300 >              oname.append('.');
1301 >              oname.append(outsuffix);
1302 >              pocmd.append(oname);
1303 >              f_out=popen(pocmd.chars(), "w");
1304 >              if (f_out==NULL) GError("Error: cannot popen '%s'\n",pocmd.chars());
1305 >              }
1306 > return f_out;
1307 > }
1308 >
1309 > void guess_unzip(GStr& fname, GStr& picmd) {
1310 > GStr fext=getFext(fname);
1311 > if (fext=="gz" || fext=="gzip" || fext=="z") {
1312 >    picmd="gzip -cd ";
1313 >    }
1314 >   else if (fext=="bz2" || fext=="bzip2" || fext=="bz" || fext=="bzip") {
1315 >    picmd="bzip2 -cd ";
1316 >    }
1317   }
1318  
1319 +
1320 + int loadAdapters(const char* fname) {
1321 +  GLineReader lr(fname);
1322 +  char* l;
1323 +  while ((l=lr.nextLine())!=NULL) {
1324 +   if (lr.length()<=3 || l[0]=='#') continue;
1325 +   if ( l[0]==' ' || l[0]=='\t' || l[0]==',' ||
1326 +        l[0]==';'|| l[0]==':' ) {
1327 +      int i=1;
1328 +      while (l[i]!=0 && isspace(l[i])) {
1329 +        i++;
1330 +        }
1331 +      if (l[i]!=0) {
1332 +        GStr s(&(l[i]));
1333 +      #ifdef GDEBUG
1334 +          //s.reverse();
1335 +      #endif
1336 +        adapters3.Add(s);
1337 +        continue;
1338 +        }
1339 +      }
1340 +    else {
1341 +      GStr s(l);
1342 +      s.startTokenize("\t ;,:");
1343 +      GStr a5,a3;
1344 +      if (s.nextToken(a5))
1345 +         s.nextToken(a3);
1346 +      a5.upper();
1347 +      a3.upper();
1348 +     #ifdef GDEBUG
1349 +     //   a5.reverse();
1350 +     //   a3.reverse();
1351 +     #endif
1352 +      adapters5.Add(a5);
1353 +      adapters3.Add(a3);
1354 +      }
1355 +   }
1356 +   return adapters5.Count()+adapters3.Count();
1357 + }
1358 +
1359 + void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
1360 +                       GStr& s, GStr& infname, GStr& infname2) {
1361 + // uses outsuffix to generate output file names and open file handles as needed
1362 + infname="";
1363 + infname2="";
1364 + f_in=NULL;
1365 + f_in2=NULL;
1366 + f_out=NULL;
1367 + f_out2=NULL;
1368 + //analyze outsuffix intent
1369 + GStr pocmd;
1370 + if (outsuffix=="-") {
1371 +    f_out=stdout;
1372 +    }
1373 +   else {
1374 +    GStr ox=getFext(outsuffix);
1375 +    if (ox.length()>2) ox=ox.substr(0,2);
1376 +    if (ox=="gz") pocmd="gzip -9 -c ";
1377 +        else if (ox=="bz") pocmd="bzip2 -9 -c ";
1378 +    }
1379 + if (s=="-") {
1380 +    f_in=stdin;
1381 +    infname="stdin";
1382 +    f_out=prepOutFile(infname, pocmd);
1383 +    return;
1384 +    } // streaming from stdin
1385 + s.startTokenize(",:");
1386 + s.nextToken(infname);
1387 + bool paired=s.nextToken(infname2);
1388 + if (fileExists(infname.chars())==0)
1389 +    GError("Error: cannot find file %s!\n",infname.chars());
1390 + GStr fname(getFileName(infname.chars()));
1391 + GStr picmd;
1392 + guess_unzip(fname, picmd);
1393 + if (picmd.is_empty()) {
1394 +   f_in=fopen(infname.chars(), "r");
1395 +   if (f_in==NULL) GError("Error opening file '%s'!\n",infname.chars());
1396 +   }
1397 +  else {
1398 +   picmd.append(infname);
1399 +   f_in=popen(picmd.chars(), "r");
1400 +   if (f_in==NULL) GError("Error at popen %s!\n", picmd.chars());
1401 +   }
1402 + if (f_out==stdout) {
1403 +   if (paired) GError("Error: output suffix required for paired reads\n");
1404 +   return;
1405 +   }
1406 + f_out=prepOutFile(infname, pocmd);
1407 + if (!paired) return;
1408 + if (doCollapse) GError("Error: sorry, -C option cannot be used with paired reads!\n");
1409 + // ---- paired reads:-------------
1410 + if (fileExists(infname2.chars())==0)
1411 +     GError("Error: cannot find file %s!\n",infname2.chars());
1412 + picmd="";
1413 + GStr fname2(getFileName(infname2.chars()));
1414 + guess_unzip(fname2, picmd);
1415 + if (picmd.is_empty()) {
1416 +   f_in2=fopen(infname2.chars(), "r");
1417 +   if (f_in2==NULL) GError("Error opening file '%s'!\n",infname2.chars());
1418 +   }
1419 +  else {
1420 +   picmd.append(infname2);
1421 +   f_in2=popen(picmd.chars(), "r");
1422 +   if (f_in2==NULL) GError("Error at popen %s!\n", picmd.chars());
1423 +   }
1424 + f_out2=prepOutFile(infname2, pocmd);
1425 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines