#include "clib.h"
#include "i386.h"
#include "console.h"


void real_debug_handler(int sig) _fastcall;

static int __if = 0;

void __cli(void)
{
	int n;
	asm ("pushfl\n"
             "popl %%eax\n"
             "orl  $0x8000,%%eax\n"
             "shrl $8,%%eax\n"
             "jb   1f\n"
             "xorl  %%eax,%%eax\n"
             "1:\n":"=a"(n));
       if (n == 0) {
        if (__if > 0) __if = 0;
       	__if--;
        asm_cli;
       }
       else {
        __if++;
        if (__if > 0) asm_sti;
       }
}

void __sti(void)
{

}

console_t debugcon;

void handle_keyboard()
{
	int sc;
        asm("inb $0x60,%%al":"=al"(sc):);
        if (sc == 1) exit(5);
        con_convert_key(&debugcon, sc);
}


void real_debug_handler(int sig)
{
   asm_cli;
   switch (sig) {
        case 1: handle_keyboard();
        default : return;
   }
   asm_sti;

}

void debug_msg(const char*msg, ...)
{
	va_list args;
        char	buf[2048];
        va_start(args, msg);
        vsprintf(buf, msg, args);
        con_write(&debugcon, buf);
        va_end(args);
}


char readkey(void)
{
	char c;
        char_t ct;
        do {
                asm_cli;
        	ct = con_get_key(&debugcon);
		debug_msg("\e[s\e[Hshift %2d\e[u",ct.shift);
                asm_sti;
        } while (ct.ascii == 0);
        if (ct.ascii == 0) kprintf("@@@");
//        debug_msg("\e[s\e[Hshift %2d\e[u",ct.shift);

//        debug_msg("ascii %c sc %xh",ct.ascii,ct.scanc);
//	kprintf("ascii %d sc %xh",ct.ascii,ct.scanc);
        c = ct.ascii;

        return c;
}




void putc(char c)
{
	char str[2] = {c,0};
        con_write(&debugcon, str);
}



void debug_start(void)
{
        char c;
        int i;
        asm_cli;
        memset(&debugcon,0,sizeof(debugcon));
        debugcon.video = (void*)0xB8000;
        debugcon.color = 0x0700;
        debugcon.fl.outrdy = 1;
        debugcon.fl.movecursor = 1;
        debugcon.hwwidth = 80;
        debugcon.width = 80;
        debugcon.height = 25;
        asm_cli;
        con_write(&debugcon, "\e[2JKernel Debugger V0.0a\n");
                for (i = 0; i < 1000; i++) {
                con_write(&debugcon, "\e[s\e[Hshift %2d\e[u");
                }

        asm_cli;
        __cli();
        asm_sti;
        __cli();


        do {
		c = readkey();
                putc(c);

//                kprintf("%c", c);
        } while (c != 27);
        exit(0);
}