/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bicat.GO;
import java.util.*;
import java.io.*;
/**
 *
 * @author Hamed
 */
public class GoReader {
static Scanner scanner;
    
public static LinkedList  getFunctionalClasses(String file,double thr_alpha)
{
    
    try {
			FileReader fr = new FileReader(file);
			LineNumberReader lnr = new LineNumberReader(fr);

			 // read the first line
                        String s = lnr.readLine();

			if (s == null)
				return new LinkedList();
			if (null != s && 0 == s.length())
				return new LinkedList(); // special case, when no GO exists
			
                        
                        FunctionalClass fclass ;
			LinkedList outputList = new LinkedList();
                        
                        // get the unused lines (7 lines)
                        for(int i=1;i<=7;i++)
                        {
                            s = lnr.readLine(); 
                        }
                     
                        // get the first line of information line no 9 
                        do{
                        s= lnr.readLine();
                        }while((null != s) && (0 != s.length()) && ! s.startsWith("GO:"));
                        
			//if (null != s && 0 != s.length())              s=s.substring(1);
                        
                                               
			while ((null != s) && (0 != s.length()))
                        {
				fclass=getFunctionClassFromLine(s,thr_alpha);
				
                                if(fclass !=null)
                                  outputList.add(fclass);
                                
                                s = lnr.readLine(); // get the next info line
                                
			}
			System.out.println(" no of Go's>>"+outputList.size());
                     
                        return outputList;
                     
		} catch (FileNotFoundException e) {
			System.err.println(e);
		} // System.exit(1);
		catch (IOException e) {
			System.err.println(e);
		} // System.exit(1); }

		return null;
}

public static FunctionalClass getFunctionClassFromLine(String s,double thr_Pvalue)
{
    
    FunctionalClass fClass=null;
    String [] parts = s.split("\\\t");
    String [] arr=null;
    String names="";
    if(parts.length <7 || parts[5]== null || "NA".equalsIgnoreCase(parts[5]))
      return null;
    else if (Double.valueOf(parts[5].trim()).isNaN() || Double.parseDouble(parts[5]) > thr_Pvalue )
       return null;
    else
    {
       fClass=new FunctionalClass();
       
       if(parts[0]!= null && parts[0].startsWith("GO:"))   // the name
       fClass.setName(parts[0].trim());
       else return null;
       
       if(parts[1] != null && isDouble(parts[1]))  // the pop freq //check that it is a no
              fClass.setPop_Freq(Double.parseDouble(parts[1].trim()));
       
       if(parts[2] != null && parts[2].contains("/"))  // the pop frac
       {
           arr=parts[2].trim().split("/");
           if(isInteger(arr[0]) && isInteger(arr[1]) )
           {
                    fClass.setContributed_Gene_No_In_Pop(Integer.parseInt(arr[0]));
                    fClass.setPop_count(Integer.parseInt(arr[1]));
                    fClass.setPop_Frac(parts[2].trim());
           }else return null;
       }else return null;
       
        
       if(parts[3] != null && parts[3].contains("/"))  //study frac
       {
           arr=parts[3].trim().split("/");
           if ( isInteger(arr[0]) && isInteger(arr[1]) )
           {
                fClass.setContributed_Gene_No_In_Cluster(Integer.parseInt(arr[0]));
                fClass.setGene_count_In_cluster(Integer.parseInt(arr[1]));
                fClass.setStudy_Freq(Double.parseDouble(arr[0])  /  Double.parseDouble(arr[1]));
                fClass.setStudy_Frac( parts[3]);
            }else return null;
       } else return null;
       
       
       if(parts[4] != null && ! "NA".equalsIgnoreCase(parts[4].trim()) && isDouble(parts[4]) )  // raw pvalue
       {
          fClass.setRaw__Pvalue(Double.parseDouble(parts[4].trim()));
       }
       
       fClass.setThr_Pvalue(thr_Pvalue);
       
       if(parts[5] != null && ! "NA".equalsIgnoreCase(parts[5].trim()) && isDouble(parts[5]))//  e score : corrcetd pvalue
       {
          fClass.setCorrected_Pvalue(Double.parseDouble(parts[5].trim()));
       }  
       
      if(parts[6] != null ) // desc 
       {
          fClass.setDescription(parts[6]);
       }  
      
       if(parts[7] != null)
       {
          int count=7;
          while(count<parts.length)
          {
              names+=" "+parts[count];
              //System.out.println(parts[count]);
              count++;
          }
       }
      
       fClass.setContributed_Genes_Names_Cluster(names);
      
     return fClass;
    }
  
}


public static LinkedList  getAllFunctionalClasses(String file)
{
    
    try {
            FileReader fr = new FileReader(file);
            LineNumberReader lnr = new LineNumberReader(fr);

             // read the first line
            String s = lnr.readLine();

            if (s == null)
                    return new LinkedList();
            if (null != s && 0 == s.length())
                    return new LinkedList(); // special case, when no GO exists


            FunctionalClass fclass ;
            LinkedList outputList = new LinkedList();

            // get the unused lines (7 lines)
            for(int i=1;i<=7;i++)
            {
                s = lnr.readLine(); 
            }

            // get the first line of information line no 9 
            do{
            s= lnr.readLine();
            }while((null != s) && (0 != s.length()) && ! s.startsWith("GO:"));

            //if (null != s && 0 != s.length())              s=s.substring(1);


            while ((null != s) && (0 != s.length()))
            {
                    fclass=getFunctionClassFromLine(s);

                    if(fclass !=null)
                      outputList.add(fclass);

                    s = lnr.readLine(); // get the next info line

            }
            System.out.println(" no of Go's>>"+outputList.size());

            return outputList;

            } catch (FileNotFoundException e) {
            System.err.println(e);
            } // System.exit(1);
            catch (IOException e) {
            System.err.println(e);
            } // System.exit(1); }

            return null;
}

public static FunctionalClass getFunctionClassFromLine(String s)
{
    
    FunctionalClass fClass=null;
    String [] parts = s.split("\\\t");
    String [] arr=null;
    String names="";
    if(parts.length <7 || parts[5]== null || "NA".equalsIgnoreCase(parts[5]) ||!isDouble(parts[5]))
      return null;
    else if (Double.valueOf(parts[5].trim()).isNaN())
       return null;
    else
    {
       fClass=new FunctionalClass();
       
       if(parts[0]!= null && parts[0].startsWith("GO:"))   // the name
       fClass.setName(parts[0].trim());
       else return null;
       
       if(parts[1] != null && isDouble(parts[1]))  // the pop freq //check that it is a no
              fClass.setPop_Freq(Double.parseDouble(parts[1].trim()));
       
       if(parts[2] != null && parts[2].contains("/"))  // the pop frac
       {
           arr=parts[2].trim().split("/");
           if(isInteger(arr[0]) && isInteger(arr[1]) )
           {
                    fClass.setContributed_Gene_No_In_Pop(Integer.parseInt(arr[0]));
                    fClass.setPop_count(Integer.parseInt(arr[1]));
                    fClass.setPop_Frac(parts[2].trim());
           }else return null;
       }else return null;
       
        
       if(parts[3] != null && parts[3].contains("/"))  //study frac
       {
           arr=parts[3].trim().split("/");
           if ( isInteger(arr[0]) && isInteger(arr[1]) )
           {
                fClass.setContributed_Gene_No_In_Cluster(Integer.parseInt(arr[0]));
                fClass.setGene_count_In_cluster(Integer.parseInt(arr[1]));
                fClass.setStudy_Freq(Double.parseDouble(arr[0])  /  Double.parseDouble(arr[1]));
                fClass.setStudy_Frac( parts[3]);
            }else return null;
       } else return null;
       
       
       if(parts[4] != null && ! "NA".equalsIgnoreCase(parts[4].trim()) && isDouble(parts[4]) )  // raw pvalue
       {
          fClass.setRaw__Pvalue(Double.parseDouble(parts[4].trim()));
       }
       
      // fClass.setThr_Pvalue(thr_Pvalue);
       
       if(parts[5] != null && ! "NA".equalsIgnoreCase(parts[5].trim()) && isDouble(parts[5]))//  e score : corrcetd pvalue
       {
          fClass.setCorrected_Pvalue(Double.parseDouble(parts[5].trim()));
       }  
       
      if(parts.length >=7 && parts[6] != null ) // desc 
       {
          fClass.setDescription(parts[6]);
       }  
      
       if(parts.length >=8 && parts[7] != null)
       {
          int count=7;
          while(count<parts.length)
          {
              names+=" "+parts[count];
              //System.out.println(parts[count]);
              count++;
          }
       }
      
       fClass.setContributed_Genes_Names_Cluster(names);
      
     return fClass;
    }
  
}


public static LinkedList filterFCListByPvalue(LinkedList fclassList,double thr_Pvalue)
{
    LinkedList outputFcList=new LinkedList();
    FunctionalClass fclass;
    for(int i=0;i<fclassList.size();i++)
    {
        fclass=(FunctionalClass)fclassList.get(i);
        if(fclass.getCorrected_Pvalue()< thr_Pvalue)
        {
            fclass.setThr_Pvalue(thr_Pvalue);
            outputFcList.add(fclass);
        }
    }
    return outputFcList;
}


public static boolean isDouble(String s)
{
scanner = new Scanner(s);
return scanner.hasNextDouble();
}
public static boolean isInteger(String s)
{
scanner = new Scanner(s);
return scanner.hasNextInt();
}












}
