/*
 * 5799-WZQ (C) COPYRIGHT IBM CORPORATION 1986
 * LICENSED MATERIALS - PROPERTY OF IBM
 * REFER TO COPYRIGHT INSTRUCTIONS FORM NUMBER G120-2083
 */
/* $Header:gets.s 12.0$ */
/* $ACIS:gets.s 12.0$ */
/* $Source: /ibm/acis/usr/src/lib/libc/ca/stdio/RCS/gets.s,v $ */

	.data
rcsid:	.asciz	"$Header:gets.s 12.0$"
	.text

#define S	r2	/* gets(S) */
#define IOP_CNT	r3
#define IOP_PTR	r4	/* Keep iop_ptr local until filbuf is called. */
#define C	r5
#define CS	r13
#define IOP	r14	/* Keep iop_ptr local until filbuf is called. */

#define CNT	0
#define	PTR	4
#define NEWLINE	012
#define EOF	-1
#define FIRSTSVREG	r12
#define STACKDROP	52 /* ARGSV(16)+LINKSV(20)+REGSV(64)-(FIRSTSVREG*4) */
.data
.align 2		/* Start data on word boundary. */
.globl	_gets
	_gets:	 .long _.gets
.text
.align 2		/* Start text on word boundary. */
.globl	_.gets		/* gets(s) r2 s; */
	_.gets:
		stm	FIRSTSVREG,-STACKDROP(sp)
		ai	sp,sp,-STACKDROP	/* Drop stack ptr. */
		get	IOP,$__iob		/* &_iob[0] */
		get	IOP_CNT,CNT(IOP)	/* load local iop->_cnt */
		get	IOP_PTR,PTR(IOP)	/* load local iop->_ptr */
		cas	CS,S,r0			/* cs = s */
	Lwhile_loop:			/* while((c = getchar(fp)) != '\n' */
		si	IOP_CNT,IOP_CNT,1	/* --iop->_cnt */
		jl	Lfilbuf			/* need more! call filbuf() */
		lcs	C,0(IOP_PTR)		/* c = iop->_ptr */
		inc	IOP_PTR,1		/* iop->_ptr++ */
	Lfilbuf_return:
		inc	CS,1			/* cs++ */
		ci	C,NEWLINE		/* c==\n ? */
		bnex	Lwhile_loop
		stc	C,-1(CS)		/* *cs = c */	

		lis	C,0			/* tmpreg <- zero */
		bx	Lreturn
		stc	C,-1(CS)		/* *cs = '\0', zap newline */
	Lfilbuf:		/* Filbuf called ~1/25-1/50 of the time. */
		put	S,  STACKDROP-16(sp)	/* Put arg word 1 on stack. */
		get	r0,$__filbuf
		balix	r15,_._filbuf
		cas	r2,IOP,r0		/* filbuf(iop) setup */
		
		cas	C,r2,r0			/* c = filbuf() */
		get	S,  STACKDROP-16(sp)	/* Restore arg word 1. */
		ci	C,EOF			/* Was EOF returned? */
		jeq	Leof
		get	IOP_CNT,CNT(IOP)	/* Get new local iop->_cnt */
		bx	Lfilbuf_return
		get	IOP_PTR,PTR(IOP)	/* Get new local iop->_ptr */
	Leof:
		c	CS,S			/* Put any chars in buffer? */
		jne	Lreturn_no_newline	/* if (cs!=s) return(!EOF). */
		lis	r2,0			/* Return a null */
		j	Lreturn_null
	Lreturn_no_newline:
		lis	C,0			/* tmpreg <- 0 */
		bx	Lreturn_null
		stcs	C,0(CS)			/* *cs = '\0' */
	Lreturn:
		put	IOP_CNT,CNT(IOP)	/* Put local cnt back. */
		put	IOP_PTR,PTR(IOP)	/* Put local ptr back. */
/*		cas	r2,S,r0		return(s), s still in r2. */
	Lreturn_null:
		lm	FIRSTSVREG,0(sp)		
		brx	r15
		ai	sp,sp,STACKDROP		/* Restore caller's sp. */

.short 0xdf07	/* Trace table marker. */
.short 0xdfa8	/* Trace table marker, (first,gpr,flags) */
.short 0x1100+STACKDROP/4	/* trace table nparams, fp, local_offset */

.data
.globl	.oVncs
.set	.oVncs, 0
