package org.fda.alignmentparser.delta;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.fda.data.Reference;
import org.fda.data.ReferenceSet;
import org.fda.data.Utilities;

/**
 *
 * @author Gokhan.Yavas
 */
public class DeltaFileReader {
    private BufferedReader br;    
    private String header = null;
    private ReferenceSet chrset;
    
    public DeltaFileReader(){
        
    }
    public void openFile(File f, ReferenceSet c) throws FileNotFoundException, IOException{        
        chrset = c;
        br = new BufferedReader(new FileReader(f));
        
        // read the first two lines
        for(int i=0; i<2; i++)
            header = header + Utilities.ls + br.readLine(); 
    }
    public DeltaRecord readNextDeltaRecord(){
        String line;
        String contigID=null;
        Reference refID=null;
        DeltaRecord dr=null;
        StringBuilder sb= new StringBuilder();
        String[] rec;
        boolean first=true;
        int contigLength=0;
        int refChrLength=0;
        try{
            while((line = br.readLine())!=null){
                if(line.startsWith(">")){
                    if(first){
                        line = line.substring(1);
                        rec = line.split(" ");
                        contigID = rec[1];
                        refID = chrset.findReference(rec[0]);
                        contigLength = Integer.parseInt(rec[3]);
                        refChrLength = Integer.parseInt(rec[2]);
                        first =false;
                    }
                    else{
                        br.reset();
                        break;
                    }
                }
                else{
                    sb = sb.append(line+Utilities.ls);
                    br.mark(Utilities.mark4BackTrack);
                }
            }
            if(contigID!=null && refID !=null)
                dr = new DeltaRecord(refID, contigID, sb.toString(),contigLength, refChrLength);
            else
                br.close();
        }
        catch(Exception e){e.printStackTrace();}
        return dr;
    }
    public void closeReader() throws FileNotFoundException, IOException{
        br.close();
    }
    
}
