#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <snes/input.h>
#include <snes/interrupt.h>


static unsigned char buf[33];
static unsigned char idx;
static void input();

int __read(int f,char *p,int n)
{
  unsigned char x=0;
  if(buf[idx]==0){
    input();
    idx=0;
  }
  while(n!=0&&buf[idx]){
    *p++=buf[idx];
    n--;x++;idx++;
  }
  return x;
}

static unsigned int joy(void)
{
 do{}while(REG_HVBJOY&1);
 return REG_JOYxLH(0);
}

static void input()
{
  unsigned int i,j,l=0;
  unsigned int tm,delay=0;

 REG_NMITIMEN=0x1;

  i=0;
  buf[0]='a';buf[1]=0;
  do{}while(j=joy());
  while(1){
    __write(0,"\r",1);
    __write(0,buf,strlen(buf));
    if(j!=l) delay=0x7000;
    l=j;
    if((j&KEY_RIGHT)&&i<30) i++;
    if((j&KEY_LEFT)&&i!=0) i--;
    if(buf[i]==0) {buf[i]=buf[i-1];buf[i+1]=0;}
    if(j&KEY_UP) do{buf[i]++;}while(!isprint(buf[i]));
    if(j&KEY_DOWN) do{buf[i]--;}while(!isprint(buf[i]));
    if(j&KEY_A) break;
    if((j&KEY_B)&&i<31){
      for(j=i+1;j<=31;j++)
        if(buf[j]) buf[j]=' ';
      __write(0,"\r",1);
      __write(0,buf,strlen(buf));

      buf[i+1]=0;
    }
    for(tm=0;tm<delay;tm++) if((j=joy())!=l) break;
    delay=0x500;
  }
  __write(0,"\n",1);
  buf[i+1]='\n';
  buf[i+2]=0;
}

