%define drive 0x80
%define ploc 0x9000

temp_word: dw 0

_strlen:
	push bp
	mov bp,sp
	mov ax,0
	mov si,[bp+4]
.LSTR:
	mov al,[si]
	cmp al,0
	je .LEND
	inc si
	inc ax
	jmp .LSTR
.LEND:
	leave
	ret

_readfile:
	push bp
	mov bp,sp
	push word [bp+4]
	call _strlen
	add sp,2
	mov [temp_word],ax
	mov al,[temp_word]
	mov [charcount],al
	push word [bp+4]
	call search
	add sp,2
	mov sp,bp
	pop bp
	ret

search:         ; search the filetable for the file
        ;pusha
	push bp
        mov bp,sp

        cmp ax,ax ; to set zero flag
        ;mov di,[bp+18]
        mov di,[bp+4]

        mov bx,0
        cld
        cont_chk:
                mov al,[gs:bx]
                cmp al,'}'

                je complete

                cmp al,[di]
                je chk
                inc bx
                jmp cont_chk

        chk:
                push bx
                mov cx, [charcount]
        check:
                mov al,[gs:bx]
                inc bx

                scasb
                loope check

                je succ

                ;mov di,[bp+18]
                mov di,[bp+4]
                pop bx
                inc bx
                jmp cont_chk

        complete:
                push fail
                call _print
                jmp en
        succ:

                inc bx
                push  bx

                call findsect
        en:
                mov sp,bp
                ;popa
		pop bp
                ret

findsect:	; find the sector containing the given file	
	;pusha
	push bp
	mov bp,sp
	;mov bx,[bp+18]
	mov bx,[bp+4]
	cld
	mov word [sect],0
	mov cl,10
	cont_st:
		mov al,[gs:bx]
		inc bx
		cmp al,','
		jz finish
		cmp al,48
		jl mismatch
		cmp al,58
		jg mismatch
		sub al,48
		mov ah,0
		mov dx,ax
		mov ax,word [sect]
		mul cl
		add ax,dx
		mov word [sect],ax		
		jmp cont_st
		finish:
			push word [sect]
			
			call load 	;load exe in memory

		
			jmp ploc:0000  ;switching to our program 

			;mov dx,[buffer]
			;jmp dx  ;switching to our program 

		mismatch_end:
			mov sp,bp
			pop bp
			;popa
			ret
		mismatch:
			push fail
			call _print
			jmp mismatch_end

load:		;load the specified sector into RAM
	;pusha
	push bp
	mov bp,sp
	
	mov ah,0
	mov dl,0x80
	int 0x13

	;mov ax,[buffer]
	mov ax,ploc
	mov es,ax
	;mov cl,[bp+18] 
	mov cl,[bp+4] 
;DEBUG
;LOAD K
	;mov al,1
	mov al,2
	mov bx,0
	mov dl,drive 
	mov dh,0 
	mov ch,0 
;DEBUG 110
	mov ah,2
	;mov ah,10
	int 0x13
	jnc success
	err:
			push erro
			call _print
	success:
		mov sp,bp
		pop bp
		;popa
		ret

;buffer dw 0
;welcome db "Welcome ! Type help or about to know more",10,13,0
erro db "Error loading sector",10,13,0
fail db "File not found !",10,13,0
query times 30 db 0
;arr times 10 db 0

first_time db 1

nl db 10,13,0
;prompt db 10,13, ">>",0

charcount dw 0

sect dw 0











