import java.net.*;
import java.awt.*;
import java.io.*;

public class SockStreamTextArea extends TextArea implements Runnable {
     Socket mySocket;
     InputStream is;
     String stub= new String("");

     SockStreamTextArea(Socket s){
	  super();
	  initSocket(s);
     }
     SockStreamTextArea(int x, int y,Socket s){
	  super(x,y);
	  initSocket(s);
     }
     SockStreamTextArea(String st, Socket s){
	  super(st);
	  initSocket(s);
     }
     SockStreamTextArea(String st, int x, int y, Socket s){
	  super(st, x, y);
	  initSocket(s);
     }

     public void initSocket (Socket s){
	  mySocket = s;
	  try { is = s.getInputStream(); }
	  catch (Exception e) { 
	       System.out.println("can't get input stream...\n");
	       System.exit(0); }
     }

     public void run() {
	  int n, x=0;
	  byte b[];

	  try { Thread.sleep(6000); } catch (Exception e) {}
	  try {
	       while( (n=is.read(b = new byte[100], 0, 100)) >= 0) {
		    String s = new String(b, 0);
		    s = stub+s;
		    stub = new String("");
		    s = autoFill(s,60);
		    appendText(s);
	       }
	  } catch (Exception e) { 
	  System.out.println("Doh! "+ e);
	  System.exit(0); }
     }

     public String autoFill(String s, int w){
	  String s2, s3, s4;

	  System.out.println("Autofilling----\n"+s+"\n-----");

	  if(s.indexOf("\n") > w){
	       System.out.println("Wrapping!"+s.indexOf("\n"));
	       int i = s.lastIndexOf(" ", w);
	       if(i >= 0){
		    s2 = s.substring(0,i-1);
		    stub = s.substring(i+1);
		    s4 = autoFill(stub, w);
		    return new String(stub+"\n"+s4);
	       }
	       else{
		    System.out.println("Uh oh");
		    return(s);
	       }
	  }
	  else{
	       System.out.println("No wrap\n==========");
	       if(s.indexOf("\n") >= 0){
		    s2 = s.substring(0, s.indexOf("\n")-1);
		    stub = s.substring(s.indexOf("\n")+1);
		    s4 = autoFill(stub, w);
		    return new String(s2+"\n"+s4);
	       }
	       else {
		    stub = s;
		    return new String("");
	       }
	  }
	  
     }

}
