/*
    PNG wrapper 0.1b 1.7.2003
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <png.h>
#include "png_wrap.h"

int read_png(char *name,PNG *png)
{
    FILE    *fp;
    unsigned char hdr[8];
    int n,depth,color,dummy,idx;

    png_structp png_ptr;
    png_infop info_ptr;
    png_bytep *rows;
    png_uint_32 x,y;
    png_colorp pal;

    fp=fopen(name,"rb");
    if(fp==NULL)
        return(-1);
    n=fread(hdr,1,8,fp);
    if(png_sig_cmp(hdr,0,8))
        return(-1);

    png_ptr=png_create_read_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
    info_ptr=png_create_info_struct(png_ptr);
    png_init_io(png_ptr,fp);
    png_set_sig_bytes(png_ptr,8);
    png_read_png(png_ptr,info_ptr,0,NULL);

    png_get_IHDR(png_ptr,info_ptr, &x,&y,&depth,&color, &dummy,&dummy,&dummy);
    png->x=x;
    png->y=y;
    rows=png_get_rows(png_ptr,info_ptr);

    fclose(fp);
    switch(color)
    {
        case PNG_COLOR_TYPE_GRAY: depth=1; png->type=TYPE_GRAY; break;
        case PNG_COLOR_TYPE_PALETTE: depth=1; png->type=TYPE_PALETTE; break;
        case PNG_COLOR_TYPE_RGB: depth=3; png->type=TYPE_RGB; break;
        case PNG_COLOR_TYPE_RGB_ALPHA: depth=4; png->type=TYPE_RGBA; break;
        default: depth=1; png->type=TYPE_UNKNOWN;
    }

    png->data=malloc(x*y*depth);
    if(png->data==NULL)
        return(-1);

    for(n=0;n<y;n++)
        memcpy(&png->data[n*x*depth],rows[n],x*depth);

    if(color==PNG_COLOR_TYPE_PALETTE)
    {
        png_get_PLTE(png_ptr,info_ptr,&pal,&idx);
        for(n=0;n<idx;n++)
        {
            png->pal[n*3]=pal[n].red;
            png->pal[n*3+1]=pal[n].green;
            png->pal[n*3+2]=pal[n].blue;
        }
    }

    png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
    return(0);
}
