/*
 * Copyright (c) 2010 The Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package org.broadinstitute.sting.gatk.walkers.fasta;

import org.broad.tribble.util.variantcontext.VariantContext;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.walkers.*;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.collections.Pair;


/**
 * Generates an alternative reference sequence over the specified interval.  Given variant ROD tracks,
 * it replaces the reference bases at variation sites with the bases supplied by the ROD(s).  Additionally,
 * allows for a "snpmask" ROD to set overlapping bases to 'N'.
 */
@WalkerName("FastaAlternateReferenceMaker")
@Reference(window=@Window(start=0,stop=50))
@Requires(value={DataSource.REFERENCE})
public class FastaAlternateReferenceWalker extends FastaReferenceWalker {

    private int deletionBasesRemaining = 0;

    public Pair<GenomeLoc, String> map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {

        if (deletionBasesRemaining > 0) {
            deletionBasesRemaining--;
            return new Pair<GenomeLoc, String>(context.getLocation(), "");
        }

        String refBase = String.valueOf(ref.getBaseAsChar());

        for ( VariantContext vc : tracker.getAllVariantContexts(ref) ) {
            // if we have multiple variants at a locus, just take the first one we see
            if (!vc.getSource().startsWith("snpmask") && vc.isDeletion()) {
                deletionBasesRemaining = vc.getReference().length();
                // delete the next n bases, not this one
                return new Pair<GenomeLoc, String>(context.getLocation(), refBase);
            } else if (!vc.getSource().startsWith("snpmask") && vc.isInsertion()) {
                return new Pair<GenomeLoc, String>(context.getLocation(), refBase.concat(vc.getAlternateAllele(0).toString()));
            } else if (vc.isSNP()) {
                return new Pair<GenomeLoc, String>(context.getLocation(), (vc.getSource().startsWith("snpmask") ? "N" : vc.getAlternateAllele(0).toString()));
            }
        }

        // if we got here then we're just ref
        return new Pair<GenomeLoc, String>(context.getLocation(), refBase);
    }
}
@@ -1589,16 +1589,46 @@
 .Pair;%0A%0A
+import java.util.Collection;%0A%0A
 %0A/**%0A * 
@@ -2509,14 +2509,19 @@
     
-for ( 
+Collection%3C
 Vari
@@ -2534,13 +2534,15 @@
 text
+%3E
  vc
- :
+s =
  tra
@@ -2576,22 +2576,19 @@
 ref)
- ) %7B%0A 
+;%0A%0A
         
    /
@@ -2587,85 +2587,89 @@
     
-   // if we have multiple variants at a locus, just take the first one we see
+// Check to see if we have a called snp%0A        for ( VariantContext vc : vcs ) %7B
 %0A   
@@ -2677,24 +2677,25 @@
         if (
+ 
 !vc.getSourc
@@ -2716,26 +2716,48 @@
 (%22snpmask%22) 
-&&
+) %7B%0A                if (
  vc.isDeleti
@@ -2756,32 +2756,36 @@
 isDeletion()) %7B%0A
+    
                 
@@ -2853,16 +2853,20 @@
         
+    
 // delet
@@ -2906,32 +2906,36 @@
                 
+  
+  
 return new Pair%3C
@@ -2990,32 +2990,36 @@
 e);%0A            
+    
 %7D else if (!vc.g
@@ -3017,48 +3017,8 @@
 if (
-!vc.getSource().startsWith(%22snpmask%22) &&
  vc.
@@ -3042,32 +3042,36 @@
                 
+   
+ 
 return new Pair%3C
@@ -3170,32 +3170,36 @@
 ));%0A            
+    
 %7D else if (vc.is
@@ -3203,24 +3203,28 @@
 .isSNP()) %7B%0A
+    
             
@@ -3289,90 +3289,363 @@
 (), 
-(vc.getSource().startsWith(%22snpmask%22) ? %22N%22 : vc.getAlternateAllele(0).toString())
+vc.getAlternateAllele(0).toString());%0A                %7D%0A            %7D%0A        %7D%0A%0A        // if we don't have a called site, and we have a mask at this site, mask it%0A        for ( VariantContext vc : vcs ) %7B%0A            if ( vc.getSource().startsWith(%22snpmask%22) && vc.isSNP()) %7B%0A                return new Pair%3CGenomeLoc, String%3E(context.getLocation(), %22N%22
 );%0A 
@@ -3649,32 +3649,32 @@
 ;%0A            %7D%0A
-
         %7D%0A%0A     
@@ -3660,32 +3660,33 @@
    %7D%0A        %7D%0A%0A
+%0A
         // if we

Fix for instability in output of fasta alternative reference maker when snpmask and snp files are provided and have overlapping records. The order of the records changed due to optimization of the refmetadatatracker, and uncovered this non-determinanism. Now preferrentially masks out includes sites from snps before considering masking out sites in snpmask