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

decimal

\needs sys vocabulary sys
also sys also definitions
20 constant max#files

: open-block-file	( str -- fid )
	dup read fopen dup 0=
	if ." Can't open " drop ".  abort  ( )
	then	( str fid )
	nip ;

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 <> abort" Disk error"  ;
: (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
: (cold-hook	(cold-hook install-block-io  ;
forth definitions


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

previous previous definitions
