#include "kernel.h"

word *screen = (word *)0xB8000;
word cursorx = 0, cursory = 0, attr = 0x0F00;

void outportb(word port, byte data)
{
    __asm__("outb %1, %0"::"d"(port), "a" (data));
}

byte inportb(word port)
{
	byte data;
	__asm__("inb %1, %0":"=a" (data):"d" (port));
	return data;
}

void updatecursor()
{
	dword temp = (cursory * 80) + cursorx;
	outportb(VGA_CRTC_INDEX, 14); outportb(VGA_CRTC_DATA, (temp >> 8));
	outportb(VGA_CRTC_INDEX, 15); outportb(VGA_CRTC_DATA, (temp & 0xFF));
}

void showcursor()
{
	outportb(VGA_CRTC_INDEX, 10);
	byte cursor = (inportb(VGA_CRTC_DATA) & ~0x20);
	outportb(VGA_CRTC_DATA, cursor);
}

void hidecursor()
{
	outportb(VGA_CRTC_INDEX, 10);
	byte cursor = (inportb(VGA_CRTC_DATA) | 0x20);
	outportb(VGA_CRTC_DATA, cursor);
}

void cls(byte ch)
{
    word *line, blank = (attr | ch);
    for(int y = 0; y < 25; y++){
        line = (screen + (y * 80));
        for(int x = 0; x < 80; x++)
            *(line + x) = blank;
    }
    cursorx = 0; cursory = 0;
    updatecursor();
}

byte putch(byte ch)
{
    switch(ch){
        case '\b': if(cursorx > 0) cursorx--;          break;
        case '\t': cursorx = (cursorx + 4) & ~(4 - 1); break;
        case '\r': cursorx = 0;                        break;
        case '\n': cursorx = 0; cursory++;             break;
          default: if(ch < ' ')                        break;
            *(screen + (cursory * 80) + cursorx) = (attr | ch);
            cursorx++;
    }
    if(cursorx >= 80){
        cursorx = 0; cursory++;
    }
    updatecursor();
    return ch;
}

void putsnocr(string text){
    while(*text) putch(*text++);
}

void puts(string text){
    putsnocr(text); putch('\n');
}

void settextcolor(char fore, char back){
    attr = ((back << 12) | ((fore & 0x0F) << 8));
}

void gotoxy(int x, int y)
{
    cursorx = x; cursory = y;
    updatecursor();
}

