
/* FileDemo.java
   
  1996(c) burt rosenberg all rights reserved
  Nov 11, 1996
  changed name Nov 13.

*/

import java.awt.* ;
import java.io.* ;
import java.applet.Applet ;

public class FileDemo {
   public static void main(String argv[]) {
      Applet theAp = new MyApplet() ;
      Frame myFrame = new MyFrame("FileDemo", theAp, 230, 150 ) ;
   } 
}

class MyFrame extends Frame {
   public MyFrame( String title, Applet theAp, int w, int h ) {
      super(title) ;
      add("Center", theAp) ;
      resize(w,h) ;
      show() ;
      theAp.init() ;
      theAp.start() ;
   }
}

class MyApplet extends Applet 
implements Runnable {
   
   Button goButton = new Button("Go") ;
   Button quitButton = new Button("Quit")  ;
   TextField fileNameField = new TextField(15) ;
   Label fileNameLabel = new Label("File name:") ;
   Label statusLabel = new Label("Status:") ;
   Label statusField = new Label("Waiting") ;

   // String homeDir = "/Hard Disk/Desktop Folder/Burt's Junk/Huffman/" ;
   String homeDir = "./" ;
   
   Thread runThread = null ;
   int runCommand = IDLE ;
   static final int IDLE = 0 ;
   static final int GO = 1 ;
   static final int QUIT = 2 ;
    
   public void init() {
      setLayout( new GridLayout(3,2) ) ;
      add( fileNameLabel ) ;
      add( fileNameField) ;
      add( goButton ) ;
      add( quitButton ) ;
      add( statusLabel ) ;
      add( statusField ) ;
      validate() ;      
   }
   
   public synchronized boolean action( Event e, Object arg ) {
     
      if (e.target==goButton ) {
      
         if ( runThread == null ) {
            runCommand = GO ;
            runThread = new Thread(this) ;
            runThread.start() ;
         }
         return true ;
      }
      
      if ( e.target==quitButton) {
         // I don't know how to quit!
         return true ;
      }
      
      return false ;    
   }
   
   public void run() {
      
      if ( runCommand != GO ) {
         runThread = null ;
         return ;
      }
      // else copy
          
      String infile = fileNameField.getText() ;
      String outfile = infile + ".out" ;
      statusField.setText("Encoding "+infile) ;
      
      try {  
         int c ;
         FileInputStream fileIn = new FileInputStream( homeDir + infile ) ;
         FileOutputStream fileOut = new FileOutputStream( homeDir + outfile ) ;
         while ( (c = fileIn.read()) != -1 ) fileOut.write(c) ;
         fileIn.close() ;
         fileOut.close() ;
      
      } catch ( FileNotFoundException except ) {
         statusField.setText("File not found.") ;
         
      } catch ( IOException except ) {
         statusField.setText("IO Exception") ;
      }
      
      runThread = null ;
   } 
   
}
