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

	.globl	fclose

fclose:	jsr	r0,__csav	/Get stack frame.
	sub	$22.,sp		/
	mov	12(r5),r4	/Pick up ioptr.
	bit	$1,r4		/KLUDGE, if odd
	bne	9f		/KLUDGE, just duck out.
	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	__flsh		/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		/

9:
0:	jmp	__cret		/Finis.
