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

char __open(__reg("r0/r1") char *,__reg("r2") char )=
"\tinline\n"
"\tldy\t#-1\n"
".loop:\n"
"\tiny\n"
"\tlda\t(r0),y\n"
"\tbne\t.loop\n"
"\tlda\t#$0d\n"
"\tsta\t(r0),y\n"
"\tldx\tr0\n"
"\tldy\tr1\n"
"\tlda\tr2\n"
"\tjsr\t$ffce\n"
"\teinline";

void __close(__reg("a") char)="\ttay\n\tlda\t#0\n\tjsr\t$ffce";

static char namebuf[FILENAME_MAX+1];

extern FILE __files[FOPEN_MAX+3];


FILE *fopen(const char *name,const char *mode)
{
  FILE *f;
  char md,c;

  for(c=3;c<sizeof(__files)/sizeof(__files[0]),c++){
    if(!__files[c].filehandle) break;
  }

  if(c>=sizeof(__files)/sizeof(__files[0])) {errno=ENFILE;return 0;}
  f=&__files[c];

  md=0xC0;
  if(*mode=='r') md=0x40;
  else if(mode=='w') md=0x80;

  strcpy(namebuf,name);

  c=__open(namebuf,md);

  if(c==0){ errno=ENOENT; return 0; }
  f->filehandle=c;
  f->count=0;
  f->pointer=f->base;
  f->flags=0;
  if(md&0x40) f->flags|=_READABLE;
  if(md&0x80) f->flags|=_WRITEABLE;

  return f;
}

int fclose(FILE *f)
{
  char h=f->filehandle;
  _flushbuf(f);
  __close(h);
  f->filehandle=0;
  return 0;
}

void _EXIT_2_fopen(void)
{
  char c;
  for(c=0;c<sizeof(__files)/sizeof(__files[0]);c++){
   if(__files[c].filehandle) _flushbuf(&__files[c]);
  }
}
