
#include <stdio.h>

#undef __read

char __conbuf[81];
char __conbufcur;
char __conbufend;

extern FILE __files[];
__zpage long __sdptr;
int __sdlen;

extern char __conx,__conxdim;
extern void __cput(char);

static char readchar(__reg("btmp0") long) = "\tlda\t[btmp0],z";

int hyppo_readfile() = "\tinline\n"
                       "\tlda\t#$1a\n"
                       "\tsta\t[___hptr],z\n"
                       "\tclv\n"
                       "\tldz\t#0\n"
                       "\tbcs\t.noerr\n"
                       "\tsta\t_errno\n"
                       "\tldx\t#-1\n"
                       "\tldy\t#-1\n"
                       ".noerr:\n"
                       "\ttxa\n"
                       "\tpha\n"
                       "\ttya\n"
                       "\ttax\n"
                       "\tpla\n"
                       "\teinline";


char __asciitopetscii(char c)
{
    if (c>=97 && c<=122 )
    {
        return c - 32;
    }

    if (c >= 65 && c <= 90)
    {
        return c + 32;
    }

    return c;
}

void __readline(void)
{
  __conbufend=0;
  __cput('_');
  while(1){
    char c;
    while((c=readchar(0xffd3610))==0);
    __asm("\tlda\t#0\n\tsta\t[btmp0],z");
    c=__asciitopetscii(c);
    if(c=='\n'){__conbuf[__conbufend++]=c;--__conx;__cput(' '); __cput(c);return;}
    else if(c==20){if(__conbufend) --__conbufend;__conx-=2;__cput('_');__cput(' ');--__conx;}
    else if(__conx==__conxdim-1||__conbufend==sizeof(__conbuf)) continue;
    else{__conbuf[__conbufend++]=c;--__conx;__cput(c);__cput('_');}
  }
}

char __readsdbuf()="\tlda\t[___sdptr],z";

static int __sdgetnext()
{
 unsigned char c;
 if(__sdlen<=0){
   __sdlen=hyppo_readfile();
   if(__sdlen<=0) return -1;
   __sdptr=0xffd6e00;
 }
 c=__readsdbuf();
 __sdlen--;
 __sdptr++;
 return c;
}

static char __congetnext()
{
 char c;
 if(!__conbufcur)
    __readline();
  c=__conbuf[__conbufcur];
  if(++__conbufcur==__conbufend) __conbufcur=0;
  return c;
}

unsigned int __read(int f,char *p,unsigned int len)
{
  unsigned int n=0;
  char c;
  do{
   if(f==4){
     int r=__sdgetnext();
     *p++=c=r;
     if(r<0) {__files[3].flags|=_EOF;break;}
     n++;
   }else{
     *p++=c=__congetnext();
      n++;
   }
  }while(n<len&&c!='\n');
  return n;
}
