/* macstuff.c - macintosh interface routines for xlisp */

#include <string.h>
#include <stdio.h>

/* program limits */
#define LINEMAX 	200	/* maximum line length */

/* externals */
extern FILE *tfp;
extern int x;

/* local variables */
static char linebuf[LINEMAX+1],*lineptr;
static int linepos[LINEMAX],linelen;
static long rseed = 1L;

osinit(name)
  char *name;
{
    /* initialize the mac interface routines */
    macinit();

    /* initialize the line editor */
    linelen = 0;
}

osfinish()
{
}

oserror(msg)
{
    char line[100],*p;
    sprintf(line,"error: %s\n",msg);
    for (p = line; *p != '\0'; ++p)
	ostputc(*p);
}

int osrand(n)
  int n;
{
    long k1;
    
    /* make sure we don't get stuck at zero */
    if (rseed == 0L) rseed = 1L;
    
    /* algorithm taken from Dr. Dobbs Journal, November 1985, Page 91 */
    k1 = rseed / 127773L;
    if ((rseed = 16807L * (rseed - k1 * 127773L) - k1 * 2836L) < 0L)
	rseed += 2147483647L;
	
    /* return a random number between 0 and n-1 */
    return ((int)(rseed % (long)n));
}

FILE *osaopen(name,mode)
  char *name,*mode;
{
    return (fopen(name,mode));
}

FILE *osbopen(name,mode)
  char *name,*mode;
{
    char nmode[4];
    strcpy(nmode,mode); strcat(nmode,"b");
    return (fopen(name,nmode));
}

int osclose(fp)
  FILE *fp;
{
    return (fclose(fp));
}

int osagetc(fp)
  FILE *fp;
{
    return (getc(fp));
}

int osbgetc(fp)
  FILE *fp;
{
    return (getc(fp));
}

int osaputc(ch,fp)
  int ch; FILE *fp;
{
    return (putc(ch,fp));
}

int osbputc(ch,fp)
  int ch; FILE *fp;
{
    return (putc(ch,fp));
}

int ostgetc()
{
    int ch,i;

    if (linelen--) return (*lineptr++);
    linelen = 0;
    while ((ch = scrgetc()) != '\r')
	switch (ch) {
	case EOF:
	    return (ostgetc());
	case '\010':
	    if (linelen > 0) {
		linelen--;
		while (x > linepos[linelen])
		    scrdelete();
	    }
	    break;
	default:
	    if (linelen < LINEMAX) {
	        linebuf[linelen] = ch;
		linepos[linelen] = x;
		linelen++;
	    }
	    scrputc(ch);
	    break;
	}
    linebuf[linelen++] = '\n';
    scrputc('\r'); scrputc('\n');
    if (tfp)
	for (i = 0; i < linelen; ++i)
	    osaputc(linebuf[i],tfp);
    lineptr = linebuf; linelen--;
    return (*lineptr++);
}

int ostputc(ch)
  int ch;
{
    if (ch == '\n')
	scrputc('\r');
    scrputc(ch);
    if (tfp)
	osaputc(ch,tfp);
    return (1);
}

osflush()
{
    lineptr = linebuf;
    linelen = 0;
}

oscheck()
{
    DoEvent();
}

