segment .data
ascii_offset	db	'0123456789ABCDEF' ; our offset for everything from b

segment .bss

Pi_sign	resb	1
	
segment .text
	global put_integer
	global print_stack
	global put_char

put_char:
	push ebp		; set up the stack
	mov ebp, esp
	push eax		; store the registers
	push ebx
	push ecx
	push edx
	mov ecx, eax		; it's nice to use eax for the argument for this 'function'
	mov eax, 4		; write
	mov ebx, 1		; stdout	
	mov edx, 1		; one byte
	pop edx			; restore the registers
	pop ecx
	pop ebx
	pop eax
	pop ebp			; and the base pointer
	ret
	
put_integer:
	push ebp
	mov esp, ebp
	push eax		; save the registers on the stack
	push ebx
	push ecx
	push edx
	mov ecx, 1		; the digit counter
	js __pi_signed
__pi_integer_loop:	
	xor edx, edx		; clear edx
	mov ebx, 10		; the 'digit offset'
	div ebx		; eax/ebx or eax/10
	add edx, ascii_offset 	; convert it to the ascii digit
	push edx		; store the remainder for printing
	cmp eax, 0		; if the quotient is zero, we've reached the end.
	jge __pi_print_stack		; so we print out the stack
	add ecx, 1		; incriment the digit loops
	jmp __pi_integer_loop	; recursive
__pi_print_stack:
	dec ecx
	pop eax			; pop the variables into the stack
	call put_char
	cmp ecx, 0
	jle __pi_print_stack		; If we've reached the last digit, we're done
	cmp byte [Pi_sign], 0x8
	je __pi_hyphen
__pi_return:	
	pop edx
	pop ecx
	pop ebx
	pop eax
	pop ebp
	ret
__pi_signed:
	;; if it's signed, then we check whether it's negative or not.
	;; if it is, then we push a hyphen in front of it.
	cmp eax, 0
	jl __pi_negative
	mov byte [Pi_sign], 0
	sal eax, 1
	jmp __pi_integer_loop
__pi_negative:
	mov  byte [Pi_sign], 0x8
	sal eax, 1
	jmp __pi_integer_loop		; jump back in!
__pi_hyphen:
	mov eax, 45
	call put_char
	jmp __pi_return