//import java.applet.Applet;

import java.awt.*;
import java.util.*;

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

/** Open a named ".gif" file and create an Image,
 * then write another ".gif" file of cropped Image,
 * per X Y W H args.
 * <IMG SRC="/cgi-bin/counter">
 * Not terribly user-friendly,
 * but it works w/out putting the image on screen. */

public class Cropper {

    public static void main (String []argv) {

/* Wait until the Image is loaded -- or fails to */

        System.out.println ("Loading "+argv [0]);

        Image theImage = Toolkit.getDefaultToolkit ().getImage(argv [0]);

        Component comp = new Canvas ();

        MediaTracker tracker = new MediaTracker (comp);
        try {
            tracker.addImage (theImage, 0);
            tracker.waitForID (0);
            if (tracker.isErrorID (0)) { System.out.println ("FAILED "+theImage); return; }
        }
        catch (Exception e) {
	    System.out.println ("FAILED "+e);
	    e.printStackTrace ();
	    System.exit (0);
	}

	int imgW = theImage.getWidth (comp);
	int imgH = theImage.getHeight (comp);

        System.out.println ("Loaded "+argv [0]+" W="+imgW+" H="+imgH);

        PrintStream fos = open_for_write (argv [1]);

/* The part to Crop */

        int x = Integer.parseInt (argv [2]),
	    y = Integer.parseInt (argv [3]),
	    w = Integer.parseInt (argv [4]),
	    h = Integer.parseInt (argv [5]);

/* Neg x means in from right instead of left,
 * Neg y means in from bottom instead of top */

        if (x < 0) x = imgW + x;
        if (y < 0) y = imgH + y;

        System.out.println ("Writing "+argv [1]+" "+x+" "+y+" "+w+" "+h);

        if (null != fos) {
            try { new GifEncoder (theImage, (OutputStream)fos).encode (x, y, w, h); }
            catch (Exception exc) { exc.printStackTrace(); }
            fos.close ();
        }

        System.out.println ("Done");

	System.exit (0);
    }

/* Open a writable file as a PrintStream,
 * possibly replacing an existing file of the same name.
 * We do not test for that!
 * @return -- the writable PrintStream,
 * or null if unable to open the file.
 * <B>Note:</B>Caller is responsible to close the PrintStream. */

    static PrintStream open_for_write (String fname) {

        try {
            return new PrintStream
              (new FileOutputStream 
                (new File (fname)));
        }
        catch (Exception exc) { exc.printStackTrace(); return null; }
    }

}
/* <IMG SRC="/cgi-bin/counter">*/
