format binary
use32
org 0ac00h

include 'systemvar.inc'
include 'cpu.inc'

	mov	ax, 10h
	mov	ds, ax
	mov	es, ax
	mov	ss, ax
	mov	esp, 7c00h
	call	setupidt
	call	detectcpu

	;..
;        mov     al, 20h
;        out     64h, al
;        in      al, 60h
;        movzx   eax, al
;        push    eax
;        call    dwtoh
	mov	word[0b8000h],"A1"
	sti
     @@:
	mov	ah, 1
	int	30h
	jz	@B
	mov	edi, buffer
	mov	ah, 2
	int	30h
	mov	edi, buffer
	mov	al, [edi]
	mov	ah, "1"
	mov	[0b8010h],ax
     jmp  @B
     buffer rb 32

;        mov     si, string
;        mov     ah, 0eh
;     @@:
;        lodsb
;        test    al ,al
;        jz      @F
;        int     10h
;        jmp     @B
;     @@:
;        cli
;        hlt

setupidt:
	cli
	;remap irq
	in	al,021h
	mov	ah,al
	in	al,0A1h
	mov	cx,ax

	mov	al,011h 		; ICW1 to both controllers
	out	20h, al 		; bit 0=1: ICW4 provided
	call	Delay32 		; bit 1=0: cascaded PICs
	out	0A0h, al		; bit 2=0: call address interval 8
	call	Delay32 		; bit 4=1: at 1 (?)
	mov	al, 20h 		; ICW2 PIC1 - offset of vectors
	out	21h, al 		; irq00:07 mapped to int_20h:27h
	call	Delay32
	mov	al, 28h 		; ICW2 PIC2 - offset of vectors
	out	0A1h, al		; irq08:15 mapped to int028h:2fh
	call	Delay32
	mov	al,04h			; ICW3 PIC1 (master)
	out	21h, al 		; bit 2=1: irq2 is the slave
	call	Delay32
	mov	al,02h			; ICW3 PIC2
	out	0A1h, al		; bit 1=1: slave id is 2
	call	Delay32
	mov	al,01h			; ICW4 to both controllers
	out	21h, al 		; bit 0=1: 8086 mode
	call	Delay32
	out	0A1h, al
	call	Delay32
	mov	ax,cx
	out	0A1h,al
	mov	al,ah
	out	021h,al
	mov	ecx, 1000
      @@:
	call	Delay32
	loop	@B

	cli
	mov	al, 0ffh		;mask irq
	out	0A1h, al
	out	021h, al
	call	Delay32
	lidt	[idt]
	mov	al,20h
	out	64h,al
	in	al,60h
	or	al,1b
	mov	bl,al
	mov	al,60h
	out	64h,al
	mov	al,bl
	out	60h,al
	mov	al, 0aeh
	out	64h, al
	mov	al, 0			;unmask
	out	021h,al
	sti
	;enable keyboard irq
	mov	[keycount],0
	mov	[keystatus],0
	retn

Empty8024:
in al, 64h
test al,1
jz empty1
in al, 060h
jmp Empty8024
empty1:
test al,2
jnz Empty8024
retn 4

Delay32:
	jmp	.2
     .1:
	jmp	.3
     .2:
	jmp	.1
     .3:
	retn

detectcpu:
	and	dword[CPU], 0
	pushfd
	or	byte[esp+2],32
	popfd
	pushfd
	pop	eax
	shr	eax, 22
	jnc	nocpuid
	xor	eax, eax
	inc	eax
	cpuid
	test	edx, 1
	jz	nofpu
	test	edx, 1 SHL 15
	jz	nocmov
	test	edx, 1 SHL 23
	jz	nommx
	test	edx, 1 SHL 25
	jz	nosse
	test	edx, 1 SHL 26
	jz	nosse2
	or	dword[CPU], HASSSE2
     nosse2:
	or	dword[CPU], HASSSE
     nosse:
	or	dword[CPU], HASMMX
     nommx:
	or	dword[CPU], HASCMOV
     nocmov:
	or	dword[CPU], HASFPU
     nofpu:
	or	dword[CPU], HASCPUID
     nocpuid:
	retn

include "idt.inc"

