/* This file is part of the hacked version of the ghostview package */
/* which is distributed under the terms of the gnu license. The */
/* modification referred to above is by Tanmoy Bhattacharya, */
/* <tanmoy@qcd.lanl.gov> on Nov 17, 1994. Neither the modification, */
/* nor the original program provides any warranty. */
#include <string.h>
#include <ctype.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include "pdf.h"
#ifdef NOMEMMOVE
#define memmove memcpy
#endif
static struct tagtable {
  double xmin, ymin, xmax, ymax;
  struct tagtable *next;
  int page;
} *tagstart=NULL, *tagcurrent=NULL;
void pdf_process(char buf[])
{char *pointer=buf;
 while (*pointer&&(pointer=strstr(pointer,"\n%%[pdfinfo:\n"))) {
   char *rectptr=strstr(pointer,"/Rect ");
   char *pageptr=strstr(pointer,"/Page ");
   char *endptr=strstr(pointer,"%%]\n");
   char *lnkptr=strstr(pointer,"\n[/LNK ");
   if (lnkptr && lnkptr<endptr && rectptr) {
     rectptr += strlen("/Rect ");
     while (isspace(*rectptr)) rectptr++;

     if (*rectptr++ == '[') {
       if(!tagstart) {
	 tagcurrent = tagstart = malloc(sizeof(struct tagtable));
	 if(!tagcurrent) {
           strcat(buf,"\nGhostview: Unable to malloc!\n");
	   } }
       else if (tagcurrent) {
	 tagcurrent->next = malloc(sizeof(struct tagtable));
	 tagcurrent = tagcurrent->next;}

       if(!tagcurrent) {
	 strcat(buf,"\nGhostview: Something seriously wrong!\n");
	 }
       else {
	 tagcurrent->next = NULL;
	 if (pageptr) {
	   pageptr += strlen("/Page ");
	   if(sscanf(pageptr,"%d",&tagcurrent->page) != 1) {
	     strcat(buf,"\nGhostview: Incorrect page specification\n");
	     tagcurrent->page = -1;
	   }
	   else tagcurrent->page--;
	 }
	 else
	   tagcurrent->page = -1;
	 if (sscanf(rectptr,"%lf %lf %lf %lf",&tagcurrent->xmin,
		    &tagcurrent->ymin, &tagcurrent->xmax, &tagcurrent->ymax)
	     != 4) {
	   strcat(buf,"\nGhostview: Incorrect rect specification\n");
	   fprintf(stderr,"error: %s\n",rectptr);
	   tagcurrent->xmin=0;
	   tagcurrent->ymin=0;
	   tagcurrent->xmax=0;
	   tagcurrent->ymax=0;
	 }
       } }
   }
   if (endptr) {
     endptr += strlen("%%]\n");
     memmove(pointer,endptr,strlen(endptr)+1);
   }
   else pointer++;
 }
}

void pdf_clear(void)
{tagcurrent=tagstart=NULL;}

int pdf_page(int x, int y)
{struct tagtable *pointer=tagstart;
 while(tagcurrent&&pointer){
   if (x<=pointer->xmax && x >=pointer->xmin &&
       y<=pointer->ymax && y >=pointer->ymin)
     return pointer->page;
   pointer = pointer->next;
 }
 return -1;
}
