import java.util.zip.*;
import java.io.*;

/**
 * A simple compression tool to show more I/O examples, and more complex exception things.
 *
 * @author JJ Johns
 **/

public class gzip {

	public static void main(String[] args) {

		if (args.length < 2) {
			System.out.println("USAGE: java gzip [-c|-d] file.gz [if -c, filename to compress]");
			System.exit(0);
		}


		// compress a file
		if (args[0].equals("-c")) {

			GZIPOutputStream gos = null;
			FileInputStream fis = null;

			try {

				// instantiate the wrappers.
				gos = new GZIPOutputStream( new FileOutputStream( args[1] ));
				fis = new FileInputStream( args[2] );

				byte[] buffer = new byte[1024];
				int numread = 0;

				// read through the file and write it to the gzip file
				while ((numread = fis.read(buffer)) != -1) {
					gos.write(buffer,0, numread);
				}

			}
			catch (IOException ioe) {
				ioe.printStackTrace();
			}
			catch (ArrayIndexOutOfBoundsException aiob) {
				System.out.println("Improper Arguments: java -c filename.gz file");
			}
			finally {

				// ALWAYS close your streams
				try {
					fis.close();
				}
				catch (Exception ioe) { }

				try {
					gos.close();
				}
				catch (Exception ioe2) { }

			}
		}

		// extract a file
		if (args[0].equals("-d")) {

			GZIPInputStream gis = null;
			FileOutputStream fos = null;

			try {

				gis = new GZIPInputStream( new FileInputStream(args[1]) );
				fos = new FileOutputStream( args[1].substring(0, args[1].lastIndexOf(".gz")));

				byte[] buffer = new byte[1024];
				int numread = 0;

				while ((numread = gis.read(buffer)) != -1) {
					fos.write(buffer,0, numread);
				}

			}
			catch (IOException ioe) {
				ioe.printStackTrace();

			}
			catch (ArrayIndexOutOfBoundsException aiob) {
				System.out.println("Improper Arguments: java -d filename.gz");
			}
			finally {

				// ALWAYS close your files.
				try {
					gis.close();
				}
				catch (Exception ioe) { }

				try {
					fos.close();
				}
				catch (Exception ioe2) { }

			}

		}

	}

}