
#include <getopt.h>
#include "jopen.h"
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
#define JOGDIR "/usr/local/jog07"
#define JOGPS "Jog.ps"

// TODO protect against infinite recursion
int
include(char *fich, char *defdir, char *defext) {
   FILE* fd;
   char s[STRSIZE];
   char s0[STRSIZE];
   long n;

   if ( strncmp(fich,"-",STRSIZE)==0 ) {
     fd = stdin;
   } else {
     fprintf(stdout, "%s Including: %s\n", "%", fich);
     if ( (fd = jopen(fich, defdir, defext)) == NULL ) { return 0; };
   }
   n = 0;
   while ( fgets(s, STRSIZE, fd) != NULL ) {
      n++;
      if ( strchr(s, '#') == s ) {
         sscanf(s,"#include %s",s0);
         if ( !inclure(s0,defdir,defext) ) { printf("%s Could not include %s\n","%",s0); };
      } else if ( strchr(s, '!') == s ) {
         fflush(stdout);
         system(&s[1]);
      } else if (strchr(s, '?') == s) {
         // a trace postscript function ? must be defined
         // build the message string with the jog file line number
         fprintf(stdout,"(===%s===%ld===) ?\n",fich,n);
      } else {
         fprintf(stdout, "%s", s);
      }
   }
   return 1;
}

void
head(char *bb) {
  printf("%s\n","%!PS-Adobe-3.0 EPSF-3.0");
  printf("%s %s\n","%%BoundingBox: ",bb);
  printf("%s\n","%%Creator: Jog07 - J.Roux / IPG Paris");
  printf("%s\n","%%EndComments");
}

void
setup() {
  printf("%s\n","%%BeginSetup");
  printf("%s\n","mark");
  printf("%s\n","%%EndSetup");
  printf("%s\n","/jog 400 dict def"); // TODO evaluate this number
  printf("%s\n","jog begin");
  printf("%s\n","%%BeginJog");
}

void
epilogue() {
  printf("%s\n","%%EndJog");
  printf("%s\n","pop");
  printf("%s\n","end % jog");
  printf("%s\n","showpage");
  printf("%s\n","%%eof");
}

int
main(int argc, char* argv[])
{
   head("0 0 595 842"); // A4 portrait bounding box
   if ( !include(JOGPS,JOGDIR,".ps") ) { return EXIT_FAILURE; }
   setup();
   if ( !include("-",JOGDIR,".ps") ) { return EXIT_FAILURE; }
   epilogue();
   return EXIT_SUCCESS;
}
