/*
 * This class calls the cap3 program and starts two threads
 * to control stdin and stdout of cap3 process.
 * */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Calendar;

public class WSCap3{

   private Process processo;
   private String path = "d:\\programas\\cap3\\wscap3\\";
   private String arqSaida;

   private String getData(){

      String dataFormatada;

      Calendar data = Calendar.getInstance();

      int ano = data.get(Calendar.YEAR);
      int mes = data.get(Calendar.MONTH) + 1;
      int dia = data.get(Calendar.DAY_OF_MONTH);

      int hora = data.get(Calendar.HOUR_OF_DAY);
      int minuto = data.get(Calendar.MINUTE);
      int segundo = data.get(Calendar.SECOND);

      dataFormatada = ano + "" + mes + "" + dia + "_" + hora + "" + minuto + "" + segundo;

      return dataFormatada;

   }
   
// Reads the cap3 output file and returns the content
   private String outFile() throws Exception{

      BufferedReader br = new BufferedReader(new FileReader(arqSaida));
      String nextLine = "";
      StringBuffer sb = new StringBuffer();

      while ((nextLine = br.readLine()) != null) {
         sb.append(nextLine);
         sb.append("\n");
      }
      return sb.toString();
   }

   public String runCap3(String input) throws IOException,Exception{

      String newPath = path + this.getData() + "\\";

      String cmd = "cmd /C md " + newPath;
      processo = Runtime.getRuntime().exec(cmd);
      processo.waitFor();

      cmd = "cmd /C copy " + input + " " + newPath + "my_seqs";
      processo = Runtime.getRuntime().exec(cmd);
      processo.waitFor();

      arqSaida = newPath + "my_seqs.cap.contigs";

      cmd = "d:\\programas\\cap3\\cap3 " + newPath + "my_seqs";
      processo = Runtime.getRuntime().exec(cmd);
      
//    Starting the thread to handle cap3 stdin
      StringBuffer inBuffer = new StringBuffer();
      InputStream inStream = processo.getInputStream();
      new InputStreamHandler( inBuffer, inStream );
//    Starting the thread to handle cap3 stderr
      StringBuffer errBuffer = new StringBuffer();
      InputStream errStream = processo.getErrorStream();
      new InputStreamHandler( errBuffer , errStream );
      
      processo.waitFor();
      
      Writer output;
      output = new BufferedWriter(new FileWriter(newPath + "out"));
      output.write(inBuffer.toString());
      output.close();

      return outFile();

   }

}
