;author: Beau Johnston 	Email: bjohnst8@gmail.com 
;about: This program attempts to act as a basic calculator

%include "system.inc"
section  .data

input dd 0 ;set input buffer to zero
write dd 0 ;set write buffer to zero
totalResult dd 0;
newVal dd 0;

section .text
global _start
_start:
mov rax, [totalResult]
mov rax, 0
mov [totalResult], rax
houseKeeping:
call readNum
mov rax, [input]
and rax, 7Fh
cmp rax, 0 ; if the next character is null
je continue
cmp rax, 10 ; if enter pressed
je continue
cmp rax, 32 ; if the next character is a space
je continue
sub rax, '0'
mov [newVal], rax
mov rax, 0
mov rbx, 10
mov rax, [totalResult]
mul rbx
mov [totalResult], rax
mov rax, [newVal]
add [totalResult], rax
jmp houseKeeping

continue:
mov rax, [totalResult]
push rax
call writenum
jmp exit

exit:
mov rax, 1	; system call number (sys_exit)
int 0x80	; call kernel

readNum:
mov rdx, 3	;message length
mov rcx, input	;message to read
mov rbx, 0	;file descriptor (stdin)
mov rax, 3	;system call number (sys_read)
int 0x80	;call kernel	
ret

writenum:
push	rbp	; Function entry sequence
mov rbp, rsp
sub rsp, 16	; Leave space for a local variable
mov rax, [rbp+16] ; Get first argument off the stack
mov rdx, 0	; Clear high order bits
mov rbx, 10	; Store 10 for divide operation
div rbx 	; Divide edx/eax by ebx (10)
mov [rbp-16], rdx ; Store number to display on stack
cmp rax, 0	; Is there anything left to do?
je writenum1	; Jump if nothing left
push rax	; Setup first (and only) parameter
call writenum	; Write the number out
add rsp, 16	; Clean up the stack (2 bytes used)

writenum1:  
mov rdx, [rbp-16] ; Get number to display off stack
add rdx, '0'	; Convert binary number to ASCII
call print1char
mov rsp, rbp	; Function exit sequence
pop rbp
ret

print1char:
mov [write],rdx	; Move al to memory
mov rdx,1	; message length
mov rcx,write	; message to write
mov rbx,1	; file descriptor (stdout)
mov rax,4	; system call number (sys_write)
int	0x80	; call kernel
ret
