/* 
 * $Log$
 */
//////////////////////////////////////////////////
package general;

// Standard packages.
import java.io.*;
import java.net.*;

// Packages specific to network design tool.

public class CGI {
public static String post(String home, String file, String message) {
  int port = 80;
  Socket s = null;
  StringBuffer rbuf = new StringBuffer();
  String line;
  try {
    Thread.yield();
    s = new Socket(home, port);
    DataOutputStream os = new DataOutputStream(s.getOutputStream());
    DataInputStream is = new DataInputStream(s.getInputStream());

    os.writeBytes("POST " + file
		  + " HTTP/1.0\r\n"
		  + "Content-type: text/plain\r\n"
		  + "Content-length: " 
		  + message.length() + "\r\n\r\n");
    Thread.yield();
    os.writeBytes(message);
    while (is.available() == 0) {
      Thread.yield();
    }
    while ( (line = is.readLine()) != null ) {
      rbuf.append(line + "\n");
      Thread.yield();
    }
    is.close();
    os.close();
  }
  catch (Exception e) {
    System.out.println("Error " + e.getMessage());
    if (s != null) {
      try {
	s.close();
      }
      catch (IOException ex) {
	System.out.println("IOException in post:");
      }
    }
  } 
  return rbuf.toString();
}

/**
 * call the CGI program which solves linear programming
 */
public static String linearProgramming(String sData) {
  String home = "www.cs.wustl.edu";
  String file = "/~hma/script/lp_solve.cgi";
  // the trailing (char)255 is needed so that the lp_solve can
  // know that it's the end of file
  // sData = sData + (char)255;
  //System.out.println("CGI.linearProgramming Data = \n" + sData);
  //System.out.println("bytes sent = " + sData.length());
  String ret = CGI.post(home, file, sData);
  //System.out.println("String returned from LinearProgramming:\n" + ret);
  //System.out.println("bytes received = " + ret.length());
  return ret;
}

/**
 * call the CGI program which does Delaunay Triangulation
 */
public static String DelaunayTriangulation(String sData) {
  String home = "www.cs.wustl.edu";
  // switch -t means triangulation
  String file = "/~hma/script/voronoi.cgi?-t"; 
  return CGI.post(home, file, sData);
}

public static void main(String args[]) {
  String sData = "4\n" + "max: -x1 + 2 x2;\n" +
    "C1: 2x1 + x2 < 5;\n" + " -4 x1 + 4 x2 <5;\n" +
      "int x2,x1;\n";
  System.out.println(sData);

  String home = "www.cs.wustl.edu";
  String file = "/~hma/cgi-bin/lp.cgi";

  String rData = CGI.post(home, file, sData);
  System.out.println(rData);
}

} // end of class CGI

