\ This program converts a binary file into a form suitable for downloading
\ to a Data-IO prom programmer.  The format used is Intel Hex Format,
\ which is select code 83 on the Data-IO.
\ 
\ To use:
\ % forth hexify.fth -s "hexify your-binary-file-name" >filename.hex

\ TODO: use new record formats to support >64K:
\ : bb AAAA 02 SSSS dd dd dd dd ... cc          Address is (SSSS <  4) + AAAA
\ : bb AAAA 04 HHHH dd dd dd dd ... cc          Address is (HHHH < 16) + AAAA
\ The SSSS and HHHH portions of the address are "sticky", applying to
\ subsequent (type 00) records.

hex

10 constant bytes/line
variable out-addr
create line-buf 64 allot
variable outfile
variable checksum
variable end-of-file?

: .2	(s u -- )	h# ff and s>d <# # # #> 2dup upper type  ;
: .4	(s u -- )	s>d <# # # # # #> 2dup upper type  ;

: get-line
	bytes/line 0 do h# ff line-buf i + c! loop
	bytes/line 0
	do	ifd @  fgetc  dup -1 =
		if	drop  end-of-file? on  leave
		else	line-buf i + c!
		then
	loop ;
: put-line
	bytes/line  checksum !
	." :"  bytes/line .2
	out-addr @ 8 rshift h# ff and checksum +!
	out-addr @ h# ff and checksum +!
	out-addr @ .4 ." 00"
	bytes/line  0
	do	line-buf i + c@  dup checksum +!  .2
	loop
	checksum @ ff and  100 swap -  .2 cr
	bytes/line out-addr +! ;
: (hexify	( -- )
	end-of-file? off
	0 out-addr !
	begin	get-line  put-line
		end-of-file? @
	until
	." :00000001FF" cr
	ifd @ fclose ;
: hexify	( "input-file-name" -- )
	hex reading (hexify  ;
