/*
 * tkImgFmtPPM.c --
 *
 *	A photo image file handler for PPM (Portable PixMap) files.
 *
 * Copyright (c) 1994 The Australian National University.
 * Copyright (c) 1994-1995 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * Author: Paul Mackerras (paulus@cs.anu.edu.au),
 *	   Department of Computer Science,
 *	   Australian National University.
 */

static char sccsid[] = "@(#) tkImgFmtPPM.c 1.4 95/01/03 17:06:32";

#include "tkInt.h"
#include "tkPort.h"

/*
 * The maximum amount of memory to allocate for data read from the
 * file.  If we need more than this, we do it in pieces.
 */

#define MAX_MEMORY	10000		/* don't allocate > 10KB */

/*
 * The format record for the PPM file format:
 */

static int		FileMatchPPM _ANSI_ARGS_((FILE *f, char *fileName,
			    char *formatString, int *widthPtr,
			    int *heightPtr));
static int		FileReadPPM  _ANSI_ARGS_((Tcl_Interp *interp,
			    FILE *f, char *fileName, char *formatString,
			    Tk_PhotoHandle imageHandle, int destX, int destY,
			    int width, int height, int srcX, int srcY));
static int		FileWritePPM _ANSI_ARGS_((Tcl_Interp *interp,
			    char *fileName, char *formatString,
			    Tk_PhotoImageBlock *blockPtr));

Tk_PhotoImageFormat tkImgFmtPPM = {
    "PPM",			/* name */
    FileMatchPPM,		/* fileMatchProc */
    NULL,			/* stringMatchProc */
    FileReadPPM,		/* fileReadProc */
    NULL,			/* stringReadProc */
    FileWritePPM,		/* fileWriteProc */
    NULL,			/* stringWriteProc */
};

/*
 * Prototypes for local procedures defined in this file:
 */

static char *		GetString _ANSI_ARGS_((char *line, int length,
			    FILE *f));
static int		ReadPPMHeader _ANSI_ARGS_((FILE *f, int *widthPtr,
			    int *heightPtr));

/*
 *----------------------------------------------------------------------
 *
 * FileMatchPPM --
 *
 *	This procedure is invoked by the photo image type to see if
 *	a file contains image data in PPM format.
 *
 * Results:
 *	The return value is 1 if the first characters in file "f" look
 *	like PPM data, and 0 otherwise..
 *
 * Side effects:
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
FileMatchPPM(f, fileName, formatString, widthPtr, heightPtr)
    FILE *f;			/* The image file, open for reading. */
    char *fileName;		/* The name of the image file. */
    char *formatString;		/* User-specified format string, or NULL. */
    int *widthPtr, *heightPtr;	/* The dimensions of the image are
				 * returned here if the file is a valid
				 * raw PPM file. */
{
    return ReadPPMHeader(f, widthPtr, heightPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * FileReadPPM --
 *
 *	This procedure is called by the photo image type to read
 *	PPM format data from a file and write it into a given
 *	photo image.
 *
 * Results:
 *	A standard TCL completion code.  If TCL_ERROR is returned
 *	then an error message is left in interp->result.
 *
 * Side effects:
 *	The access position in file f is changed, and new data is
 *	added to the image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
FileReadPPM(interp, f, fileName, formatString, imageHandle, destX, destY,
	width, height, srcX, srcY)
    Tcl_Interp *interp;		/* Interpreter to use for reporting errors. */
    FILE *f;			/* The image file, open for reading. */
    char *fileName;		/* The name of the image file. */
    char *formatString;		/* User-specified format string, or NULL. */
    Tk_PhotoHandle imageHandle;	/* The photo image to write into. */
    int destX, destY;		/* Coordinates of top-left pixel in
				 * photo image to be written to. */
    int width, height;		/* Dimensions of block of photo image to
				 * be written to. */
    int srcX, srcY;		/* Coordinates of top-left pixel to be used
				 * in image being read. */
{
    int fileWidth, fileHeight;
    int nLines, nBytes, h;
    unsigned char *pixelPtr;
    Tk_PhotoImageBlock block;

    if (!ReadPPMHeader(f, &fileWidth, &fileHeight)) {
	Tcl_AppendResult(interp, "couldn't read raw PPM header from file \"",
		fileName, "\"", NULL);
	return TCL_ERROR;
    }
    if ((fileWidth <= 0) || (fileHeight <= 0)) {
	Tcl_AppendResult(interp, "PPM image file \"", fileName,
		"\" has dimension(s) <= 0", (char *) NULL);
	return TCL_ERROR;
    }

    if ((srcX + width) > fileWidth) {
	width = fileWidth - srcX;
    }
    if ((srcY + height) > fileHeight) {
	height = fileHeight - srcY;
    }
    if ((width <= 0) || (height <= 0)
	|| (srcX >= fileWidth) || (srcY >= fileHeight)) {
	return TCL_OK;
    }

    block.width = width;
    block.pixelSize = 3;
    block.pitch = 3 * fileWidth;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;

    Tk_PhotoExpand(imageHandle, destX + width, destY + height);

    if (srcY > 0) {
	fseek(f, (long) (srcY * block.pitch), SEEK_CUR);
    }

    nLines = (MAX_MEMORY + block.pitch - 1) / block.pitch;
    if (nLines > height) {
	nLines = height;
    }
    if (nLines <= 0) {
	nLines = 1;
    }
    nBytes = nLines * block.pitch;
    pixelPtr = (unsigned char *) ckalloc((unsigned) nBytes);
    block.pixelPtr = pixelPtr + srcX * 3;

    for (h = height; h > 0; h -= nLines) {
	if (nLines > h) {
	    nLines = h;
	    nBytes = nLines * block.pitch;
	}
	if (fread(pixelPtr, 1, (unsigned) nBytes, f) != nBytes ){
	    Tcl_AppendResult(interp, "error reading PPM image file \"",
		    fileName, "\": ",
		    feof(f) ? "not enough data" : Tcl_PosixError(interp),
		    (char *) NULL);
	    ckfree((char *) pixelPtr);
	    return TCL_ERROR;
	}
	block.height = nLines;
	Tk_PhotoPutBlock(imageHandle, &block, destX, destY, width, nLines);
	destY += nLines;
    }

    ckfree((char *) pixelPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FileWritePPM --
 *
 *	This procedure is invoked to write image data to a file in PPM
 *	format.
 *
 * Results:
 *	A standard TCL completion code.  If TCL_ERROR is returned
 *	then an error message is left in interp->result.
 *
 * Side effects:
 *	Data is written to the file given by "fileName".
 *
 *----------------------------------------------------------------------
 */

static int
FileWritePPM(interp, fileName, formatString, blockPtr)
    Tcl_Interp *interp;
    char *fileName;
    char *formatString;
    Tk_PhotoImageBlock *blockPtr;
{
    FILE *f;
    int w, h;
    int greenOffset, blueOffset, nBytes;
    unsigned char *pixelPtr, *pixLinePtr;

    if ((f = fopen(fileName, "wb")) == NULL) {
	Tcl_AppendResult(interp, fileName, ": ", Tcl_PosixError(interp),
		(char *)NULL);
	return TCL_ERROR;
    }

    fprintf(f, "P6\n%d %d\n255\n", blockPtr->width, blockPtr->height);

    pixLinePtr = blockPtr->pixelPtr + blockPtr->offset[0];
    greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
    blueOffset = blockPtr->offset[2] - blockPtr->offset[0];

    if ((greenOffset == 1) && (blueOffset == 2) && (blockPtr->pixelSize == 3)
	    && (blockPtr->pitch == (blockPtr->width * 3))) {
	nBytes = blockPtr->height * blockPtr->pitch;
	if (fwrite(pixLinePtr, 1, (unsigned) nBytes, f) != nBytes) {
	    goto writeerror;
	}
    } else {
	for (h = blockPtr->height; h > 0; h--) {
	    pixelPtr = pixLinePtr;
	    for (w = blockPtr->width; w > 0; w--) {
		if ((putc(pixelPtr[0], f) == EOF)
			|| (putc(pixelPtr[greenOffset], f) == EOF)
			|| (putc(pixelPtr[blueOffset], f) == EOF)) {
		    goto writeerror;
		}
		pixelPtr += blockPtr->pixelSize;
	    }
	    pixLinePtr += blockPtr->pitch;
	}
    }

    if (fclose(f) == 0) {
	return TCL_OK;
    }
    f = NULL;

 writeerror:
    Tcl_AppendResult(interp, "error writing \"", fileName, "\": ",
	    Tcl_PosixError(interp), (char *) NULL);
    if (f != NULL) {
	fclose(f);
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * GetString --
 *
 *	This procedure reads the next non-comment line from a PPM file,
 *	stripping out comment lines along the way.
 *
 * Results:
 *	Data from the next line (up to "len" bytes or one whole line,
 *	whichever is less) is placed at *line.  The return value is
 *	line.
 *
 * Side effects:
 *	The access position in f is advanced.
 *
 *----------------------------------------------------------------------
 */

static char *
GetString(line, len, f)
    char *line;			/* Buffer to receive the line read in. */
    int len;			/* Amount of space available at *line. */
    FILE *f;			/* File to read from. */
{
    int incomment = 0;

    for(;;){
	if (fgets(line, len, f) == NULL) {
	    return NULL;
	}
	if (!incomment && line[0] != '#') {
	    break;
	}
	incomment = line[strlen(line) - 1] != '\n';
    }
    return line;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadPPMHeader --
 *
 *	This procedure reads the PPM header from the beginning of a
 *	PPM file and returns the dimensions of the image.
 *
 * Results:
 *	The return value is 1 if file "f" appears to start with
 *	a valid PPM header, 0 otherwise.  If the header is valid,
 *	then *widthPtr and *heightPtr are modified to hold the
 *	dimensions of the image.
 *
 * Side effects:
 *	The access position in f advances.
 *
 *----------------------------------------------------------------------
 */

static int
ReadPPMHeader(f, widthPtr, heightPtr)
    FILE *f;			/* Image file to read the header from */
    int *widthPtr, *heightPtr;	/* The dimensions of the image are
				 * returned here. */
{
    int maxPixel;
    char line[64];

    return (GetString(line, sizeof(line), f) != NULL)
	    && (strcmp(line, "P6\n") == 0)
	    && (GetString(line, sizeof(line), f) != NULL)
	    && (sscanf(line, "%d%d", widthPtr, heightPtr) == 2)
	    && (GetString(line, sizeof(line), f) != NULL)
	    && (sscanf(line, "%d", &maxPixel) == 1)
	    && (maxPixel == 255);
}
