/* +-------------------------------------------------------------------+ */
/* | Copyright 1990, 1991, 1993 David Koblas.			       | */
/* | Copyright 1996 Torsten Martinsen.				       | */
/* |   Permission to use, copy, modify, and distribute this software   | */
/* |   and its documentation for any purpose and without fee is hereby | */
/* |   granted, provided that the above copyright notice appear in all | */
/* |   copies and that both that copyright notice and this permission  | */
/* |   notice appear in supporting documentation.  This software is    | */
/* |   provided "as is" without express or implied warranty.	       | */
/* +-------------------------------------------------------------------+ */

/* $Id: readScriptC.c,v 1.5 1996/06/18 10:04:47 torsten Exp $ */

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <dlfcn.h>
#include "image.h"
#include "rwTable.h"

int
TestScriptC(char *file)
{
    FILE *fd = fopen(file, "r");
    char buf[25];
    int ret = 0;

    if (fd == NULL)
	return 0;
    if (fread(buf, 23, 1, fd) != 0) {
        if (strncasecmp(buf, "/* Xpaint-image */", 18) == 0)
	    ret = 1;
    }
    fclose(fd);

    return ret;
}

/* Read, compile, link and execute a C-script to produce an image */

Image *
ReadScriptC(char *file)
{
    Image * image;
    char cmd[512];
    char radix[256];
    void *dl_handle;
    char *ptr;
    Image * (* proc)();

    if (!file || !*file) return NULL;

    ptr = rindex(file, '/');
    if (ptr) ++ptr; else ptr = file;
    strncpy(radix, ptr, 255);
    radix[255] = '\0';
    ptr = rindex(radix, '.');
    if (ptr) *ptr = '\0';

    /* compile C script */
    sprintf(cmd, "gcc -I%s -c %s -o /tmp/%s.o ; "
                 "gcc -shared -Wl,-soname,%s.so /tmp/%s.o -o /tmp/%s.so\n",
	    	 SHAREDIR"/include",
                 file, radix, radix, radix, radix);
    system(cmd);

    sprintf(cmd, "/tmp/%s.so", radix);
    dl_handle = dlopen(cmd, RTLD_LAZY);
    unlink(cmd);
    sprintf(cmd, "/tmp/%s.o", radix);
    unlink(cmd); 
    if (!dl_handle) {
       fprintf(stderr, "Linking of C-script failed !!\n");
       return NULL;
    }
    proc = dlsym(dl_handle, "ImageCreate");
    if (proc) {
       image = proc();
       if (!image)
          fprintf(stderr, "C-script procedure created invalid image !!\n");
    } else {
       image = NULL;
       fprintf(stderr, 
          "C-script didn't include valid ImageCreate() procedure !!\n");
    }
    dlclose(dl_handle);
    return image;
}
