// This may look like C code, but it is really -*- Asm -*-
/*
 *  smoke16/src16/vfprintf.s - Part of a sub-minimal SMOKE-16 I/O library.
 *  $Revision: 1.3 $
 *  Copyright 2000, Benjamin Sittler
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <smoke16/asm.h>

	.rdata
LC_0x:	.zstring "0x"

	.text
        .align 1
// int vprintf(char *fmt, va_list arg)
	.global _vprintf
_vprintf:
	mov %a1, %a2
	mov %a0, %a1
	mov [_stdout], %a0
// int vfprintf(FILE *stream, char *fmt, va_list arg)
	FUNCTION(_vfprintf)
	push %t0 // stream
	push %t1 // fmt
	push %t2 // arg
	push %t3 // count
	push %t4 // alt
	mov %a0, %t0
	mov %a1, %t1
	mov %a2, %t2
	mov %0, %t3
vfprintf0:
	mov %0, %t4
	sethi 0, %a0
	movb [%t1], %a0
	add 1, %t1
	cmp %a0, %0
	be vfprintfN
	mov '%', %a1
	cmp %a0, %a1
	be vfprintf3
	b vfprintf2
vfprintf1:
	mov %a1, %a0
vfprintf2:
	mov %t0, %a1
	call _fputc
	cmp %a0, %0
	bl vfprintfN
	add 1, %t3
	b vfprintf0
vfprintf3:
	movb [%t1], %a0
	add 1, %t1
	cmp %a0, %0
	be vfprintf1
	cmp %a0, %a1
	be vfprintf2
	movb '#', %a1
	cmp %a0, %a1
	be vfprintf_alt
	movb 'd', %a1
	cmp %a0, %a1
	be vfprintf_d
	movb 'x', %a1
	cmp %a0, %a1
	be vfprintf_x
	movb 'i', %a1
	cmp %a0, %a1
	be vfprintf_d
	movb 's', %a1
	cmp %a0, %a1
	be vfprintf_s
	movb 'c', %a1
	cmp %a0, %a1
	be vfprintf_c
	movb 'p', %a1
	cmp %a0, %a1
	be vfprintf_p
	b vfprintf2

vfprintf_alt:
	mov 1, %t4
	mov '%', %a1
	b vfprintf3

vfprintf_p:
	mov 1, %t4
vfprintf_x:
	cmp %0, %t4
	be vfprintf_x1
	mov LC_0x, %a0
	mov %t0, %a1
	call _fputs
	add %a0, %t3
vfprintf_x1:
	mov [%t2], %a0
	add 2, %t2
	mov %t0, %a1
	call _fprintx
	add %a0, %t3
	b vfprintf0

vfprintf_d:
	mov [%t2], %a0
	add 2, %t2
	mov %t0, %a1
	call _fprintd
	add %a0, %t3
	b vfprintf0

vfprintf_c:
	mov [%t2], %a0
	add 2, %t2
	b vfprintf2

vfprintf_s:
	mov [%t2], %a0
	add 2, %t2
	mov %t0, %a1
	call _fputs
	cmp %a0, %0
	bl vfprintf0
	add %a0, %t3
	b vfprintf0

vfprintfN:
	mov %t3, %a0
	pop %t4
	pop %t3
	pop %t2
	pop %t1
	pop %t0
	RET
