/* external procedures called by TeX */
/* version adapted for cooperation with pc3 instead of pc */

#include <sys/signal.h>
#ifdef gould
#include <sys/time.h>
#else
#include <time.h>
#endif
#include "texpaths.h" /* defines MAXINPATHCHARS, defaultinputpath, etc. */
#include "h00vars.pc3.h"

# define BOOLEAN        char
# define TRUE 1
# define FALSE 0

extern char *malloc();

struct {
	 FILE *fp;
	 BOOLEAN eof,eoln,validbuffer;
	 char buffer;
       } INPUT;

extern int
#ifdef M_XENIX
near
#endif
interrupt;	/* To be made nonzero to tell TeX about interrupts */
extern long int initialized; /* true if this is a preloaded TeX */

selectscheduling()
{
#ifdef M_XENIX
  /* lock in core, because swapping is too expensive */
  plock(1);
#endif
  setuid(getuid()); /* in case superuser-bit */
  return;
}
/*
**	catchint()
**
**  Gets called when the user hits his interrupt key.  Sets the global
**  "interrupt" nonzero, then sets it up so that the next interrupt will
**  also be caught here.
**
*/

catchint()
{
	interrupt = 1;
	signal(SIGINT,catchint);
}

/*
**      dateandtime(time, day, month, year)
**
**  Stores minutes since midnight, current day, month and year into
**  *time, *day, *month and *year, respectively.
**
**  Also, set things up so that catchint() will get control on interrupts.
**
*/

dateandtime(minutes, day, month, year)
long int     *minutes, *day, *month, *year;
{
        long        clock;
	long	    help;
	struct tm   *tmptr, *localtime();
	
	help = time(&clock); /* was 0 but that seems not to work */
			     /* Xenix bug causes need for help */
	tmptr = localtime(&clock);
	
	*minutes = tmptr->tm_hour * 60 + tmptr->tm_min;
	*day = tmptr->tm_mday;
	*month = tmptr->tm_mon + 1;
	*year = tmptr->tm_year + 1900;
	if (initialized)
	  signal(SIGINT,catchint);
}


/* fixed arrays are used to hold the paths, to avoid any possible problems
   involving interaction of malloc and undump		*/

char inputpath[MAXINPATHCHARS] = defaultinputpath;
char fontpath[MAXOTHPATHCHARS] = defaultfontpath;
char formatpath[MAXOTHPATHCHARS] = defaultformatpath;
char poolpath[MAXOTHPATHCHARS] = defaultpoolpath;

char *getenv();

/*
 * setpaths is called to set up the arrays inputpath, fontpath, formatpath
 * and poolpath as follows:  if the user's environment has a value for the
 * appropriate value, then use it;  otherwise, leave the current value of
 * the array (which may be the default path, or it may be the result of
 * a call to setpaths on a previous run that was made the subject of
 * an undump: this will give the maker of a preloaded TeX the option of
 * providing a new set of "default" paths.
 *
 * Note that we have to copy the string from the environment area, since
 * that will change on the next run (which matters if this is for a
 * preloaded TeX).
 */
setpaths()
{
	register char *envpath;
	
	if ((envpath = getenv("TEXINPUTS")) != NULL)
	    copypath(inputpath,envpath,MAXINPATHCHARS);
	if ((envpath = getenv("TEXFONTS")) != NULL)
	    copypath(fontpath,envpath,MAXOTHPATHCHARS);
	if ((envpath = getenv("TEXFORMATS")) != NULL)
	    copypath(formatpath,envpath,MAXOTHPATHCHARS);
	if ((envpath = getenv("TEXPOOL")) != NULL)
	    copypath(poolpath,envpath,MAXOTHPATHCHARS);
}

/*
 * copypath(s1,s2,n) copies at most n characters (including the null)
 * from string s2 to string s1, giving an error message for paths
 * that are too long.
 */
copypath(s1,s2,n)
    register char *s1,*s2;
    register int n;
{
	while ((*s1++ = *s2++) != '\0')
	    if (--n == 0) {
		fprintf(stderr, "! Environment search path is too big\n");
		*--s1 = '\0';
		return; /* let user continue with truncated path */
		}
}

#define filenamesize 1024   /* should agree with initex.ch */
extern char nameoffile[],realnameoffile[]; /* these have size filenamesize */

/*
 *	testaccess(amode,filepath)
 *
 *  Test whether or not the file whose name is in the global nameoffile
 *  can be opened for reading (if mode=READACCESS)
 *  or writing (if mode=WRITEACCESS).
 *
 *  The filepath argument is one of the ...FILEPATH constants defined below.
 *  If the filename given in nameoffile does not begin with '/', we try 
 *  prepending all the ':'-separated areanames in the appropriate path to the
 *  filename until access can be made, if it ever can.
 *
 *  The realnameoffile global array will contain the name that yielded an
 *  access success.
 */

#define READACCESS 4
#define WRITEACCESS 2

#define NOFILEPATH 0
#define INPUTFILEPATH 1
#define READFILEPATH 2
#define FONTFILEPATH 3
#define FORMATFILEPATH 4
#define POOLFILEPATH 5

BOOLEAN
testaccess(amode,filepath)
    int amode,filepath;
{
    register BOOLEAN ok;
    register char *p;
    char *curpathplace;
    int f;
    
    switch(filepath) {
	case NOFILEPATH: curpathplace = NULL; break;
	case INPUTFILEPATH: case READFILEPATH:
			curpathplace = inputpath; break;
	case FONTFILEPATH: curpathplace = fontpath; break;
	case FORMATFILEPATH: curpathplace = formatpath; break;
	case POOLFILEPATH: curpathplace = poolpath; break;
	}
    if (nameoffile[0]=='/')	/* file name has absolute path */
	curpathplace = NULL;
    do {
	packrealnameoffile(&curpathplace);
	if (amode==READACCESS)
	    /* use system call "access" to see if we could read it */
	    if (access(realnameoffile,READACCESS)==0) ok = TRUE;
	    else ok = FALSE;
	else {
	    /* WRITEACCESS: use creat to see if we could create it, but close
	    the file again if we're OK, to let pc open it for real */
	    f = creat(realnameoffile,0666);
	    if (f>=0) ok = TRUE;
	    else ok = FALSE;
	    if (ok)
		close(f);
	    }
    } while (!ok && curpathplace != NULL);
    return (ok);
}

/*
 * packrealnameoffile(cpp) makes realnameoffile contain the directory at *cpp,
 * followed by '/', followed by the characters in nameoffile up until the
 * first blank there, and finally a '\0'.  The cpp pointer is left pointing
 * at the next directory in the path.
 * But: if *cpp == NULL, then we are supposed to use nameoffile as is.
 */
packrealnameoffile(cpp)
    char **cpp;
{
    register char *p,*realname;
    
    realname = realnameoffile;
    if ((p = *cpp)!=NULL) {
	while ((*p != ':') && (*p != '\0')) {
	    *realname++ = *p++;
	    if (realname == &(realnameoffile[filenamesize-1]))
		break;
	    }
	if (*p == '\0') *cpp = NULL; /* at end of path now */
	else *cpp = p+1; /* else get past ':' */
	*realname++ = '/';  /* separate the area from the name to follow */
	}
    /* now append nameoffile to realname... */
    p = nameoffile;
    while (*p != '\0') { /* a blank was here instead of \0, pc3 wants \0 */
	if (realname >= &(realnameoffile[filenamesize-1])) {
	    fprintf(stderr,"! Full file name is too long\n");
	    break;
	    }
	*realname++ = *p++;
	}
    *realname = '\0';
}

/*
**  The following procedure is due to sjc@s1-c.
**
**	calledit(filename, fnlength, linenumber)
**
**  TeX82 can call this to implement the 'e' feature in error-recovery
**  mode, invoking a text editor on the erroneous source file.
**  
**  You should pass to "filename" the first character of the packed array
**  containing the filename, and to "fnlength" the size of the filename.
**  
**  Ordinarily, this invokes "/usr/ucb/vi". If you want a different
**  editor, create a shell environment variable TEXEDIT containing
**  the string that invokes that editor, with "%s" indicating where
**  the filename goes and "%d" indicating where the decimal
**  linenumber (if any) goes. For example, a TEXEDIT string for a
**  variant copy of "vi" might be:
**  
**	setenv TEXEDIT "/usr/local/bin/vi +%d %s"
**  
*/

   char dvalue[] = "/usr/ucb/vi +%d %s";
   char *texeditvalue = &dvalue[0];

   calledit(filename, fnlength, linenumber)
      char *filename;
      int fnlength;
      long int linenumber;
   {
      char *temp, *command, c;
      long int sdone, ddone, i;

      sdone = ddone = 0;

      /* Replace default with environment variable if possible. */
      if (NULL != (temp = (char *) getenv("TEXEDIT")))
	 texeditvalue = temp;

      /* Make command string containing envvalue, filename, and linenumber */
      if (NULL ==
	 (command = (char *) malloc(strlen(texeditvalue) + fnlength + 25))) {
	 fprintf(stderr, "! Not enough memory to issue editor command\n");
	 exit(1);
	 }
      temp = command;
      while ((c = *texeditvalue++) != '\0') {
	 if (c == '%') {
	    switch (c = *texeditvalue++) {
	       case 'd': 
		  if (ddone) {
		     fprintf(stderr,
		     "! Line number cannot appear twice in editor command\n");
		     exit(1);
		     }
		  sprintf(temp, "%ld", linenumber);
		  while (*temp != '\0')
		     temp++;
		  ddone = 1;
		  break;
	       case 's':
		  if (sdone) {
		     fprintf(stderr,
			"! Filename cannot appear twice in editor command\n");
		     exit(1);
		     }
		  i = 0;
		  while (i < fnlength)
		     *temp++ = filename[i++];
		  sdone = 1;
		  break;
	       case '\0':
		  *temp++ = '%';
		  texeditvalue--; /* Back up to \0 to force termination. */
		  break;
	       default:
		  *temp++ = '%';
		  *temp++ = c;
		  break;
	       }
	    }
	 else
	    *temp++ = c;
	 }
      *temp = '\0';

      /* Execute command. */
      if (0 != system(command))
	 fprintf(stderr, "! Trouble executing command %s\n", command);

      /* Quit, indicating TeX had found an error before you typed "e". */
      exit(1);
      }

int _abs(a)
int a;

{
  return((a>0)?a:-a);
}

long _labs(a)
long a;

{
  return((a>0L)?a:-a);
}

double _rabs(a)
double a;

{
  return((a>0.0)?a:-a);
}

long int _round(x)
double x;

{
  register long y;
  if (x>0.0)
    y = (long)(x+0.5);
  else
    y = (long)(x-0.5);
  return(y);
}
