\ The low level I/O used to implement standard Forth BLOCKs

decimal
system definitions
20 constant max#files

: open-block-file	( str -- fid )
	read fopen dup 0= if d# -275 throw then ;

nuser default-block-fid         \ File referenced by block-fid=0
0 default-block-fid !

: map-fid	( fid -- fid' )
	?dup  0=
	if	default-block-fid @  0=
		if	p" forth.blk"  open-block-file  default-block-fid !
		then
		default-block-fid @
	then ;

\ Seek to the correct starting address and prepare the arguments
\ to the gem read or write call
: setio		( address block# fid -- address b/buf fid )
	map-fid                        ( address block# fid' )
	swap b/buf *  over fseek       ( address fid )
	b/buf swap ;

: ?disk-abort	( #transferred -- )	b/buf <> if d# -37 throw then  ;
: (read-block)	( addr blk# file -- )	setio fgets  ?disk-abort  ;
: (write-block)	( addr blk# file -- )	setio fputs  ;

: install-block-io	( -- )
	['] (read-block)  is read-block
	['] (write-block) is write-block
	0 default-block-fid ! ;
install-block-io
forth definitions
: (cold-hook	(cold-hook install-block-io  ;
	' (cold-hook is cold-hook

\ Seek to end to find size
: file-size	( fid -- l )	map-fid  fsize  ;
: .file		( fid -- )	drop ." File name unknown"  ;

forth definitions
