#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <ctss.h>

static int nchars;
static char linbuf[32767];

static CtssFile_t infile;
static CtssFile_t outfile;
static int firstread = TRUE;
static int rdcnt;

void chball()
{
}

void pack (int64_t *chrs, int64_t cnt)
{
   for (;cnt; cnt--) {
      if (*chrs) 
	 linbuf[nchars++] = *chrs++;
      else chrs++;
   }
}

void rspage(void)
{
   nchars = 0;
}

void prpage (void)
{
   fwrite (linbuf, 1, nchars, outfile.fd);
}

void pkoff (void)
{
   if (outfile.fd != stdout) {
      fclose (outfile.fd);
   }
}

int64_t frame (int64_t val)
{
   return 42;
}

void prpix (void)
{
}

void rsmem (void)
{
}

void setpk (int64_t prinam, bool outfil)
{
   memset (&outfile, 0, sizeof(outfile));
   if (outfil) {
      GetFileStr (outfile.name, prinam, PackStr("   LST"));
      if ((outfile.fd = fopen (outfile.name, "w")) == NULL) {
	 fprintf (stderr, "Can't open for writing: %s: %s\n",
		  outfile.name, strerror(errno));
         exit(1);
      }
   } else {
      strcpy (outfile.name, "TTY");
      outfile.fd = stdout;
   }
}

void wait (void)
{
   while (getchar() != '\n');
}

int64_t seek (int64_t name1, int64_t name2, int64_t *loc)
{
   *loc = 0;
   if (firstread) {
      memset (&infile, 0, sizeof(infile));
      firstread = FALSE;
   }
   GetFileStr (infile.name, name1, name2);
#ifdef DEBUG
   fprintf (stderr, "seek: name = %s\n", infile.name);
#endif
   infile.inuse = TRUE;
   infile.mode = 'r';

   infile.fd = fopen (infile.name, "r");
   rdcnt = 0;
   if (!infile.fd) {
      *loc = 1;
      fprintf (stderr, "Can't open for reading: %s: %s\n",
	       infile.name, strerror(errno));
   }
}

int64_t endrd (void)
{
#ifdef DEBUG
   fprintf (stderr, "endrd: fd = %p\n", infile.fd);
#endif
   if (infile.fd)
      fclose (infile.fd);
   firstread = TRUE;
   rdcnt = 0;
}

int64_t read(int64_t *buf, int64_t cnt, int64_t *eof)
{
   int64_t x, r;
   int i;

   r = 0LL;
   for (i = 0; i < cnt; i++) {
      x = fgetc(infile.fd);
      if (x == EOF) {
	 *eof = 1;
	 break;
      }
      if (x > 0) {
         buf[r+1] = x;
	 r++;
      	 if (x == '\n') break;
      }
   }
   return r;
}

