bits	16
org		0x0500
start: jmp main

%define IMAGE_LMODE_BASE 0x100000
%define IMAGE_PMODE_BASE 0x100000
%define IMAGE_RMODE_BASE 0x3000
%include "FILES\NewTry\stdio.inc"
%include "FILES\NewTry\gdt.inc"
%include "FILES\NewTry\A20.inc"
%include "FILES\NewTry\Memory.inc"
%include "FILES\NewTry\Paging.inc"
%include "FILES\NewTry\FAT12.inc"

bits 16
main:
cli
xor		ax, ax
mov		ds, ax
mov		es, ax
mov		ss, ax
mov		sp, 0FFFEh
sti
pop dx
mov	[BootDevice], dl

jmp startcheck
%include "FILES\NewTry\bitmenu.inc"
cmp ah, 0x00
je bit16proc
cmp ah, 0x01
je bit32proc
;cmp ah, 0x02
;je bit64proc
bits 16
	
bit16proc:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;goto real mode OS
mov		si, msgFailure
call   	Puts16
mov		ah, 0
int     0x16
int     0x19
cli
hlt
		
bit32proc:
call	ENABLE_A20
call	InstallGDT
call	LoadRoot
mov    	ebx, 0
mov		ebp, IMAGE_RMODE_BASE
mov 	esi, ImageName
call	LoadFile
mov   	dword [ImageSize], ecx
push	ecx
;call	MEMEM
cmp		ax, 0
je		OK
mov		si, msgFailure
call   	Puts16
mov		ah, 0
int     0x16
int     0x19
cli
hlt
OK:
cli
mov	eax, cr0
or	eax, 1
mov	cr0, eax

jmp   CODE_DESC:Stagekrn32
bits 32
Stagekrn32:
mov   ax, DATA_DESC
mov   ds, ax
mov   ss, ax
mov   es, ax
mov   esp, 90000h   
call   ClrScr32
call   EnablePaging
CopyImage:
mov ecx, [ImageSize]
movzx ebx, word [bpbBytesPerSector]
imul ecx,ebx
shr ecx,2
cld
mov esi, IMAGE_RMODE_BASE
mov   edi, IMAGE_PMODE_BASE
rep movsd
mov esi,IMAGE_RMODE_BASE
mov ebx,[esi+60]
cmp word [esi+ebx],'PE'
je     ContinueLoad
mov   ebx, BadImage
call   Puts32
cli
hlt
ContinueLoad:
movzx edx,word [esi+ebx+6]
add ebx,256
sectionloop:
mov ebp,[esi+ebx]
mov edi,[esi+ebx+4]
add edi,IMAGE_PMODE_BASE
mov ecx,[esi+ebx+8]
cmp ecx,ebp
jb vsize_ok
mov ecx,ebp
vsize_ok:
sub ebp,ecx
push esi
add esi,[esi+ebx+12]
rep movsb
pop esi
mov ecx,ebp
mov al,0
rep stosb
add ebx,40
dec edx
jnz sectionloop
TestImage:
mov esi,IMAGE_RMODE_BASE
mov ebx,[esi+60]
mov eax,[esi+ebx+40]
add eax,[esi+ebx+52]

mov byte[eax], 0xEB						;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
inc eax									;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov byte[eax], 0xFE						;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
dec eax									;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

call eax
cli
hlt

bit64proc:
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;goto long mode OS
mov		si, msgFailure
call   	Puts16
mov		ah, 0
int     0x16
int     0x19
cli
hlt		
	
ImageSig db 'PE'	
BadImage db "Error: please reboot.", 0
LoadingMsg db 0x0D, 0x0A, "Searching for Operating System...", 0x00
msgFailure db 0x0D, 0x0A, "Error: press any key to reboot.", 0x0D, 0x0A, 0x0A, 0x00
ImageName		db "KERNEL  EXE"
ImageSize		dd 0
BootDevice	db 0
bitnum			dw 0 