import java.io.*;


/* This class is used to concurrently copy between two pairs of input
   and output streams.  It creates a thread to handle the first pair,
   handles the second pair directly, and waits for the thread to complete.
 */
public class Copy2Files implements Runnable {

   private static boolean verbose = false;
   private boolean abort1When2Done = false;

   private DataInputStream in1;
   private DataOutputStream out1;
   private DataInputStream in2;
   private DataOutputStream out2;
   private int count1;
   private int count2;

   public Copy2Files(DataInputStream in1, DataOutputStream out1,
                     DataInputStream in2, DataOutputStream out2) {
      this.in1 = in1;
      this.out1 = out1;
      this.in2 = in2;
      this.out2 = out2;
      count1 = 0;
      count2 = 0;
   }

   public static void setVerbose(boolean f) {
      verbose = f;
   }

   public void setAbort1When2Done(boolean f) {
      abort1When2Done = f;
   }

   public int getCount1() {
      return count1;
   }

   public int getCount2() {
      return count2;
   }

   public void run() {
    CopyFile copyFile;
    if (verbose)
       System.out.println("Copy2Files started to read from first input");
    copyFile = new CopyFile(in1, out1);
    count1 = copyFile.copyAll();
    if (verbose)
    System.out.println("Copy2Files done with first transfer, bytes: " +
                       count1);
   }

   public void copyAll() {
      CopyFile copyFile;
      Thread thread;
      thread = new Thread(this);
      thread.start();
      copyFile = new CopyFile(in2,out2);
      count2 = copyFile.copyAll();
      if (abort1When2Done) {
         if (verbose)
            System.out.println("second transfer done, terminating first");
         try {
            in1.close();
         } catch (IOException e) {}
      }
      try {
         thread.join();
      } catch (InterruptedException e) {
         if (verbose)
            System.out.println("Cannot join thread doing first copy");
      }
   }

}
