
#include <stddef.h>
#include <stdio.h>
#include <limits.h>
#include <stdarg.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "libsys.h"

char hyppo_setname() = "\tinline\n"
                       "\tldy\t#$18\n"
                       "\tlda\t#$2e\n"
                       "\tsta\t[___hptr],z\n"
                       "\tclv\n"
                       "\tldz\t#0\n"
                       "\teinline";

char hyppo_openfile() = "\tinline\n"
                        "\tlda\t#$18\n"
                        "\tsta\t[___hptr],z\n"
                        "\tclv\n"
                        "\tldz\t#0\n"
                        "\tbcs\t.noerr\n"
                        "\tsta\t_errno\n"
                        "\tlda\t#-1\n"
                        ".noerr:\n"
                        "\teinline";

char hyppo_findfile() = "\tinline\n"
                        "\tlda\t#$34\n"
                        "\tsta\t[___hptr],z\n"
                        "\tclv\n"
                        "\tldz\t#0\n"
                        "\tbcs\t.noerr\n"
                        "\tsta\t_errno\n"
                        "\tlda\t#-1\n"
                        ".noerr:\n"
                        "\teinline";

char hyppo_closeall() = "\tinline\n"
                        "\tlda\t#$22\n"
                        "\tsta\t[___hptr],z\n"
                        "\tclv\n"
                        "\tldz\t#0\n"
                        "\teinline";


static char namebuf[FILENAME_MAX+1];

__zpage long __hptr;

extern FILE __files[FOPEN_MAX+3];

FILE *fopen(const char *name,const char *mode)
{
  FILE *f;
  static char init;
  if(__files[3].filehandle) return 0;

  if(*mode!='r') return 0;

  if(!init){
    __hptr=0xffd3640;
  }

  memcpy(namebuf,(void*)0x1800,FILENAME_MAX);
  memcpy((void*)0x1800,name,FILENAME_MAX);
  hyppo_setname();
  memcpy((void*)0x1800,namebuf,FILENAME_MAX);

  if(hyppo_findfile()==255) return 0;

  hyppo_openfile();

  f=&__files[3];

  f->count=0;
  f->pointer=f->base;
  f->filehandle=4;

  if (1/*md == 'r'*/) 
    f->flags = _READABLE;
  else{
    f->flags = _WRITEABLE;
  }

  return f;
}

char hyppo_closeall() = "\tinline\n"
                        "\tlda\t#$22\n"
                        "\tsta\t[___hptr],z\n"
                        "\tclv\n"
                        "\tldz\t#0\n"
                        "\teinline";

int fclose(FILE *f)
{
  /*char h=f->filehandle;*/
  /*_flushbuf(f);*/
  if(f==&__files[3]){
    hyppo_closeall();
    __files[3].filehandle=0;
  }
  __asm("\tneeds\t___write.3");
  __asm("\tneeds\t___read.3");
  __asm("\tneeds\t_fflush.3");
  __asm("\tneeds\t_stdin");
  __asm("\tneeds\t_stdout");
  __asm("\tneeds\t_stderr");
  return 0;
}

#if 0
void _EXIT_2_fopen(void)
{
 /*_flushbuf(&files[3]);*/
}
#endif
