/*
//
// image.c
//
// Image file functions
//
// Copyright (c) 1995-96 Jim Nelson.  Permission to distribute
// granted by the author.  No warranties are made on the fitness of this
// source code.
// Amiga version - 1997 - Geert Bevin
//
*/

#include "htp.h"

#define IMAGE_TYPE_UNKNOWN              (0)
#define IMAGE_TYPE_GIF                  (1)
#define IMAGE_TYPE_JFIF                 (2)

BOOL OpenImageFile(const char *filename, IMAGEFILE *imageFile)
{
    assert(filename != NULL);
    assert(imageFile != NULL);

    /* open the file to make sure its reachable */
    if((imageFile->file = fopen(filename, "rb")) == NULL)
    {
        DEBUG_PRINT(("could not open image file %s", filename));
        return FALSE;
    }

    /* build the rest of the image file structure */
    if((imageFile->name = DuplicateString(filename)) == NULL)
    {
        DEBUG_PRINT(("could not duplicate filename string"));
        return FALSE;
    }

    /* by default, unknown image type */
    imageFile->imageType = IMAGE_TYPE_UNKNOWN;

    /* is this a GIF file? */
    if(GifFormatFound(imageFile->file) == TRUE)
    {
        imageFile->imageType = IMAGE_TYPE_GIF;
        return TRUE;
    }

    /* is this a JFIF file? */
    if(JpegFormatFound(imageFile->file) == TRUE)
    {
        imageFile->imageType = IMAGE_TYPE_JFIF;
        return TRUE;
    }

    /* return TRUE anyways, because the image file is open (although unsure of */
    /* its format or content) */
    return TRUE;
}   

void CloseImageFile(IMAGEFILE *imageFile)
{
    assert(imageFile != NULL);
    assert(imageFile->name != NULL);
    assert(imageFile->file != NULL);

    FreeMemory(imageFile->name);
    fclose(imageFile->file);

    imageFile->name = NULL;
    imageFile->file = NULL;
}   

BOOL GetImageDimensions(IMAGEFILE *imageFile, WORD *width, WORD *height)
{
    assert(imageFile != NULL);
    assert(width != NULL);
    assert(height != NULL);

    if(imageFile->imageType == IMAGE_TYPE_GIF)
    {
        return GifReadDimensions(imageFile->file, height, width);
    }
    else if(imageFile->imageType == IMAGE_TYPE_JFIF)
    {
        return JpegReadDimensions(imageFile->file, height, width);
    }

    /* unknown file type */
    return FALSE;
}   

