import java.io.*;
import java.net.*;

public class MatClient
{
  Socket sock;
  PrintWriter out;
  BufferedReader in;
  String sendRequest, fromServer;
  public MatClient()
  {
    sock = null;
    out  = null;
    in   = null;
    sendRequest = "";
    fromServer  = "";
    try
    {
      sock = new Socket( "localhost", 4444 );
      out = new PrintWriter( sock.getOutputStream(), true );
      in = new BufferedReader( new InputStreamReader( sock.getInputStream()) );
    }
    catch ( UnknownHostException e ) 
    { System.err.println("no localhost"); System.exit(1); } 
    catch (IOException e) { System.err.println( e ); System.exit(1); }
  }

  public void finishJob() throws IOException
  {
    out.close();
    in.close();
    sock.close();
  }

  public double createJob( String j ) throws IOException
  {
    sendRequest = j;
    // uncomment for debugging purposes
    // System.out.println("Send Matlab request" );
    out.println( sendRequest ); 
    double rez = 0.0;
    while(( fromServer = in.readLine() ) != null ) 
    {
      // comment this out when not debugging 
      System.out.println( "server: " + fromServer );
      if( fromServer.startsWith( "bye" ) )
      {
        finishJob();
        break;
      }
      else
      {
        // process answer from server
        if( sendRequest.startsWith( "testEE" ) )
          rez = Double.parseDouble( fromServer );
        if( sendRequest.startsWith( "testDM" ) )
          rez = Double.parseDouble( fromServer );

        // uncomment for debugging purposes
        // System.out.println("Result Returned");
        break;
      }
    }
    return rez;
  }
}

