/*
 * $Id: writeMagick.cxx,v 4.0 2003/04/28 14:44:37 hut66au Exp $
 *
 * Imview, the portable image analysis application
 * http://www.cmis.csiro.au/Hugues.Talbot/imview
 * ----------------------------------------------------------
 *
 *  Imview is an attempt to provide an image display application
 *  suitable for professional image analysis. It was started in
 *  1997 and is mostly the result of the efforts of Hugues Talbot,
 *  Image Analysis Project, CSIRO Mathematical and Information
 *  Sciences, with help from others (see the CREDITS files for
 *  more information)
 *
 *  Imview is Copyrighted (C) 1997-2001 by Hugues Talbot and was
 *  supported in parts by the Australian Commonwealth Science and 
 *  Industry Research Organisation. Please see the COPYRIGHT file 
 *  for full details. Imview also includes the contributions of 
 *  many others. Please see the CREDITS file for full details.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *  
 *  This program 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 General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
 * */


/*------------------------------------------------------------------------
 *
 * Write Interface to the Image Magick Library
 *
 * We are only using the convenience functions at this point.
 *
 * Hugues Talbot	31 Jul 2000
 *
 *-----------------------------------------------------------------------*/

#include "imview.hxx"

#ifdef HAVE_MAGICK

#include <stdio.h>
#include <setjmp.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include "../imageIO.hxx"

extern imageIO *IOBlackBox;
// typical simple C solution


#include <magick/api.h>

static ImageInfo     *image_info = 0;
static Image         *magickImage = 0;

extern jmp_buf        magick_jmp; // defined in readMagic.C

// handlers have been set in readMagick.C


int save_magick(const char *fname,         /* input file name */
		const char *format,        /* output format */
		int          numcomp,      /* 1 or 3 at this point */  
		int          nx,           /* dimensions */
		int          ny,           /* dimensions */
		uchar        *pR,          /* buffers */
		uchar        *pG,
		uchar        *pB) 
{
    char                nf[1024];
    uchar               *newbuf = 0, *p;
    int                 i;
    ExceptionInfo        exception;
    volatile int         retval = 0; // volatile so that it doesn't get clobbered by longjmp.

    dbgprintf("save_magick called\n");

    if (setjmp(magick_jmp)) {
	// if we get here, ImageMagick found an error, bailing out
	if (magickImage) {
	    DestroyImage(magickImage);
	    magickImage = 0;
	}
	if (image_info) {
	    DestroyImageInfo(image_info);
	    image_info = 0;
	}
	return 100; 
    }
    
    assert(pR != 0); // Can't work otherwise
    assert((numcomp == 1) || (numcomp == 3));

    // allocate RGB buffer
    if ((newbuf = (uchar *)malloc(nx * ny * 3 * sizeof(uchar))) == 0) {
        errprintf("save_magick: Out of memory condition\n");
        return 50;
    }
    p = newbuf;

    if (numcomp == 3) {
	assert(pG != 0);
	assert(pB != 0);
	// interlace the data (RGBRGBRGB etc)
	for (i = 0 ; i < nx * ny ; i++) {
	    *p++ = pR[i];
	    *p++ = pG[i];
	    *p++ = pB[i];
	}
    } else {
        // with ImageMagick, grey-level images are interpreted as RGB,
        // the output module is `smart' enough to find out that the image
        // is really only grey.
	// pseudo `interlace' the data (RRR,RRR,RRR etc)
	for (i = 0 ; i < nx * ny ; i++) {
	    *p++ = pR[i];
	    *p++ = pR[i];
	    *p++ = pR[i];
	}
    }
    
    // prefix the image name with format
    //snprintf(nf, 1024, "%s:%s", format, fname);
    strcpy(nf, fname);

    // set up the Magick stuff
    
    // initializes the exception information
    GetExceptionInfo(&exception);

    if (image_info == 0)
	image_info = CloneImageInfo((ImageInfo *)0);

    // constitute the image
    magickImage = ConstituteImage (nx, ny, "RGB", CharPixel, newbuf, &exception);

    // actual saving
    if (magickImage != 0) {
	// when saving an image, the filename is attached to the IMAGE
	// structure, not the imageinfo... Makes perfect sense!
	strcpy(magickImage->filename, nf);

	if (!WriteImage(image_info, magickImage)) { // failure
	    errprintf("Image %s failed to write %s\n",
		      fname,
		      (errno) ? strerror(errno):"for some reason");
	    retval = 20;
	}
	// in any case here,
	DestroyImage(magickImage);
	magickImage = 0;
    } else {
#ifdef MAGICK_USES_REASON // God I hate gratuitous API changes
        // for ImageMagick 5.2.7-2 (on RH7.1)
        MagickError(exception.severity,exception.reason,exception.description);
#else
	// for other ImageMagick versions < 5.2.7-2
        MagickError(exception.severity,exception.message,exception.qualifier);
#endif
	retval = 10;
    }

    DestroyImageInfo(image_info);
    image_info = 0;

    free(newbuf);
    
    return retval;
}

#else // HAVE_MAGICK

int save_magick(const char *fname,         /* input file name */
		const char *format,        /* output format */
		int          numcomp,      /* 1 or 3 at this point */  
		int          nx,
		int          ny,       /* dimensions */
		uchar        *pR, 
		uchar        *pG, 
		uchar        *pB) /* buffers */
{
    errprintf("This version of Imview cannot save this images as the ImageMagick library\n"
	      "is not available\n");

    return 1;
}

#endif // HAVE_MAGICK
