; File: p1example.asm
;
; This assembly language program was generated by an expression
; "compiler" to compute the expression "3 + 4 * 5 / 3". The
; comments (including this sentence) were added later.
;
; (Note: set tab stop to 8 for cleaner fomatting.)
;
; Compile with:
;   nasm -f elf p1example.asm
;   gcc p1example.o
;

; Declare some external functions 
; 
	extern printf			; the C function we'll call

	SECTION .data			; Data section. "static" values go here.

printf_ctrl:	
	db "%d", 10, 0			; ctrl string to print an int value + newline.



	SECTION .text			; Code section.

	global main			; allows main to be called from elsewhere
main:
	push	ebp			; set up stack frame
	mov	ebp,esp

	push	DWORD 3			; push numbers on the stack
	push	DWORD 4
	push	DWORD 5			
	pop	ecx			; ECX <- 5
	pop	eax			; ECX <- 4
	imul	ecx			; EDX:EAX <- EAX * ECX
	push	eax			; push 20 on the stack
	push	DWORD 3			 
	pop	ecx			; ECX <- 3
	pop	eax			; EAX <- 20
	cdq				; Sign extend EAX into EDX	
	idiv	ecx			; EAX <- EDX:EAX / ECX 
	push	eax			; push 6 on the stack
	pop	eax
	add	[esp], eax		; add 6 to 3, store result in stack

	; Answer should be at the top of the stack
	push	dword printf_ctrl	; address of ctrl string
	call	printf			; Call C function
	add	esp, 8			; pop 2 args from stack

	mov	esp, ebp		; takedown stack frame
	pop	ebp			;   same as leave op

	ret

