/* Copyright Andy C. Deck 1999 All rights reserved. */    
import java.io.*;
import java.net.*;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Component;
import java.util.StringTokenizer;

public class readAnim implements Runnable {
Thread thread;
boolean penDown;
int wid,ht;
play but;
Graphics g;
drawPanel dp;
openStudio ops;
String fname;

    public readAnim(int wid,int ht, openStudio ops,play b,String name) {
	this.ops       = ops;
	this.wid       = wid;
	this.ht        = ht;
	this.fname     = name;
        dp             = ops.dp;
	this.g         = dp.myGetGraphics();
	this.dp        = dp;
	but            = b;
	start();
    }	

    public void start(){
	thread = new Thread(this);
        thread.setPriority(Thread.MIN_PRIORITY);	
        thread.start();
    }

    public void stop(){
	if(thread!=null) thread.stop();
	thread = null;
    }

    public void run(){
	String get = new String("GET /draw/cgi/draw.cgi?"+fname+" HTTP/1.0\n" +
              "User-Agent: " + System.getProperty("java.version") + " " +
                  System.getProperty("java.vendor")+ " " +
                  System.getProperty("os.name")+"\n\n");  
	byte[] GET = new byte[get.length()];
	Rectangle r=new Rectangle();
  	String line         = null;
	Socket sock         = null;
  	DataInputStream is  = null;
  	OutputStream os  = null;
  	Item d              = new Item();
	get.getBytes(0,get.length(),GET,0);
	but.start();
	byte[] buf = new byte[10000];
	int dataLen=0;
	try{
		sock = new Socket(Env.host, 80); 
	        os = sock.getOutputStream();
                if(os!=null)os.write(GET);
		is = new DataInputStream(new BufferedInputStream(sock.getInputStream()));
		while((line=is.readLine())!=null &&
                       line.length()>1){
			StringTokenizer st = new StringTokenizer(line);
			if(st.nextToken().equals("Content-Length:")){
				dataLen = Integer.parseInt(st.nextToken());
				System.out.println(dataLen);
			}
		}
		Thread.sleep(20);
		byte[] head = new byte[2];
		short clen;
		Stroke s;
		d.id = 9;
	
		while(thread!=null && dataLen >0){
		   if(is!=null) is.readFully(head);
		   clen = (short)((int)head[0]<<8|((int)head[1])&0x00ff); 
		   if(clen>=3 && clen <=10000){
			if(is!=null)
                        is.readFully(buf,0,clen);
		   	//thread.sleep(25);
		   	if(buf!=null)
			   ops.handleStroke(buf,(int)clen);
		   }else{
		        System.out.println("Stopping because clen="+clen);
			break;
		   }
		   dataLen -= (clen+2);
		}
		sock.close(); 
               }catch(Exception e){}  
		  but.stop();
		  dp.repaint(0,0,wid,ht);
               }
/*
		if(is!=null) is.close();
		if(os!=null) os.close();
		if(sock!=null) sock.close();
	    }
	    catch(Exception e){ }
	    finally{
	       //but.stop();
	       //dp.repaint(0,0,wid,ht);
		try{
		  if(sock!=null) sock.close();
		  sock=null;
		}catch(IOException e){}
	    }
	}
  */
}
