/*
  Filename   : Compute.s
  Author     : Gary M. Zoppetti
  Course     : CSCI 370
  Description: Compute (9x - 3) / 5 for an inputted "x"
               Build with "gcc -m32 -no-pie Compute.s -o Compute
*/

/**********************************************************/
// Data is generally placed in the .data section
	.data
prompt:
	.string "Please enter x ==> "
	
formatSpec:
	.string "%d"
	
output:	
	.string "(9x - 3) / 5 = %d\n"
	
/**********************************************************/
// Code must be placed in the .text section
	.text
// Mark 'main' as global so it's callable from another module
	.globl	main

main:
	pushl	%ebp
	movl	%esp, %ebp
	# Save callee save register %ebx
	#  (although we're not using it in this code)
	pushl	%ebx
	# Allocate space for local variable x (at %ebp - 8)
	subl	$4, %esp

	pushl	$prompt
	call	printf

	# Compute and push address of x
	leal	-8(%ebp), %eax
	pushl	%eax
	pushl	$formatSpec
	call	scanf

	# Push value of x
	pushl	-8(%ebp)
	call	computeF

	# Output result
	pushl	%eax
	pushl	$output
	call	printf

	# Return 0 from main
	movl	$0, %eax

	# Restore ebx
	movl	-4(%ebp), %ebx
	movl	%ebp, %esp
	popl	%ebp

	ret

/**********************************************************/
// Functions
computeF:
	pushl	%ebp
	movl	%esp, %ebp
	# Again, save ebx
	pushl	%ebx

	# Compute 9x - 3	
	movl	8(%ebp), %eax
	leal	-3(%eax, %eax, 8), %eax

	# Divide by 5
	# Convert long to quad, sign extending %eax into %edx
	cltd
	movl	$5, %ecx
	# Will place quotient in %eax
	idivl	%ecx
	
	# Restore ebx
	movl	-4(%ebp), %ebx
	movl	%ebp, %esp
	popl	%ebp

	ret
