global _start

section .data
	outbuffer	db	'0000000000', 10,10

section .text

_start:

	push 13				; PUSH WANTED FIBBONACCI MEMBER INDEX HERE
						; REMEMBER, IT MUST BE (N - 1)
						; SO IF YOU WANT 14th MEMBER (LIKE HERE), YOU PUSH 13
	call fibo
	call printint

	jmp exit

exit:
	mov		eax, 01h		; exit()
	xor		ebx, ebx		; errno
	int		80h

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	
fibo:
	push    ebp         ; Retrieve parameter and put it
	push    ebx         ; Save previous parameter
	mov     ebp,esp     ; into EBX register
	add     ebp,12      ;
	mov     ebx,[ebp]   ; EBX = Param
	
	cmp     ebx,1       ; Check for base case
	jle     base        ; It is base if (n <= 1)
	
	lea  ecx,[ebx-1]
	push ecx            ; push N-1
	call fibo   		; Calculate fibo for (EBX - 1)
	pop  ecx            ; remove N-1 off the stack
	
	push eax            ; save the result of fibo(N-1)
	lea ecx,[ebx-2]
	push ecx            ; push N-2
	call fibo   		; Calculate fibo for (EBX - 2)
	pop ecx             ; remove N-2 off the stack
	pop ecx             ; ecx = fibo(N-1)
	add eax,ecx         ; eax = fibo(N-2) + fibo(N-1)
	
	jmp end
	
	base:               ; Base case
		mov eax,1           ; The result would be 1
	
	end:
		pop     ebx         ; Restore previous parameter
		pop     ebp         ; Release EBP
		ret


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

printint:
	pushad
	mov ecx, 10d
	mov	edi, 10d
	mov ebx, outbuffer+9
	innerprintloop:
		mov edx, 0h
		div edi
		add edx, '0' ; '0' - 0x48h
		mov [ebx], dl
		dec ebx
		loop innerprintloop
	mov ecx, outbuffer
	mov edx, 11
	call write
	popad
	ret

read:
	;move where to read to ecx
	;move length to edx 
	mov		eax, 03h		; 3 is recognized by the system as meaning "read"
	mov		ebx, 00h		; read from standard input
	int		80h				; call the kernel
	ret
	
write:
	;move what to write to ecx
	;move length to edx
	mov		eax, 04h		; the system interprets 4 as "write"
	mov		ebx, 01h		; standard output (print to terminal)
	int		80h				; call the kernel
	ret