ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/fqtrim/fqtrim.cpp
(Generate patch)
# Line 3 | Line 3
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 <5adapter> -3 <3adapter>|-f <adapters_file>}] [-a <min_matchlen>]\\\n\
# Line 30 | Line 31
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 < -a  minimum length of exact match to adaptor sequence at the proper end (6)\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\
# Line 66 | Line 68
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;
# Line 75 | Line 78
78   bool isfasta=false;
79   bool convert_phred=false;
80   GStr outsuffix; // -o
78 //GStr adapter3;
79 //GStr adapter5;
81   GStr prefix;
82   GStr zcmd;
83   int num_trimmed5=0;
# Line 91 | Line 92
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 match_score=2; //match score
98 < const int mismatch_score=-3; //mismatch
99 <
100 < const int a_m_score=2; //match score
101 < const int a_mis_score=-3; //mismatch
102 < const int a_dropoff_score=7;
103 < const int poly_dropoff_score=7;
104 < int a_min_score=12; //an exact match of 6 bases at the proper ends WILL be trimmed
105 < const int a_min_chain_score=15; //for gapped alignments
106 <
107 < class CSegChain;
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 < class CSegPair {
101 <  public:
102 <   GSeg a;
103 <   GSeg b; //the adapter segment
113 <   int score;
114 <   int flags;
115 <   CSegChain* chain;
116 <   CSegPair(int astart=0, int aend=0, int bstart=0, int bend=0, int mscore=0):a(astart,aend),b(bstart, bend) {
117 <      score=mscore;
118 <      if (score==0) score=a.len()*a_m_score;
119 <      flags=0;
120 <      chain=NULL;
121 <      }
122 <   int len() { return  a.len(); }
123 <   bool operator==(CSegPair& d){
124 <      //return (a.start==d.a.start && a.end==d.a.end && b.start==d.b.start && b.end==d.b.end);
125 <      //make equal even segments that are included into one another:
126 <      return (d.a.start>=a.start && d.a.end<=a.end && d.b.start>=b.start && d.b.end<=b.end);
127 <      }
128 <   bool operator>(CSegPair& d){ //ordering based on b (adaptor) start coord and score
129 <     if (b.start==d.b.start) {
130 <        if (score==d.score) {
131 <           //just try to be consistent:
132 <           if (b.end==d.b.end) {
133 <             return (a.start==d.a.start)?(a.end<d.a.end):(a.start<d.a.start);
134 <             }
135 <           return (b.end>d.b.end);
136 <           }
137 <         else return (score<d.score);
138 <        }
139 <     return (b.start>d.b.start);
140 <     }
141 <   bool operator<(CSegPair& d){ //ordering based on b (adaptor) coord
142 <     /*if (b.start==d.b.start && b.end==d.b.end) {
143 <          return (a.start==d.a.start)?(a.end<d.a.end):(a.start<d.a.start);
144 <          }
145 <     return (b.start==d.b.start)?(b.end<d.b.end):(b.start<d.b.start);*/
146 <     if (b.start==d.b.start) {
147 <        if (score==d.score) {
148 <           //just try to be consistent:
149 <           if (b.end==d.b.end) {
150 <             return (a.start==d.a.start)?(a.end>d.a.end):(a.start>d.a.start);
151 <             }
152 <           return (b.end<d.b.end);
153 <           }
154 <         else return (score>d.score);
155 <        }
156 <     return (b.start<d.b.start);
157 <     }
158 < };
159 <
160 < int cmpSegEnds(pointer sa, pointer sb) { //sort by adaptor seg ends AND score
161 < CSegPair& x = *(CSegPair *)sa;
162 < CSegPair& y = *(CSegPair *)sb;
163 < /*
164 < if (x.b.end==y.b.end) {
165 <     if (x.b.start==y.b.start) {
166 <         if (x.a.end==y.a.end) {
167 <            if (x.a.start==y.a.start) return 0;
168 <            return ((x.a.start>y.a.start) ? -1 : 1);
169 <            }
170 <          else {
171 <            return ((x.a.end>y.a.end) ? -1 : 1);
172 <            }
173 <          }
174 <      else {
175 <       return ((x.b.start>y.b.start) ? -1 : 1);
176 <       }
177 <     }
178 <    else {
179 <     return ((x.b.end>y.b.end) ? -1 : 1);
180 <     }
181 < */
182 <  if (x.b.end==y.b.end) {
183 <     if (x.score==y.score) {
184 <     if (x.b.start==y.b.start) {
185 <         if (x.a.end==y.a.end) {
186 <            if (x.a.start==y.a.start) return 0;
187 <            return ((x.a.start<y.a.start) ? -1 : 1);
188 <            }
189 <          else {
190 <            return ((x.a.end<y.a.end) ? -1 : 1);
191 <            }
192 <          }
193 <      else {
194 <       return ((x.b.start<y.b.start) ? -1 : 1);
195 <       }
196 <      } else return ((x.score>y.score) ? -1 : 1);
197 <     }
198 <    else {
199 <     return ((x.b.end>y.b.end) ? -1 : 1);
200 <     }
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 < }
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:
206 <   uint astart;
207 <   uint aend;
208 <   uint bstart;
209 <   uint bend;
210 <   int score;
211 <   bool endSort;
212 <  CSegChain(bool aln5=false):GList<CSegPair>(true,true,true) {//sorted, free elements, unique
213 <   //as SegPairs are inserted, they will be sorted by a.start coordinate
214 <   score=0;
215 <   astart=MAX_UINT;
216 <   aend=0;
217 <   bstart=MAX_UINT;
218 <   bend=0;
219 <   endSort=aln5;
220 <   if (aln5) { setSorted(cmpSegEnds); }
221 <   }
222 < bool operator==(CSegChain& d) {
223 <   //return (score==d.score);
224 <    return (astart==d.astart && aend==d.aend && bstart==d.bstart && bend==d.bend);
225 <   }
226 < bool operator>(CSegChain& d) { // order based on b (adaptor) coordinate
227 <   //return (score<d.score);
228 <   if (bstart==d.bstart && bend==d.bend) {
229 <          return (astart==d.astart)?(aend>d.aend):(astart>d.astart);
230 <          }
231 <     return (bstart==d.bstart)?(bend>d.bend):(bstart>d.bstart);
232 <   }
233 < bool operator<(CSegChain& d) {
234 <   //return (score>d.score);
235 <   if (bstart==d.bstart && bend==d.bend) {
236 <          return (astart==d.astart)?(aend<d.aend):(astart<d.astart);
237 <          }
238 <     return (bstart==d.bstart)?(bend<d.bend):(bstart<d.bstart);
239 <   }
240 < void addSegPair(CSegPair* segp) {
241 <   if (AddIfNew(segp)!=segp) return;
242 <   score+=segp->score;
243 <   if (astart>segp->a.start) astart=segp->a.start;
244 <   if (aend<segp->a.end) aend=segp->a.end;
245 <   if (bstart>segp->b.start) bstart=segp->b.start;
246 <   if (bend<segp->b.end) bend=segp->b.end;
247 <   }
248 < //for building actual chains:
249 < bool extendChain(CSegPair* segp) { //segp expected to be "Greater Than" current chain
250 <   int bgap=0;
251 <   int agap=0;
252 <   //if (endSort) {
253 <   if (bstart>segp->b.start) {
254 <      bgap = (int)(bstart-segp->b.end);
255 <      if (abs(bgap)>2) return false;
256 <      agap = (int)(astart-segp->a.end);
257 <      if (abs(agap)>2) return false;
258 <      }
259 <     else {
260 <      bgap = (int) (segp->b.start-bend);
261 <      if (abs(bgap)>2) return false;
262 <      agap = (int)(segp->a.start-aend);
263 <      if (abs(agap)>2) return false;
264 <      }
265 <   if (agap*bgap<0) return false;
266 <   addSegPair(segp);
267 <   score-=abs(agap)+abs(bgap);
268 <   return true;
269 <   }
270 < };
110 > CGreedyAlignData* gxmem_l=NULL;
111 > CGreedyAlignData* gxmem_r=NULL;
112  
113   // element in dhash:
114   class FqDupRec {
# Line 317 | 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
# Line 331 | Line 174
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
334 bool polytrim(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:f:t:o:z:a:");
188 >  GArgs args(argc, argv, "YQDCVAl:d:3:5:m:n:r:p:q:f:t:o:z:a:");
189    int e;
190    if ((e=args.isError())>0) {
191        GMessage("%s\nInvalid argument: %s\n", USAGE, argv[e]);
# Line 352 | Line 196
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 392 | 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('a');
252 >  s=args.getOpt('3');
253    if (!s.is_empty()) {
254 <     int a_minmatch=s.asInt();
255 <     a_min_score=a_minmatch<<1;
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');
# Line 424 | Line 278
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 +    //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;
# Line 455 | Line 317
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 (!doCollapse) {
459 <         if (fq2!=NULL) {
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",
# Line 488 | Line 349
349                 int nocounter=0;
350                 writeRead(f_out2, seqid2, seqinfo2, rseq2, rqv2, nocounter);
351                 }
352 <            } //paired read
492 <       // }
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++;
# Line 504 | Line 368
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
# Line 584 | Line 452
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)
# Line 595 | Line 465
465      FWCLOSE(f_out);
466      FWCLOSE(f_out2);
467     } //while each input file
468 <
468 > delete gxmem_l;
469 > delete gxmem_r;
470   //getc(stdin);
471   }
472  
# Line 861 | Line 732
732   return ncount;
733   }
734  
864
865 // ------------------ adapter matching - simple k-mer seed & extend, no indels for now
866 //when a k-mer match is found, simply try to extend the alignment using a drop-off scheme
867 //check minimum score and
868 //for 3' adapter trimming:
869 //     require that the right end of the alignment for either the adaptor OR the read must be
870 //     < 3 distance from its right end
871 // for 5' adapter trimming:
872 //     require that the left end of the alignment for either the adaptor OR the read must
873 //     be at coordinate < 3 from start
874
875 bool extendMatch(const char* a, int alen, int ai,
876                 const char* b, int blen, int bi, int mlen, int& l5, int& l3, CSegChain& segs, bool end5=false) {
877 //so the alignment starts at ai in a, bi in b, with a perfect match of length mlen
878 #ifdef DEBUG
879 GStr dbg(b);
880 #endif
881 //if (debug) {
882 //  GMessage(">> in %s\n\textending hit: %s at position %d\n", a, (dbg.substr(bi, mlen)).chars(), ai);
883 //  }
884 int a_l=ai; //alignment coordinates on a
885 int a_r=ai+mlen-1;
886 int b_l=bi; //alignment coordinates on b
887 int b_r=bi+mlen-1;
888 int ai_maxscore=ai;
889 int bi_maxscore=bi;
890 int score=mlen*a_m_score;
891 int maxscore=score;
892 int mism5score=a_mis_score;
893 if (end5 && ai<(alen>>1)) mism5score-=2; // increase penalty for mismatches at 5' end
894 //try to extend to the left first, if possible
895 while (ai>0 && bi>0) {
896   ai--;
897   bi--;
898   score+= (a[ai]==b[bi])? a_m_score : mism5score;
899   if (score>maxscore) {
900       ai_maxscore=ai;
901       bi_maxscore=bi;
902       maxscore=score;
903       }
904     else if (maxscore-score>a_dropoff_score) break;
905   }
906 a_l=ai_maxscore;
907 b_l=bi_maxscore;
908 //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);
909 //now extend to the right
910 ai_maxscore=a_r;
911 bi_maxscore=b_r;
912 ai=a_r;
913 bi=b_r;
914 score=maxscore;
915 //sometimes there are extra AAAAs at the end of the read, ignore those
916 if (strcmp(&a[alen-4],"AAAA")==0) {
917    alen-=3;
918    while (a[alen-1]=='A' && alen>ai) alen--;
919    }
920 while (ai<alen-1 && bi<blen-1) {
921   ai++;
922   bi++;
923   //score+= (a[ai]==b[bi])? a_m_score : a_mis_score;
924   if (a[ai]==b[bi]) { //match
925      score+=a_m_score;
926      if (ai>=alen-2) {
927           score+=a_m_score-(alen-ai-1);
928           }
929      }
930    else { //mismatch
931      score+=a_mis_score;
932      }  
933   if (score>maxscore) {
934       ai_maxscore=ai;
935       bi_maxscore=bi;
936       maxscore=score;
937       }
938     else if (maxscore-score>a_dropoff_score) break;
939   }
940  a_r=ai_maxscore;
941  b_r=bi_maxscore;
942  int a_ovh3=alen-a_r-1;
943  int b_ovh3=blen-b_r-1;
944  int mmovh3=(a_ovh3<b_ovh3)? a_ovh3 : b_ovh3;
945  int mmovh5=(a_l<b_l)? a_l : b_l;
946  //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);
947 #ifdef DEBUG
948  if (debug) GMessage("     extended to: %*s\n",a_r+1,dbg.substr(b_l,b_r-b_l+1).chars());
949 #endif
950  if (maxscore>=a_min_score && mmovh3<2 && mmovh5<2) {
951     if (a_l<a_ovh3) {
952        //adapter closer to the left end (typical for 5' adapter)
953        l5=a_r+1;
954        l3=alen-1;
955        }
956      else {
957        //adapter matching at the right end (typical for 3' adapter)
958        l5=0;
959        l3=a_l-1;
960        }
961     return true;
962     }
963 else { //keep this segment pair for later (gapped alignment)
964   segs.addSegPair(new CSegPair(a_l+1, a_r+1, b_l+1, b_r+1, maxscore));
965   //this will also update min & max coordinates in segs (segs.astart, .aend, .bstart, .bend)
966   }
967  //do not trim:
968  l5=0;
969  l3=alen-1;
970  return false;
971 }
972
973 /*
974 int getWordValue(const char* s, int wlen) {
975 int r=0;
976 while (wlen--) { r+=(((int)s[wlen])<<wlen) }
977 return r;
978 }
979 */
735   int get3mer_value(const char* s) {
736   return (s[0]<<16)+(s[1]<<8)+s[2];
737   }
# Line 1000 | 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-12), 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-3) ||
839 +    (maxloc.score==poly_minScore && ri==rlen-1) ||
840 +    (maxloc.score>(poly_minScore<<1) && ri>=rlen-6)) {
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   }
1031 #endif
1032 const char *pA_seed="AAAA";
1033 const char *pT_seed="TTTT";
1034 const int polyA_seed=*(int*)pA_seed;
1035 const int polyT_seed=*(int*)pT_seed;
848  
849 < bool trim_poly3(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 + 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
1043 //TODO: should we attempt polyA and polyT at the same time, same end?
858   // -- find the initial match (seed)
859 < int rlo=GMAX((rlen-10), 0);
860 < int si;
861 < for (si=rlen-5;si>rlo;si--) {
862 <   if (polyA_seed==*(int*)&(seq.chars()+si)) {
859 > int lmax=GMIN(8, 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        }
865     }
866 < if (si<=rlo) return false;
867 < //seed found, try to extend it to left and right
868 < int score=4*match_score;
869 < max_rlo=rlo;
870 < rlo--;
871 < while (rlo>=0) {
872 <    rlo--;
873 <    score+=
874 <    
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      }
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 +   if (maxloc.score<=loc.score) {
908 +      maxloc=loc;
909 +      }
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<<1) && li<6)) {
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 < //first try a full match, we might get lucky
929 < int fi=-1;
930 < if ((fi=seq.index(adapter3))>=0) {
931 <   if (fi<rlen-fi-a3len) {//match is closer to the right end
932 <      l5=fi+a3len;
933 <      l3=rlen-1;
934 <      }
935 <    else {
936 <      l5=0;
937 <      l3=fi-1;
938 <      }
939 <   return true;
940 <   }
941 < #ifdef DEBUG
942 < if (debug) GMessage(">TRIM3 >>   Read: %s\n",seq.chars());
943 < #endif
944 <
1085 < //also, for fast detection of other adapter-only reads that start past
1086 < // the beginning of the adapter sequence, try to see if the first a3len-4
1087 < // bases of the read are a substring of the adapter
1088 < if (rlen>a3len-3) {
1089 <   GStr rstart=seq.substr(1,a3len-4);
1090 <   if ((fi=adapter3.index(rstart))>=0) {
1091 <     l3=rlen-1;
1092 <     l5=a3len-4;
1093 <     while (fi+l5<a3len && l5<l3 && adapter3[fi+l5]==seq[l5]) l5++;
1094 <     return true;
1095 <     }
1096 <  }
1097 < CSegChain a3segs; //no chains here, just an ordered collection of segment pairs
1098 <  //check the easy cases - 11 bases exact match at the end
1099 < int fdlen=11;
1100 <  if (a3len<16) {
1101 <   fdlen=a3len>>1;
1102 <   }
1103 < if (fdlen>4) {
1104 <     //check if we're lucky enough to have the last 11 bases of the read a part of the adapter
1105 <     GStr rstart=seq.substr(-fdlen-3,fdlen);
1106 <     if ((fi=adapter3.index(rstart))>=0) {
1107 < #ifdef DEBUG
1108 <       if (debug) GMessage("  W11match found: %*s\n", rlen-3, (adapter3.substr(fi,fdlen)).chars());
1109 < #endif
1110 <       if (extendMatch(seq.chars(), rlen, rlen-fdlen-3,
1111 <                     adapter3.chars(), a3len, fi,  fdlen, l5,l3, a3segs))
1112 <            return true;
1113 <       }
1114 <     //another easy case: first 11 characters of the adaptor found as a substring of the read
1115 <     GStr bstr=adapter3.substr(0, fdlen);
1116 <     if ((fi=seq.rindex(bstr))>=0) {
1117 < #ifdef DEBUG
1118 <       if (debug) GMessage("  A11match found: %*s\n", fi+fdlen, bstr.chars());
1119 < #endif
1120 <       if (extendMatch(seq.chars(), rlen, fi,
1121 <                     adapter3.chars(), a3len, 0,  fdlen, l5,l3, a3segs))
1122 <            return true;
1123 <       }
1124 <     } //tried to match 11 bases first
1125 <    
1126 < //no easy cases, so let's do the wmer hashing for the first 12 bases of the adaptor
1127 < //-- only extend if the match is in the 3' (ending) region of the read
1128 < int wordSize=3;
1129 < int hlen=12;
1130 < if (hlen>a3len-wordSize) hlen=a3len-wordSize;
1131 < int imin=rlen>>1; //last half of the read, left boundary for the wmer match
1132 < if (imin<a3len) { imin=GMIN(a3len, rlen-wordSize); }
1133 < imin=rlen-imin;
1134 < for (int iw=0;iw<hlen;iw++) {
1135 <   //int32* qv=(int32*)(adapter3.chars()+iw);
1136 <   int qv=get3mer_value(adapter3.chars()+iw);
1137 <   fi=-1;
1138 <   //while ((fi=fast4rmatch(*qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
1139 <   while ((fi=w3_rmatch(qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
1140 <     //GMessage(" ... fi=%d after w3_rmatch() (imin=%d)\n", fi, imin);
1141 <
1142 < #ifdef DEBUG
1143 <     if (debug) GMessage("    Wmatch found: %*s\n", fi+wordSize, (adapter3.substr(iw,wordSize)).chars());
1144 < #endif
1145 <     if (extendMatch(seq.chars(), rlen, fi, adapter3.chars(),
1146 <                   a3len, iw, wordSize, l5,l3, a3segs)) return true;
1147 <     fi--;
1148 <     if (fi<imin) break;
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 wmer in the first hlen bases of the adaptor
947 < /*
1152 < //couldn't find a good trimming extension, hash 12 more bases of the adapter to collect more segment pairs there
1153 < //but only do this if we already have segment pairs collected in the last 12 bases of the adapter
1154 < if (a3segs.bstart>3 || a3segs.bend<(uint)(hlen-wordSize)) return false;
1155 < int hlen2=a3len-wordSize;
1156 < //if (hlen2>a3len-4) hlen2=a3len-4;
1157 < if (hlen2>hlen) {
1158 < #ifdef DEBUG
1159 <     if (debug && a3segs.Count()>0) {
1160 <        GMessage("  >>>>>2nd. hash: %s\n",seq.chars());
1161 <        }
1162 < #endif
1163 <     for (int iw=hlen;iw<hlen2;iw++) {
1164 <         //int* qv=(int32 *)(adapter3.chars()+iw);
1165 <         int qv=get3mer_value(adapter3.chars()+iw);
1166 <         fi=-1;
1167 <         //while ((fi=fast4rmatch(*qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
1168 <         while ((fi=w3_rmatch(qv, seq.chars(), rlen, fi))>=0 && fi>=imin) {
1169 <           extendMatch(seq.chars(), rlen, fi, adapter3.chars(),
1170 <                         a3len, iw, wordSize, l5,l3, a3segs);
1171 <           fi--;
1172 <           if (fi<imin) break;
1173 <           }
1174 <         } //for each wmer between hlen2 and hlen bases of the adaptor
1175 <     }
1176 < //lastly, analyze collected a3segs for a possible gapped alignment:
1177 < GList<CSegChain> segchains(false,true,false);
1178 < #ifdef DEBUG
1179 < if (debug && a3segs.Count()>0) {
1180 <   GMessage(">>>>>>>>>   Read: %s\n",seq.chars());
1181 <   }
1182 < #endif
1183 < for (int i=0;i<a3segs.Count();i++) {
1184 <   if (a3segs[i]->chain==NULL) {
1185 <       if (a3segs[i]->b.start>3) continue; //don't start a hopeless chain
1186 <       CSegChain* newchain=new CSegChain();
1187 <       newchain->setFreeItem(false);
1188 <       newchain->addSegPair(a3segs[i]);
1189 <       a3segs[i]->chain=newchain;
1190 <       segchains.Add(newchain); //just to free them when done
1191 <       }
1192 <   for (int j=i+1;j<a3segs.Count();j++) {
1193 <      CSegChain* chain=a3segs[i]->chain;
1194 <      if (chain->extendChain(a3segs[j])) {
1195 <          a3segs[j]->chain=chain;
1196 < #ifdef DEBUG
1197 <          if (debug) dbgPrintChain(*chain, adapter3.chars());
1198 < #endif      
1199 <          //save time by checking here if the extended chain is already acceptable for trimming
1200 <          if (chain->aend>(uint)(rlen-4) && chain->bstart<4 && chain->score>a_min_chain_score) {
1201 <            l5=0;
1202 <            l3=chain->astart-2;
1203 < #ifdef DEBUG
1204 <          if (debug && a3segs.Count()>0) {
1205 <            GMessage(">>> >> trimmed-3: %*s\n",l3-l5+1,seq.substr(l5,l3-l5+1).chars());
1206 <            }
1207 < #endif
1208 <            return true;
1209 <            }
1210 <          } //chain can be extended
1211 <      }
1212 <   } //collect segment alignments into chains
1213 < */  
1214 < return false; //no adapter parts found
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;
965 <      }
966 <   return true;
967 <   }
968 < #ifdef DEBUG
969 < if (debug) GMessage(">TRIM5 >>   Read: %s\n",seq.chars());
970 < #endif
1238 <
1239 < CSegChain a5segs(true); //list of segment pairs to analyze later if no extendMatch succeeded
1240 <
1241 < //try the easy way out first - look for an exact match of 11 bases
1242 < int fdlen=11;
1243 <  if (a5len<16) {
1244 <   fdlen=a5len>>1;
1245 <   }
1246 < if (fdlen>4) {
1247 <     GStr rstart=seq.substr(1,fdlen); //skip the first base as it's sometimes bogus
1248 <     if ((fi=adapter5.index(rstart))>=0) {
1249 < #ifdef DEBUG
1250 <       if (debug) GMessage("  W11match found: %*s\n", 1+fdlen, (adapter3.substr(fi,fdlen)).chars());
1251 < #endif
1252 <       if (extendMatch(seq.chars(), rlen, 1,
1253 <                     adapter5.chars(), a5len, fi,  fdlen, l5,l3, a5segs, true))
1254 <           return true;
1255 <       }
1256 <     //another easy case: last 11 characters of the adaptor found as a substring of the read
1257 <     GStr bstr=adapter5.substr(-fdlen);
1258 <     if ((fi=seq.index(bstr))>=0) {
1259 < #ifdef DEBUG
1260 <       if (debug) GMessage("  A11match found: %*s\n", fi+fdlen, bstr.chars());
1261 < #endif
1262 <       if (extendMatch(seq.chars(), rlen, fi,
1263 <                     adapter5.chars(), a5len, a5len-fdlen,  fdlen, l5,l3,a5segs,true))
1264 <          return true;
1265 <       }
1266 <     } //tried to matching at most 11 bases first
1267 <    
1268 < //-- no easy cases, do the wmer hashing for the last 12 bases of the adaptor
1269 < //-- only extend a wmer if it matches in the 5' (beginning) region of the read
1270 < int wordSize=3;
1271 < int hlen=12;
1272 < if (hlen>a5len-wordSize) hlen=a5len-wordSize;
1273 < int imax=rlen>>1; //first half of the read, right boundary for the wmer match
1274 < if (imax<a5len) { imax=GMIN(a5len, rlen-wordSize); }
1275 < for (int iw=0;iw<=hlen;iw++) {
1276 <   int apstart=a5len-iw-wordSize;
1277 <   fi=0;
1278 <   //int* qv=(int32 *)(adapter5.chars()+apstart);
1279 <   int qv=get3mer_value(adapter5.chars()+apstart);
1280 <   //while ((fi=fast4match(*qv, seq.chars(), rlen, fi))>=0 && fi<=imax) {
1281 <   while ((fi=w3_match(qv, seq.chars(), rlen, fi))>=0 && fi<=imax) {
1282 < #ifdef DEBUG
1283 <     if (debug) GMessage("    Wmatch found: %*s\n", fi+wordSize, (adapter5.substr(apstart,wordSize)).chars());
1284 < #endif
1285 <     if (extendMatch(seq.chars(), rlen, fi, adapter5.chars(),
1286 <                a5len, apstart, wordSize, l5,l3, a5segs, true)) return true;
1287 <     fi++;
1288 <     if (fi>imax) break;
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 wmer in the last hlen bases of the adaptor
973 < /*
974 <
1293 < //couldn't find a good trimming extension, hash 12 more bases of the adapter to collect more segment pairs there
1294 < //but only do this if we already have segment pairs collected in the last 12 bases of the adapter
1295 < if (a5segs.bend<(uint)(a5len-3) || a5segs.bstart>(uint)(a5len-hlen+4)) return false;
1296 < int hlen2=a5len-wordSize;
1297 < //if (hlen2>a5len-wordSize) hlen2=a5len-wordSize;
1298 < #ifdef DEBUG
1299 <      if (debug && a5segs.Count()>0) {
1300 <        GMessage("  >>>>>2nd. hash: %s\n",seq.chars());
1301 <        }
1302 < #endif
1303 < if (hlen2>hlen) {
1304 <     for (int iw=hlen+1;iw<=hlen2;iw++) {
1305 <         int apstart=a5len-iw-wordSize;
1306 <         fi=0;
1307 <         //int* qv=(int32 *)(adapter5.chars()+apstart);
1308 <         int qv=get3mer_value(adapter5.chars()+apstart);
1309 <         //while ((fi=fast4match(*qv, seq.chars(), rlen, fi))>=0 && fi<=imax) {
1310 <         while ((fi=w3_match(qv, seq.chars(), rlen, fi))>=0 && fi<=imax) {
1311 <           extendMatch(seq.chars(), rlen, fi, adapter5.chars(),
1312 <                      a5len, apstart, wordSize, l5,l3, a5segs, true);
1313 <           fi++;
1314 <           if (fi>imax) break;
1315 <           }
1316 <         } //for each wmer between hlen2 and hlen bases of the adaptor
1317 <     }
1318 < if (a5segs.bend<(uint)(a5len-3) || a5segs.bstart>(uint)(a5len-hlen+4)) return false;
1319 < // lastly, analyze collected a5segs for a possible gapped alignment:
1320 < GList<CSegChain> segchains(false,true,false);
1321 < #ifdef DEBUG
1322 < if (debug && a5segs.Count()>0) {
1323 <   GMessage(">>>>>>>>>   Read: %s\n",seq.chars());
1324 <   }
1325 < #endif
1326 < for (int i=0;i<a5segs.Count();i++) {
1327 <   if (a5segs[i]->chain==NULL) {
1328 <       if (a5segs[i]->b.end<(int)(a5len-4)) continue; //don't start a hopeless chain
1329 <       CSegChain* newchain=new CSegChain(true);
1330 <       newchain->setFreeItem(false);
1331 <       newchain->addSegPair(a5segs[i]);
1332 <       a5segs[i]->chain=newchain;
1333 <       segchains.Add(newchain); //just to free them when done
1334 <       }
1335 <   for (int j=i+1;j<a5segs.Count();j++) {
1336 <      CSegChain* chain=a5segs[i]->chain;
1337 <      if (chain->extendChain(a5segs[j])) {
1338 <         a5segs[j]->chain=chain;
1339 < #ifdef DEBUG
1340 <         if (debug) dbgPrintChain(*chain, adapter5.chars());
1341 < #endif      
1342 <      //save time by checking here if the extended chain is already acceptable for trimming
1343 <         if (chain->bend>(uint)(a5len-3) && chain->astart<4 && chain->score>a_min_chain_score) {
1344 <            l5=chain->aend;
1345 <            l3=rlen-1;
1346 <            return true;
1347 <            }
1348 <         } //chain can be extended
1349 <      }
1350 <   } //collect segment alignments into chains
1351 < */
1352 < return false; //no adapter parts found
1353 < }
972 >  }//for each 5' adapter
973 >  return trimmed;
974 > }
975  
976   //convert qvs to/from phred64 from/to phread33
977   void convertPhred(GStr& q) {
# Line 1414 | Line 1035
1035        }
1036      }// fastq
1037   // } //<-- FASTA or FASTQ
1038 < rseq.upper(); //TODO: what if we care about masking?
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   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 +   GMessage(">%s\n", rname.chars());
1065 +   GMessage("%s\n",rseq.chars());
1066 + #endif
1067   if (l3-l5+1<min_read_len) {
1068     return 's';
1069     }
# Line 1458 | Line 1099
1099     w5=0;
1100     w3=wseq.length()-1;
1101     }
1102 < if (a3len>0) {
1103 <  if (trim_adapter3(wseq, w5, w3)) {
1102 > char trim_code;
1103 > do {
1104 >  trim_code=0;
1105 >  if (trim_poly5(wseq, w5, w3, polyA_seed)) {
1106 >      trim_code='A';
1107 >      }
1108 >  else if (trim_poly5(wseq, w5, w3, polyT_seed)) {
1109 >      trim_code='T';
1110 >      }
1111 >  else if (trim_adapter5(wseq, w5, w3)) {
1112 >      trim_code='5';
1113 >      }
1114 >  if (trim_code) {
1115 >     #ifdef GDEBUG
1116 >      GMessage("#### TRIM by '%c' code ( w5-w3 = %d-%d ):\n",trim_code, w5,w3);
1117 >      showTrim(wseq, w5, w3);
1118 >     #endif
1119       int trimlen=wseq.length()-(w3-w5+1);
1120 <     num_trimmed3++;
1121 <     if (trimlen<min_trimmed3)
1122 <         min_trimmed3=trimlen;
1120 >     num_trimmed5++;
1121 >     if (trimlen<min_trimmed5)
1122 >         min_trimmed5=trimlen;
1123       l5+=w5;
1124       l3-=(wseq.length()-1-w3);
1125       if (w3-w5+1<min_read_len) {
1126 <         return '3';
1126 >         return trim_code;
1127           }
1128        //-- keep only the w5..w3 range
1129        wseq=wseq.substr(w5, w3-w5+1);
1130        if (!wqv.is_empty())
1131           wqv=wqv.substr(w5, w3-w5+1);
1132 <      }//some adapter was trimmed
1133 <   } //adapter trimming
1134 < if (a5len>0) {
1135 <  if (trim_adapter5(wseq, w5, w3)) {
1132 >      }// trimmed at 5' end
1133 > } while (trim_code);
1134 >
1135 > do {
1136 >  trim_code=0;
1137 >  if (trim_poly3(wseq, w5, w3, polyA_seed)) {
1138 >      trim_code='A';
1139 >      }
1140 >  else if (trim_poly3(wseq, w5, w3, polyT_seed)) {
1141 >      trim_code='T';
1142 >      }
1143 >  else if (trim_adapter3(wseq, w5, w3)) {
1144 >      trim_code='3';
1145 >      }
1146 >  if (trim_code) {
1147 >     #ifdef GDEBUG
1148 >     GMessage("#### TRIM by '%c' code ( w5-w3 = %d-%d ):\n",trim_code, w5,w3);
1149 >     showTrim(wseq, w5, w3);
1150 >     #endif
1151       int trimlen=wseq.length()-(w3-w5+1);
1152 <     num_trimmed5++;
1153 <     if (trimlen<min_trimmed5)
1154 <         min_trimmed5=trimlen;
1152 >     num_trimmed3++;
1153 >     if (trimlen<min_trimmed3)
1154 >         min_trimmed3=trimlen;
1155       l5+=w5;
1156       l3-=(wseq.length()-1-w3);
1157       if (w3-w5+1<min_read_len) {
1158 <         return '5';
1158 >         return trim_code;
1159           }
1160        //-- keep only the w5..w3 range
1161        wseq=wseq.substr(w5, w3-w5+1);
1162        if (!wqv.is_empty())
1163           wqv=wqv.substr(w5, w3-w5+1);
1164 <      }//some adapter was trimmed
1165 <   } //adapter trimming
1164 >      }//trimming at 3' end
1165 > } while (trim_code);
1166 >
1167 >
1168   if (doCollapse) {
1169     //keep read for later
1170     FqDupRec* dr=dhash.Find(wseq.chars());
# Line 1550 | Line 1223
1223   void trash_report(char trashcode, GStr& rname, FILE* freport) {
1224   if (freport==NULL || trashcode<=' ') return;
1225   if (trashcode=='3' || trashcode=='5') {
1226 <   fprintf(freport, "%s\tA%c\n",rname.chars(),trashcode);
1226 >   fprintf(freport, "%s\ta%c\n",rname.chars(),trashcode);
1227     }
1228   else {
1229     fprintf(freport, "%s\t%c\n",rname.chars(),trashcode);
# Line 1642 | Line 1315
1315      }
1316   }
1317  
1318 +
1319 + int loadAdapters(const char* fname) {
1320 +  GLineReader lr(fname);
1321 +  char* l;
1322 +  while ((l=lr.nextLine())!=NULL) {
1323 +   if (lr.length()<=3 || l[0]=='#') continue;
1324 +   if ( l[0]==' ' || l[0]=='\t' || l[0]==',' ||
1325 +        l[0]==';'|| l[0]==':' ) {
1326 +      int i=1;
1327 +      while (l[i]!=0 && isspace(l[i])) {
1328 +        i++;
1329 +        }
1330 +      if (l[i]!=0) {
1331 +        GStr s(&(l[i]));
1332 +        adapters3.Add(s);
1333 +        continue;
1334 +        }
1335 +      }
1336 +    else {
1337 +      GStr s(l);
1338 +      s.startTokenize("\t ;,:");
1339 +      GStr a5,a3;
1340 +      if (s.nextToken(a5))
1341 +         s.nextToken(a3);
1342 +      a5.upper();
1343 +      a3.upper();
1344 +      adapters5.Add(a5);
1345 +      adapters3.Add(a3);
1346 +      }
1347 +   }
1348 +   return adapters5.Count()+adapters3.Count();
1349 + }
1350 +
1351   void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
1352                         GStr& s, GStr& infname, GStr& infname2) {
1353   // uses outsuffix to generate output file names and open file handles as needed

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines