/* load.c - load image from file
 * 
 *  Raster graphics library
 * 
 *  Copyright (c) 1997 Alfredo K. Kojima
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *  
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *  
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */


#include <X11/Xlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>

#ifdef PNG
#include <png.h>
#endif

#include "wraster.h"

#ifndef XPM
# ifndef TIFF
#  ifndef PNG  
#   error At least one image format must be enabled.
#  endif
# endif
#endif


#define IM_UNKNOWN	0
#define IM_XPM		1
#define IM_TIFF 	2
#define IM_PNG		3


static int identFile(char *path);


#ifdef XPM
extern RImage *RLoadXPM(RContext *context, char *file, int index);
#endif
#ifdef TIFF
extern RImage *RLoadTIFF(RContext *context, char *file, int index);
#endif
#ifdef PNG
extern RImage *RLoadPNG(RContext *context, char *file, int index);
#endif

RImage*
RLoadImage(RContext *context, char *file, int index)
{
    RErrorString[0] = 0;
    switch (identFile(file)) {
     case IM_UNKNOWN:
	sprintf(RErrorString, "unknown image format in file \"%s\"", file);
	return NULL;

#ifdef XPM
     case IM_XPM:
	return RLoadXPM(context, file, index);
#endif /* TIFF */
	
#ifdef TIFF
     case IM_TIFF:
	return RLoadTIFF(context, file, index);
#endif /* TIFF */

#ifdef PNG
     case IM_PNG:
	return RLoadPNG(context, file, index);
#endif /* PNG */

     default:
	sprintf(RErrorString, "unsupported image format in file \"%s\"", file);
	return NULL;
    }
}





static int
identFile(char *path)
{
    int fd;
    unsigned char buffer[32];
    int i;

    if (!path) 
      return IM_UNKNOWN;

    fd = open(path, O_RDONLY);
    if (fd < 0)
      return IM_UNKNOWN;
    if (read(fd, buffer, 32)<1) {
	close(fd);
	return IM_UNKNOWN;
    }
    close(fd);
    /* check for XPM */
    if (strncmp(buffer, "/* XPM */", 9)==0) 
      return IM_XPM;
    /* check for TIFF */
    if ((buffer[0]=='I' && buffer[1]=='I' && buffer[2]=='*' && buffer[3]==0)
	||(buffer[0]=='M' && buffer[1]=='M' && buffer[2]==0 && buffer[3]=='*'))
      return IM_TIFF;

#ifdef PNG
    /* check for PNG */
    if (png_check_sig(buffer, 8))
      return IM_PNG;
#endif

    return IM_UNKNOWN;
}



