
package tmcm.xModels;

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


class ProgramLoader extends Thread {

   String directory, fileName;
   URL url;
   ProgramPanel owner;
   int ID;

   ProgramLoader(URL url, ProgramPanel owner, int ID) {
      this.owner = owner;
      this.url = url;
      this.ID = ID;
      start();
   }
   
   ProgramLoader(String directory, String fileName, ProgramPanel owner, int ID) {
      this.owner = owner;
      this.directory = directory;
      this.fileName = fileName;
      this.ID = ID;
      start();
   }
   
   
   public void run() { // load from input stream in
      try { setPriority(getPriority() - 1); }
      catch (RuntimeException e) { }
      String systemEOL = ProgramPanel.systemEOL;
      String text = null;
      boolean success = false;
      InputStream in = null;
      try {
         int charCt = 0;
         int badCharCt = 0;
         if (url != null)
            in = url.openConnection().getInputStream();
         else
            in = new FileInputStream(new File(directory,fileName));
         StringBuffer str = new StringBuffer(10000);
         int ch = in.read();
         int ct = 0;
         while (ch >= 0 && charCt < 20000) {
            charCt++;
            ct++;
            if (ct == 500) {
               try { Thread.sleep(20); }
               catch (InterruptedException e) { }
               ct = 0;
            }
            char c = (char)ch;
            if (c < ' ' && !Character.isSpace(c))
               badCharCt++;
            else if (c == '\n') {
               str.append(systemEOL);
            }
            else if (c == '\r') {
               str.append(systemEOL);
               ch = in.read();
               if (ch == -1)
                  break;
               if (ch == '\r')
                  str.append(systemEOL);
               else if (ch != (int)'\n')
                  str.append((char)ch);
            }
            else
               str.append(c);
            if (badCharCt > 100 && badCharCt > (charCt / 100))
               throw new IOException("  The data does not seem to be text!  Input aborted.");
            ch = in.read();
         }
         if (charCt >= 20000)
            str.append(systemEOL + systemEOL + "Input terminated after reading 20000 characters!" + systemEOL);
         text = str.toString();
         success = true;
      }
      catch (IOException e) {
         text = systemEOL + "LOAD FAILED; INPUT ERROR:  " + e.getMessage() + systemEOL;
      }
      catch (SecurityException e) {
         text = systemEOL + "LOAD FAILED; SECURITY ERROR:  " + e.getMessage() + systemEOL;
      }
      catch (Exception e) {
         text = systemEOL + "LOAD FAILED; ERROR:  " + e.toString() + systemEOL;
      }
      finally {
         owner.doneLoading(ID,success,text);
         if (in != null) {
            try { in.close(); }
            catch (IOException e) { }
         }
      }
   }
  
     
}

