package bullet;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author unascribed
 * @version 1.0
 */

import java.io.*;
import java.util.*;

public class gene {

  public int orfstart = 0;
  public int start = 0;
  public int end = 0;
  public String seq = null;
  public String orfseq = null;
  public int score = 0;
  public String prediction = "";
  public int num = -1;

  public gene() {
  }

  public static Vector ReadGlimmerOutput(String fn){
    Vector res = new Vector();
    boolean start = false;
    try{
    LineNumberReader lr = new LineNumberReader(new FileReader(fn));
    String s = null;
    while((s=lr.readLine())!=null){

    if(s.trim().startsWith("End")) start = false;
    if(start){
      String ss = s.substring(0,7);
      s = s.substring(10);
      StringTokenizer st = new StringTokenizer(s," \t");
      gene G = new gene();
      if(!ss.trim().equals("")) G.num = Integer.parseInt(ss.trim());
      String token = st.nextToken();
      G.orfstart = Integer.parseInt(token);
      token = st.nextToken();
      G.start = Integer.parseInt(token);
      token = st.nextToken();
      G.end = Integer.parseInt(token);
      st.nextToken(); st.nextToken();
      token = st.nextToken();
      G.score = Integer.parseInt(token);
      res.add(G);
    }

    if(s.trim().startsWith("ID")) start = true;

    }
    }catch(Exception e){
      e.printStackTrace();
    }
    return res;
  }

  public void extractSeq(String s){

    int en = end;
    try{
    if(start<end){
    if(en+3<s.length()) en+=3;
      else en--;

    orfseq = s.substring(orfstart-1,en);
    seq = s.substring(start-1,en);}
    else{
      orfseq = s.substring(end-4,orfstart);
      seq = s.substring(end-4,start);
      orfseq = invertString(orfseq);
      seq = invertString(seq);
    }
    }catch(Exception e){
      System.out.println("Error in exctracting seq: length="+s.length()+" start="+start+" end="+en);
    }
  }

  public static String readSeqFromFasta(String fn){
    StringBuffer res = new StringBuffer();
    boolean start = false;
    try{
    LineNumberReader lr = new LineNumberReader(new FileReader(fn));
    String s = null;
    while((s=lr.readLine())!=null){
    if(start){
      res.append(s.trim().toLowerCase());
    }
    if(s.trim().startsWith(">")) start = true;

    }
    }catch(Exception e){
      e.printStackTrace();
    }
    return res.toString();
   }

   public static String invertString(String s){
     StringBuffer sb = new StringBuffer(s);
     StringBuffer sb1 = new StringBuffer(s);
     int l = sb.length();
     for(int i=0;i<sb.length();i++){
       if(sb.charAt(i)=='a') sb1.setCharAt(l-i-1,'t'); else
       if(sb.charAt(i)=='t') sb1.setCharAt(l-i-1,'a'); else
       if(sb.charAt(i)=='g') sb1.setCharAt(l-i-1,'c'); else
       if(sb.charAt(i)=='c') sb1.setCharAt(l-i-1,'g');
     }
     return sb1.toString();
   }

}