include	clib.inc
include stdio.inc

PPROC	fgets, buf:DPTR, count:word, fp:DPTR
	push	si
	push	di
	mov	ax,count
	cmp	ax,0
	jle	fgets_nul
	MLES	di,buf
	mov	si,ax
	dec	si
	jz	fgets_ret
    fgets_loop:
	push	es
	invoke	fgetc, fp
	pop	es
	cmp	ax,-1
	je	fgets_eof
	mov	es:[di],al
	inc	di
	cmp	al,10
	jne	fgets_loop
    fgets_ret:
	xor	al,al
	mov	es:[di],al
	MMOV	dx,es
	mov	ax,word ptr buf
    fgets_end:
	pop	di
	pop	si
	ret
    fgets_eof:
	cmp	di,word ptr buf
	jne	fgets_ret
    fgets_nul:
	xor	ax,ax
	cwd
	jmp	fgets_end
PEND	fgets

	END
