%include "calls.inc"
%define NODE_VALUE 0
%define NODE_NEXT 4
%define NODE_SIZE 8
%define BUF_SIZE 8

global _start
extern sint2str		; sint2str.asm

section .bss

buf		resb BUF_SIZE

section .data

newline		db 10
space		db 32

section .text

malloc:
; < (size) > (old address) : -1
	pbegin	0, ebx, esi, edi
	mov	ebx, [ebp+8]	; size

	scall	45, 0
	cmp	ecx, -1
	je	.failed

	mov	esi, eax
	lea	edi, [esi + ebx]

	scall	45, edi
	cmp	ecx, -1
	je	.failed

	cmp	eax, edi
	jne	.failed

	mov	eax, esi
	jmp	.end

.failed:
	mov	eax, -1
.end:
	pend	ebx, esi, edi

push:
; < (value) > : -1
	pbegin	0, ebx, esi
	mov	esi, [ebp+8]	; address of header
	mov	ebx, [ebp+12]	; value

	pcall	malloc, NODE_SIZE
	cmp	eax, -1
	je	.end

	mov	ecx, [esi]
	mov	[eax + NODE_VALUE], ebx
	mov	[eax + NODE_NEXT], ecx
	mov	[esi], eax

	xor	eax, eax
.end:
	pend	ebx, esi

print:
	pbegin	0, ebx
	mov	ebx, [ebp+8]
.loop:
	pcall	sint2str, [ebx + NODE_VALUE], buf
	scall	4, 1, buf, eax
	scall	4, 1, space, 1
	mov	ebx, [ebx + NODE_NEXT]
	cmp	ebx, 0
	jne	.loop

	pend	ebx

_start:
	sub	esp, 4
	mov	dword [esp], 0
	mov	esi, esp

	pcall	push, esi, 1
	pcall	push, esi, 2
	pcall	push, esi, 3
	pcall	push, esi, 4

	pcall	print, [esi]
	scall	4, 1, newline, 1

	jmp .end
.failed:
	scall	1, 1
.end:
	scall	1, 0
