#define __attribute__(x)
#include "snes/video.h"
#include "snes/background.h"

/*__near*/ unsigned int CursorX,CursorY;

extern char __font[];

#define REG_CGDATA (*(vuint8 *)0x2122)

void _INIT_2_write(void)
{
  REG_BG12NBA = 17;
  REG_BG1SC = 0;
  REG_INIDISP = (128+15);
  REG_VMAIN = 0;
  REG_BGMODE = 9;
  REG_CGADD = 0;
  REG_CGDATA = 0;
  REG_CGDATA = 0;

  REG_CGADD = 3;
  REG_CGDATA = 255;
  REG_CGDATA = 7;

  REG_VMADDLH = 0x1000;

  unsigned int c,i;

  c=0;
  while(c<95*8){
    for(i=8;i!=0;i--){
      char x=__font[c++];
      REG_VMDATAH=x;
      REG_VMDATAL=x;
    }
    for(i=8;i!=0;i--){
      REG_VMDATAH=0;
      REG_VMDATAL=0;
    }
  }
  REG_BG1HOFS=0;
  REG_BG1HOFS=0;
  REG_BG1VOFS=255;
  REG_BG1VOFS=255;

  REG_VMADDL=0;
  REG_VMADDH=0;

  for(i=0x400;i>0;i--){
    REG_VMDATALH=0;
  }
  REG_TM=1;

  REG_INIDISP=15;

}

void __chrout(int x)
{
  int adr;
  if(x=='\r'){CursorX=0;return;}
  if(x=='\n'||CursorX==32){
    CursorX=0;
    if(CursorY==27){
      unsigned int i,v,sadr=32,dadr=0;
      //      do{}while((REG_HVBJOY&128)==0);
      for(i=27*32;i!=0;i--){
        if((i&63)==0){
	  //          do{}while((REG_HVBJOY&128)!=0);
	  //          do{}while((REG_HVBJOY&128)==0);
        }
        REG_VMADDLH=sadr++;
        v=REG_VMDATAREADLH;

        REG_VMADDLH=dadr++;
        REG_VMDATALH=v;
      }
      for(i=32;i!=0;i--){
        REG_VMADDLH=dadr++;
        REG_VMDATALH=0;
      }

    }else
      CursorY++;
    if(x=='\n')
      return;
  }
  adr=CursorY*32+CursorX;
  //  do{}while((REG_HVBJOY&128)!=0);
  //  do{}while((REG_HVBJOY&128)==0);
  REG_VMADDLH=adr;
  REG_VMDATAH=0;
  REG_VMDATAL=x-32;
  CursorX++;
}

int __write(int f,char *p,unsigned int len)
{
  unsigned int n=len;
  REG_INIDISP=0x80;
  while(n){
    __chrout(*p++);
    n--;
  }
  REG_INIDISP=15;
  return len;
}

