#ifdef HAVE_PGF

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "image.h"
#include "rwTable.h"

extern char * PNM_alpha_separator;

extern FILE * openTempFile(char **np);
extern void removeTempFile(void);
extern Image * ReadPNM(char *file);
extern int WriteBinaryPNM(char *file, Image *image);
extern Image * ReadPNG(char *file);
extern int WritePNGn(char *file, Image *image);

static char * pgf_exec = NULL;

void TestPGFRuntime()
{
    struct stat sbuf;
    static char *pgf_execs[4] = {
        "/usr/bin/pgf2pnm",
        "/usr/local/bin/pgf2pnm",
        "/usr/bin/pgf",
        "/usr/local/bin/pgf",
    };
    int i;

    i = 0;
    while (i < 4) {
        if (stat(pgf_execs[i], &sbuf)>=0 && (sbuf.st_mode & S_IFREG)) {
	    pgf_exec = pgf_execs[i];
            printf("Found PGF executable : %s\n",pgf_exec);  
            return;
	}
        ++i;
    }
    pgf_exec = "";
}

int
TestPGF(char *file)
{
    unsigned char buf[4];
    FILE *fd; 
    int ret = 0;

    if (pgf_exec && !*pgf_exec)
        return ret;
   
    fd = fopen(file, "r");
    if (fd == NULL)
	return ret;

    if (3 == fread(buf, sizeof(char), 3, fd)) {
        if (buf[0] == 0x50 && buf[1] == 0x47 && buf[2] == 0x46)
	    ret = 1;
    }
    fclose(fd);
   
    if (pgf_exec || !ret)
        return ret;

    TestPGFRuntime();
    if (!*pgf_exec)
        ret = 0;
    return ret;
}

Image *
ReadPGF(char *file_name)
{
    char cmd[512];
    char name[256];
    char *tmp;
    Image *image;
    FILE *fp;
    fp = openTempFile(&tmp);
    if (!fp) return NULL;
    fclose(fp);

    if (!pgf_exec)
        TestPGFRuntime();
    if (!*pgf_exec)
        return NULL;

    if (strstr(pgf_exec, "pgf2pnm")) {
        sprintf(name, "%s.pnm", tmp);
        sprintf(cmd, "%s -t %s > %s", pgf_exec, file_name, name);
        system(cmd);
        image = ReadPNM(name);
    } else {
        sprintf(name, "%s.png", tmp);
        sprintf(cmd, "%s -d %s %s", pgf_exec, file_name, name);
        system(cmd);
        image = ReadPNG(name);
    }

    unlink(name);
    removeTempFile();
    return image;
}

int 
WritePGF(char *file_name, Image * outImage)
{
    char cmd[512];
    char name[256];
    char *tmp;
    FILE *fp;
    int res = 1;

    if (!pgf_exec)
        TestPGFRuntime();
    if (!*pgf_exec)
        return res;
    fp = openTempFile(&tmp);
    if (!fp) return res;
    fclose(fp);

    if (strstr(pgf_exec, "pgf2pnm")) {
        sprintf(name, "%s.pnm", tmp);
        PNM_alpha_separator = "";
        res = WriteBinaryPNM(name, outImage);
        PNM_alpha_separator = "\n";       
        sprintf(cmd, "%s -t -e %s < %s", pgf_exec, file_name, name);
    } else {
        sprintf(name, "%s.png", tmp);
        res = WritePNGn(name, outImage);
        sprintf(cmd, "%s -e %s %s", pgf_exec, name, file_name);
    }

    system(cmd);
    unlink(name);
    removeTempFile();
    return res;
}

#endif

