/
/ PDP-11 C
/ Stdio.
/
/ Close a file.
/

	.globl	fclose

/
/ fclose(ioptr);
/ FILE *ioptr;
/
/ Returns 0 if all ok. Returns -1 on error.
/ FCS style error code is saved in _ferr.
/

fclose:	jsr	r0,_save	/Get stack frame.
	sub	$22.,sp		/
	mov	12(r5),r4	/Pick up ioptr.
	call	_ckiov		/Check ioptr validity
	clr	_ferr		/No errors.

/
/ If NOS and not UBF, flush out the
/ buffer.
/

	mov	(r4),r0		/Get flags.
	bit	$VF_NOS,r0	/"n"
	beq	0f		/No
	bit	$VF_UBF,r0	/Yes, is it "u"
	bne	0f		/Yes
	call	_flush		/Flush out line buffer.

/
/ Flush block buffer, if necessary.
/

0:	bit	$VF_REC,r0	/Record device?
	bne	2f		/Br if yes.
	clr	r3		/No IO.WAT needed.
	bit	$VF_OUT,r0	/Is this an output IOV.
	beq	1f		/No, no need to IO.WAT.
	tst	V_RBYT(r4)	/Flush last block out.
	beq	0f		/If
	call	_wvb		/Anything in the block buffer.

/
/ Build IO.WAT parameter block.
/ This may not be used.
/

0:	mov	sp,r3
	mov	$5+[10<<8.],(r3)+
	mov	r4,(r3)
	add	$V_FNAM,(r3)+
	mov	$7+[2<<8.],(r3)+
	mov	r4,(r3)
	add	$V_FVER,(r3)+
	mov	$4+[16<<8.],(r3)+
	mov	r4,(r3)
	add	$V_RTYP,(r3)+
	mov	$1+[2<<8.],(r3)+
	mov	$_uic,(r3)+
	mov	$2+[2<<8.],(r3)+
	mov	$_pro,(r3)+
	clr	(r3)
	mov	sp,r3

/
/ Deaccess files.
/ Write attributes.
/

1:	bit	$VF_FIL,(r4)	/File accessed on lun.
	beq	2f		/Br if not.

	clr	-(sp)		/Issue deaccess QIO.
	clr	-(sp)		/
	clr	-(sp)		/
	clr	-(sp)		/
	mov	r3,-(sp)	/This may be NULL.
	clr	-(sp)		/
	mov	$IO.DAC,r0	/
	call	_qiow		/
	bcc	2f		/Br if no errors.
	mov	r0,_ferr	/Save error code.

/
/ Free buffers.
/ Then free the IOV.
/

2:	mov	V_BBUF(r4),r0	/Block buffer.
	beq	0f		/Br if none.
	call	_free		/Free it.

0:	mov	V_RBUF(r4),r0	/Record buffer.
	beq	0f		/Br if none.
	call	_free		/Free it

0:	mov	V_LUN(r4),r0	/Clear entry in LUN table.
	asl	r0		/
	clr	_luns-2(r0)	/

	mov	r4,r0		/Free IOV.
	call	_free		/

	mov	_ferr,r0	/Return -1 if any errors.
	beq	0f		/Br if all ok.
	mov	$-1,r0		/

0:	jmp	_ret		/Finis.
