// This may look like C code, but it is really -*- Asm -*-
/*
 *  smoke16/src16/fscand.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.
 *
 */

// NOTE: This code depends on the digits '0' through '9' being
// contiguous and in order in the execution character set. Both ASCII
// and The Blue Madness satisfy this requirement.

#include <smoke16/asm.h>

	.text
	.align 1
// int scand(int *d)
	.global _scand
_scand:	mov [_stdin], %a1
// int fscand(int *d, FILE *stream)
	FUNCTION(_fscand)
	push %t0 // %t0 is a copy of d
	push %t1 // %t1 is a copy of stream
	push %t2 // %t2 is the sign
	push %t3 // %t3 is the magnitude
	push %t4 // %t4 is a digit counter
	push %t5 // %t5 is the current digit
	mov %a0, %t0
	mov %a1, %t1
	mov 1, %t2
	mov %0, %t3
	mov %0, %t4
	mov %a1, %a0
	call _fgetc // read the first character
	mov '-', %a1 // if it's '-', negate the sign
	cmp %a0, %a1
	bne fscand1
	sub 2, %t2
fscand0:
	mov %t1, %a0
	call _fgetc // read the next character
fscand1:
	cmp %a0, %0
	bl fscand3 // quit on EOF
	mov '9', %a1
	cmp %a0, %a1
	bg fscand2 // quit if it's > '9'
	sub 9, %a1
	sub %a0, %a1, %t5
	bl fscand2 // quit if it's < '0'
	mov %t3, %a0
	mov 10, %a1
	call __umul
	add %t5, %a1, %t3 // update magnitude
	add 1, %t4 // increment digit counter
	b fscand0
fscand2:
	mov %t1, %a1
	call _ungetc // put back the next character
	cmp %a0, %0
	bl fscand5
fscand3:
	cmpl %0, %t4
	be fscand5
	mov %0, %a0
	b fscand6
fscand5:
	mov -1, %a0
fscand6:
	cmp %t2, %0
	bge fscand4
	sub %0, %t3, %t3 // negate the magnitude
fscand4:
	mov %t3, [%t0] // store the result
	pop %t5
	pop %t4
	pop %t3
	pop %t2
	pop %t1
	pop %t0
	RET
