#include "bootpack.h"
#include "filesystem.h"
#include "typedefs.h"
#include "screen.h"
#include "timer.h"
#include "desctable.h"
#include "ata/ataio.h"
#include "pic.h"
#include "naskfunc.h"
#include "MemMan.h"
#include "debug.h"
#include "ProcessMan.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

BOOTINFO *binfo = (BOOTINFO *)ADR_BOOTINFO;

extern "C" int __cdecl _main(int p1){
	Screen::Init(binfo);
	init_gdtidt();

	init_pit();
	init_pic();
	
	io_sti();

	io_out8(PIC0_IMR, 0xfa); /* PITとPIC1を許可(11111010) */
	io_out8(PIC1_IMR, 0xff); /* 全部無視(11111111) */

	FileSystem::Init(binfo);

	MemMan::Init();
	ProcessMan::Init();
	ThreadMan::Init();

	BITMAPFILEHEADER fileheader;
	BITMAPINFOHEADER infoheader;

	/*
	FileSystem::File *file = FileSystem::Inst().CreateFile(L"c:\\curtain_.bmp", 0, 0, 0, 0, 0, 0);
	debugprint("file:%p\n", file);

	file->Read((BYTE *)&fileheader, sizeof(fileheader));

	file->Read((BYTE *)&infoheader, sizeof(infoheader));
	//debugprint("%X %X %X\n", fileheader.bfType, fileheader.bfSize, fileheader.bfOffBits);

	//for(;;){__asm ("hlt");}

	file->Seek(fileheader.bfOffBits, FileSystem::File::SEEK_ORG::SET);

	int stride = (infoheader.biWidth * 3 + 3) / 4 * 4;
	BYTE *p = new BYTE [stride];
	//debugprint("%d %d\n", infoheader.biHeight,infoheader.biWidth );
	for(int i = 0; i < infoheader.biHeight; i++){
		file->Read(p, stride);

		for(int j = 0; j < infoheader.biWidth; j++){
			//binfo->vram[((infoheader.biHeight - i - 1) * binfo->screenx + j) * 3 + 0] = p[j * 3 + 0];
			//binfo->vram[((infoheader.biHeight - i - 1) * binfo->screenx + j) * 3 + 1] = p[j * 3 + 1];
			//binfo->vram[((infoheader.biHeight - i - 1) * binfo->screenx + j) * 3 + 2] = p[j * 3 + 2];
		}
	}
	delete [] p;
	delete file;
	*/
	ProcessMan::Inst().CreateProcess(L"c:\\ostestapp.exe");

	int t = 0;
	for(;;){
		for(volatile int i = 0; i < 0x10000; i++){
			volatile int x = i * i;
		}
		//Screen::Inst().printf("%d", t++);
		__asm ("hlt");
	}
	return 0;
}
