package mlproject.io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FastaIterator {
    BufferedReader br;
    String header;
    
    public FastaIterator(String file) throws FileNotFoundException, IOException {
        br = new BufferedReader(new FileReader(file));
        String line;
        while((line = br.readLine()) != null){
            if(line.equals("")) continue;
            if(line.charAt(0) == '>'){
                header = line.trim().substring(1);
                break;
            }
        }
    }
    
    /*  return next fasta sequence from fasta file result[0] = header, result[1] = sequence*/
    public String[] next() throws IOException {
        if(header == null) return null;
        
        StringBuffer seq = new StringBuffer();
        String line;
        while(true){
            line = br.readLine();
            if(line == null){
                String header2 = header;
                header = null;
                br.close();
                return new String[]{header2,seq.toString()};
            }
            if(line.equals("")) continue;
            if(line.charAt(0) == '>'){
                String[] result = new String[]{header,seq.toString()};
                seq = new StringBuffer();
                header = line.trim().substring(1);
                return result;
            }
            seq.append(line.trim());
        }
    }
    
    
}
