import java.io.*;
import java.util.*;
import java.util.zip.*;

public class GZipThread extends Thread {

  private List pool;
  private static int filesCompressed = 0;

  public GZipThread(List pool) {
    this.pool = pool;
  }
  
  private static synchronized void incrementFilesCompressed() {
    filesCompressed++;
  }

  public void run() {
    
    while (filesCompressed != GZipAllFiles.getNumberOfFilesToBeCompressed()) {
    
      File input = null;
      
      synchronized (pool) {         
        while (pool.isEmpty()) {
          if (filesCompressed == GZipAllFiles.getNumberOfFilesToBeCompressed()) {
            System.out.println("Thread " + this.getName() + " ending");
            return;
          }
          try {
            pool.wait();
          }
          catch (InterruptedException ex) {
            System.out.println("Thread " + this.getName() + " interrupted");
          }
        }

        input = (File) pool.remove(pool.size()-1); 
        incrementFilesCompressed();

      }
      System.out.println("Thread " + this.getName() + " got a file");
    
      // don't compress an already compressed file
      if (!input.getName().endsWith(".gz")) {       
        try {
          InputStream in = new FileInputStream(input);
          in = new BufferedInputStream(in);
          
          File output = new File(input.getParent(), input.getName() + ".gz");
          if (!output.exists()) { // Don't overwrite an existing file
            OutputStream out = new FileOutputStream(output);
            out = new GZIPOutputStream(out);
            out = new BufferedOutputStream(out);
            int b;
//>>>>Added
      try {  
	Thread.sleep(1000,0);
      } catch (InterruptedException e) {
        System.out.println("Thread " + this.getName() + " Added interrupted");
	return;
      }
//<<<<Added  
            while ((b = in.read()) != -1) out.write(b);
            out.flush();
            out.close();
            in.close();
	    System.out.println("Thread " + this.getName() + " GZrd " 
		+ input.getName());
          
	    }
        }
        catch (IOException ex) {
          System.err.println(ex);
        }
        
      } // end if 

    } // end while


    System.out.println("Thread " + this.getName() + " has terminated");
    
  } // end run

} // end ZipThread
