#include <vfork.h>
#include <strstream.h>

#include "UcharDiscreteImage.h"
#include "display.h"


#define IMAGE_DISPLAY_ENV_VAR "IMAGE_DISPLAY"
#define DEFAULT_IMAGE_DISPLAY "xv"

#define SEPARATOR_STRING " "
#define CLEANUP_STRING "; rm -f "

static char filename[]= "/tmp/IA_display_XXXXXX";

// display
//
// Forks a process to display a UcharDiscreteImage.
//
// Returns: the uid of the process      if the fork succeeded
//          -1                          if the fork failed
//
// display writes the image to a temp file in pgm format.
//
// User can set environment variable whose name is given by define constant
//        IMAGE_DISPLAY_ENV_VAR to specify what image display application
//        is to be used to display the pgm image.
//
// Default display application name is given by DEFINE constant
//        DEFAULT_IMAGE_DISPLAY
//

pid_t display(IA_UcharDiscreteImage img)
{
    char *display_program;
    pid_t pid;

    // always use a fresh tmp filename
    strcpy(filename + strlen(filename) - 6, "XXXXXX");

    // Get the image display program filename
    display_program = getenv(IMAGE_DISPLAY_ENV_VAR);
    if (!display_program) {
	display_program = DEFAULT_IMAGE_DISPLAY;
    }

    // Fork and exec the display program
    if ((pid=fork())==0){
	// pid is zero, so this is the child

	// Write the image to a tmp file with a unique pid
	img.write_PGM(mktemp(filename));

	strstream buffer;
	buffer << display_program << SEPARATOR_STRING << filename
	    << CLEANUP_STRING << filename ;

	system(buffer.str());
	abort();
    }
    return pid;
}



