/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.mimetypes.image;

import java.awt.*;
import java.io.DataInputStream;
import java.io.IOException;

/**
 * Implements the {@link ImageSizer} interface for GIF images
 *
 * @author <a href="mailto:sfreidin@arsdigita.com">Stanislav Freidin</a>
 * @version $Id: //core-platform/dev/src/com/arsdigita/mimetypes/image/GIFImageSizer.java#5 $
 */
public class GIFImageSizer extends ImageSizer {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/mimetypes/image/GIFImageSizer.java#5 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    private static final String GIF_MARKER_87 = "GIF87a";
    private static final String GIF_MARKER_89 = "GIF89a";

    protected GIFImageSizer() { super(); }

    /**
     * Read the input stream, determine the size of the image,
     * and return it
     *
     * @param in The InputStream to read
     * @return The size of the image, or null on failure
     */
    public Dimension computeSize(DataInputStream in) throws IOException {
        byte[] data = new byte[10];

        if(in.read(data) < 10) {
            return null;
        }

        String head = new String(data, 0, 6);

        if(GIF_MARKER_87.equals(head) || GIF_MARKER_89.equals(head)) {

            // We have to manually mask out bits since Java has no unsigned primitive
            short width = ImageSizer.toShort(data[7], data[6]);
            short height = ImageSizer.toShort(data[9], data[8]);
            return new Dimension(width, height);
        } else {
            return null;
        }
    }

}
