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

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

// Packages specific to network design tool.

class ThreadedPost extends Thread {
private String home;
private String file;
private String message;
private StringBuffer rbuf;
int port = 80;
  
public ThreadedPost(String home, String file, String message,
		    StringBuffer rbuf) {
  this.home = home;
  this.file = file;
  this.message = message;
  this.rbuf = rbuf;
}

public void run() {
  int i;
  Socket s = null;

  String line;
  try {
    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");
    os.writeBytes(message);

    // it may take a while for the server to feed back the result
    // so, let's give other Threads a chance to run.
    Thread.yield();
    for (int k = 0; k < 10; k++) {
      for (int j = 0; j < 100; j++) {
	Math.cos(k+j);
      }
    }

    while ( (line = is.readLine()) != null )
      rbuf.append(line + "\n");
    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:");
      }
    }
  } 
}

/**
 * call the CGI program which solves linear programming
 */
public static String linearProgramming(ThreadGroup tg,
				       String threadName,
				       String sData) {
  String home = "www.cs.wustl.edu";
  String file = "/~hma/script/lp_solve.cgi";
  StringBuffer rbuf = new StringBuffer();
  ThreadedPost tp = new ThreadedPost(home, file, sData + (char)255, rbuf);
  tp.start();
  /*
  try {
    tp.join();
  }
  catch (InterruptedException e) {
    System.err.println("interrupted  while join():" + e.getMessage());
  }
  */
  int i = 0;
  while(tp.isAlive()) {
    System.out.print(" " + i++);
//    yield();
  }
  return rbuf.toString();
}

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

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

  String rData = ThreadedPost.linearProgramming(sData);
  System.out.println(rData);
}

} // end of class ThreadedPost

