/*
 * Copyright 2009 Lari Natri <lari.natri@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package compid.sequences;

import java.util.HashMap;
import java.util.ListIterator;

/**
 * Sequence aligner using standard Needleman-Wunsch global alignment algorithm
 * @author Lari Natri
 */
public final class NeedlemanWunschAligner extends Aligner
{

    public NeedlemanWunschAligner(SimilarityMatrix s)
    {
        super(s);
    }

//    public static int biggestSizeMib = 0;

    @Override
    protected Alignment doActualAlignment(Sequence seqA, Sequence seqB)
            throws Exception
    {
        // TODO: use getGapScore(int) instead of getOpenGapScore to be
        // compatible with possible gap scorer functions

        if (seqA == null || seqB == null) {
            throw new Exception("AlignmentProblem"); // TODO: make nice exception
        }

//        int sizeMib = seqA.getLength()*seqB.getLength()*8/1024/1024;
//        if (sizeMib>biggestSizeMib) {
//            biggestSizeMib = sizeMib;
//            System.out.println("DEBUG: Biggest aligner matrix size for ("+seqA.getLength()+","+seqB.getLength()+") is "+biggestSizeMib + "MiB");
//        }

        double[][] matrix = new double[seqA.getLength() + 1][seqB.getLength() + 1];

        int i;
        int j;
        for (i = 0; i <= seqA.getLength(); ++i) {
            matrix[i][0] = i * simMatrix.getOpenGapScore();
        }
        for (j = 0; j <= seqB.getLength(); ++j) {
            matrix[0][j] = j * simMatrix.getOpenGapScore();
        }

        double chNoGap;
        double chAGap;
        double chBGap;
        double thisPairScore;

        ListIterator<Component> aIter = seqA.iterator();
        ListIterator<Component> bIter = null;
        i = 0;
        Component a = null;
        Component b = null;
        while (aIter.hasNext()) {
            a = aIter.next();
            ++i;
            bIter = seqB.iterator();
            j = 0;
            while (bIter.hasNext()) {
                b = bIter.next();
                ++j;
                thisPairScore = simMatrix.getSimilarityScore(a, b);
                chNoGap = matrix[i - 1][j - 1] + thisPairScore;
                chAGap = matrix[i - 1][j] + simMatrix.getOpenGapScore();
                chBGap = matrix[i][j - 1] + simMatrix.getOpenGapScore();
                // set best of three choices to matrix[i][j]
                matrix[i][j] = chAGap;
                if (chBGap > matrix[i][j]) {
                    matrix[i][j] = chBGap;
                }
                if (chNoGap > matrix[i][j]) {
                    matrix[i][j] = chNoGap;
                }
            }
        }


        i = seqA.getLength();
        j = seqB.getLength();

        HashMap<Integer, Integer> aGaps = new HashMap<Integer, Integer>(8);
        HashMap<Integer, Integer> bGaps = new HashMap<Integer, Integer>(8);

        Integer oldGap = null;

        int substCount = 0;

        int oldI = -1;
        int oldJ = -1;

        // construct aligned strings
        while (i > 0 && j > 0) {
            if (oldI != i) {
                a = aIter.previous();
                oldI = i;
            }
            if (oldJ != j) {
                b = bIter.previous();
                oldJ = j;
            }
            //System.out.println(i + "_" + j + " " + substCount);
            thisPairScore = simMatrix.getSimilarityScore(a, b);

            if (matrix[i][j] == matrix[i - 1][j - 1] + thisPairScore) {
                if (a.equals(b) == false && a.equalsLoosely(b) == false) {
                    substCount++;
                }
                --i;
                --j;
            } else if (matrix[i][j] == matrix[i - 1][j] + simMatrix.getOpenGapScore()) {
                oldGap = bGaps.get(j);
                if (oldGap == null) {
                    oldGap = 0;
                }
                ++oldGap;
                bGaps.put(j, oldGap);
                --i;
                ++substCount;
            } else {
                oldGap = aGaps.get(i);
                if (oldGap == null) {
                    oldGap = 0;
                }
                ++oldGap;
                aGaps.put(i, oldGap);
                --j;
                ++substCount;
            }
        }

        // add leading gapmarks
        while (aIter.hasPrevious()) {
            oldGap = bGaps.get(0);
            if (oldGap == null) {
                oldGap = 0;
            }
            ++oldGap;
            bGaps.put(0, oldGap);
            aIter.previous();
            ++substCount;
        }
        while (bIter.hasPrevious()) {
            oldGap = aGaps.get(0);
            if (oldGap == null) {
                oldGap = 0;
            }
            ++oldGap;
            aGaps.put(0, oldGap);
            bIter.previous();
            ++substCount;
        }

        final Sequence[] seqs = new Sequence[2];
        seqs[0] = seqA;
        seqs[1] = seqB;
        @SuppressWarnings("unchecked")
        final HashMap<Integer, Integer>[] gaps = new HashMap[2];
        gaps[0] = aGaps;
        gaps[1] = bGaps;
        
        /*
        // DEBUG start
        System.out.println("DEBUG: (NeedlemanWunschAligner: matrix)");
        for (int x=0; x<matrix.length; ++x) {
            for (int y=0; y<matrix[x].length; ++y) {
                System.out.print(matrix[x][y]+"\t");
            }
            System.out.println();
        }
        // DEBUG end
        */
        
        return new Alignment(seqs, matrix[seqA.getLength()][seqB.getLength()], substCount, gaps);

    }
}
