#include "libopgp.h"

static u8_t lastchr, lastung;

int fgetc(FILE * fp)
{
  if (lastung) {
    lastung = 0;
    return lastchr;
  }
  if (1 == fread(&lastchr, 1, 1, fp))
    return lastchr;
  else
    return -1;
}

int ungetc(int c, FILE * fp)
{
  lastung = c;
  lastchr = c;
  return c;
}

int fputc(int c, FILE * fp)
{
  u8_t c1 = c;
  fwrite(&c1, 1, 1, fp);
  return c1;
}

int fgets(char *c, int l, FILE * fp)
{
  int lorg = l;
  if (l)
    *c = 0;
  while (l--) {
    if (1 != fread(c, 1, 1, fp) || *c++ == '\n')
      break;
  }
  if (l)
    *c = 0;
  return lorg - l;
}

FILE *fopen(char *name, char *mode)
{
  lastung = 0;
  return FileOpen(0, name, 'DATA', 'OPGP',
                  (*mode == 'r' ? fileModeReadOnly : fileModeReadWrite)
                  | fileModeAnyTypeCreator, NULL);
}
