/*
	 Assembly C++ function library
	 Microsoft Platform dependent :(
	 done by Zhihua Lai
	 Code is free, please keep the header.
*/

#ifndef LYCHEE_ASM_FUNC
#define LYCHEE_ASM_FUNC
#define ERROR -1
#define NORMAL 0

unsigned char myToUpper(const unsigned char character)
{
  asm {
    cmp character,0x61
    jb exit
    cmp character,0x7a
    ja exit
    and character,0xdf
  }

  exit:
   return (character);
}

unsigned char myToLower(const unsigned char character)
{
  asm {
    cmp character,0x41
    jb exit
    cmp character,0x5a
    ja exit
    or character,0x20
  }

  exit:
   return (character);
}

int myExit4c(const unsigned char returnCode)
{
  asm {
    mov ah,0x4c
    mov al,returnCode
    int 0x21
  }
  return (NORMAL);
}

unsigned char myGetCharEcho(void)
{
  asm {
    mov ah,0x01
    int 0x21
  }
  return (_AL);
}

int myPutChar(const unsigned char character)
{
  asm {
    mov ah,0x02
    mov dl,character
    int 0x21
  }
  return (NORMAL);
}

unsigned char myGetAuxChar(void)
{
  asm {
    mov ah,0x03
    int 0x21
  }
  return (_AL);
}

int myPutAuxChar(const unsigned char character)
{
  asm {
    mov ah,0x04
    mov dl,character
    int 0x21
  }
  return (NORMAL);
}

int myPrintOut(const unsigned char character)
{
  asm {
    mov ah,0x05
    mov dl,character
    int 0x21
  }
  return (NORMAL);
}

int myDirectOutput(const unsigned char character)
{
  if (character==0xff) return (ERROR);
  asm {
    mov ah,0x06
    mov dl,character
    int 0x21
  }
  return (NORMAL);
}

int myDirectInput(unsigned char *character)
{
  asm {
    xor al,al
    mov ah,0x06
    mov dl,0xff
    int 0x21
    jz s
  }
  *character=_AL;
  s:
   return (_AL);
}

int myDirect(const unsigned char param)
{
  asm {
    xor al,al
    mov ah,0x06
    mov dl,param
    int 0x21
  }
  return (_AL);
}

unsigned char myUnfilteredGetCharNoEcho(void)
{
  asm {
    mov ah,0x07
    int 0x21
  }
  return (_AL);
}

unsigned char myGetCharNoEcho(void)
{
  asm {
    mov ah,0x08
    int 0x21
  }
  return (_AL);
}


int myPutString_oem(const char *string)
{
  asm {
    mov ah,0x09
    mov dx,string
    int 0x21
  }
  return (NORMAL);
}

int myPutString_alpha(const char *string)
{
  asm {
    mov ah,0x09
    mov dx,string
    mov di,dx
    mov cx,0xffff
  }
  asm {
   repne scasb
   dec di
   mov byte ptr[di],'$'
   int 0x21
   xor al,al
   mov byte ptr[di],al
  }
  return (NORMAL);
}

int myPutString(const char *string)
{
  asm {
    mov di,string
  }
  l:
  asm {
    test byte ptr[di],0xff
    jz e
    mov ah,0x02
    mov dl,byte ptr[di]
    int 0x21
    inc di
    jmp l
  }
  e:
   return (NORMAL);
}

int myGetLine(char *string,const unsigned char l)
{
  if (l==0) return (ERROR);
  asm {
    mov dx,string
    mov di,dx
    mov al,l
    mov byte ptr[di],al
    mov ah,0x0a
    int 0x21
    mov al,[di+1]
    xor ah,ah
    mov bx,ax
    mov byte ptr[bx+di+2],ah
  }
  return (_AL);
}

#endif
