/*
//
// png.c
//
// PNG (Portable Network Graphics) support functions
//
// By Rev. Bob, 1999 - derived from gif.c by Jim Nelson
//
// gif.c Copyright (c) 1995-96 Jim Nelson.  Permission to distribute
// granted by the author.  No warranties are made on the fitness of this
// source code.
//
*/

#include "htp.h"

BOOL PngFormatFound(FILE *file)
{
    BYTE header[8];

    /* move to BOF */
    if(fseek(file, 0, SEEK_SET) != 0)
    {
        DEBUG_PRINT(("unable to seek to start of PNG file"));
        return FALSE;
    }

    /* read first eight bytes, looking for PNG header + version info */
    if(fread(header, 1, 8, file) != 8)
    {
        DEBUG_PRINT(("could not read PNG image file header"));
        return FALSE;
    }

    /* is this a PNG file? */
    if(memcmp(header, "\211PNG\r\n\032\n", 8) == 0)
    {
        if(fseek(file, 12, SEEK_SET) != 0)
        {
            DEBUG_PRINT(("unable to seek to IHDR block of PNG file"));
            return FALSE;
        }

        if(fread(header, 1, 4, file) != 4)
        {
            DEBUG_PRINT(("could not read PNG image IHDR signature"));
            return FALSE;
        }

        if(memcmp(header, "IHDR", 4) == 0)
        {
            /* PNG signature and IHDR block found, must be good */
            return TRUE;
        }
    }

    /* not a PNG file */
    return FALSE;
}

/* Modify parms here and in png.h - must use 4-byte integers! */
BOOL PngReadDimensions(FILE *file, DWORD *height, DWORD *width)
{

/* PNG uses MSB LSB (B3 B2 B1 B0) notation - most significant first */

    BYTE buff[8];

    /* move to the image size position (+16) in the file header */
    if(fseek(file, 16, SEEK_SET) != 0)
    {
        DEBUG_PRINT(("unable to seek to start of PNG file"));
        return FALSE;
    }

    /* read the width and height, byte by byte */
    /* this gets around machine endian problems while retaining the */
    /* fact that PNG uses MSB LSB (big-endian) notation */
    if(fread(buff, 1, 8, file) != 8)
    {
        return FALSE;
    }
    *width  = MAKE_DWORD(buff[0], buff[1], buff[2], buff[3]);
    *height = MAKE_DWORD(buff[4], buff[5], buff[6], buff[7]);

    return TRUE;
}

