!
!	MAKE NICE BINARY FROM NASTY BINARY
!
!	8/15/79
!
	DIM	STARTAD$/:FF,:FF/, ADDRESS, MAXAD

	DIM	UPPER(200),LOWER(200),SKIP$/0/,START$/1/,LOAD$/2/,GO$/3/
	DIM	TWOB$/0,0/, BYTE$/0/, I, J, K, L
	DIM	FILE$[100], COMMAND$[10], TOP/0/
	DIM	FROM, DEST, CURPOS, OLDPOS
	DEF	MSB(L)=INT(L/256)
	DEF	LSB(L)=INT(L-MSB(L)**8)

	CREATE	#1, "BINTEMP.TMP"
	CLOSE	#1
	OPEN	#1, "BINTEMP.TMP"
	DELETE	"BINTEMP.TMP"

	PRINT	"*** MAKE NICE BINARY PROGRAM 10/06/79 ***"

10	INPUT	"COMMAND? " COMMAND$
	IF COMMAND$="" THEN 10
	COMMAND$=COMMAND$[1,1]

	IF COMMAND$="L" THEN 100
	IF COMMAND$="B" THEN 200
	IF COMMAND$="P" THEN 300

	PRINT	"THE COMMANDS ARE: L<OAD> B<INRY MAP> P<UNCH>"
	GOTO	10


100	! LOAD FILE

	INPUT	"LOAD WHAT FILE? " FILE$
	OPEN	#2, FILE$

	CURPOS	=0

110	RESTORE	#2, CURPOS
	READ	#2, BYTE$
	ON	BYTE$[1]+1 GOTO 120, 121, 122, 123

	PRINT	"UNEXPECTED LOAD RECORD AT";CURPOS;" (";BYTE$[1];")"
	CLOSE	#2
	STOP

120	READ	#2, TWOB$
	CURPOS	=CURPOS+3+TWOB$[1]**8+TWOB$[2]
	GOTO	110

121	CURPOS	=CURPOS+5
	READ	#2, TWOB$
	INPUT	"PRESERVE START ADDRESS? " FILE$
	IF	LEN(FILE$)=0 OR FILE$[1]="Y"
	THEN	STARTAD$=TWOB$
	GOTO	110

122	GOSUB	124
	GOTO	110

123	GOSUB	124
	CLOSE	#2
	GOTO	10

124	! HASSLE LOAD RECORDS

	READ	#2, TWOB$
	ADDRESS=TWOB$[1]**8+TWOB$[2]
	READ	#2, TWOB$
	MAXAD	=ADDRESS+TWOB$[1]**8+TWOB$[2]-1

	IF	ADDRESS-1=MAXAD THEN CURPOS=CURPOS+5 \ RETURN

!	INSERT RECORDS INTO TABLE OF RECORDS

	IF	TOP=0
	THEN	TOP=TOP+1 \
		LOWER(TOP)=ADDRESS \
		UPPER(TOP)=MAXAD
	ELSE	FOR I=1 TO TOP \
		IF LOWER(I)<=ADDRESS AND UPPER(I)>=ADDRESS
		THEN	IF UPPER(I)<MAXAD
			THEN	UPPER(I)=MAXAD FI \
			GOTO 125 FI \
		IF UPPER(I)>=MAXAD AND LOWER(I)<=MAXAD
		THEN	IF LOWER(I)>ADDRESS
			THEN	LOWER(I)=ADDRESS FI \
			GOTO	125 FI \
		NEXT	I \
		TOP = TOP + 1 \
		LOWER(TOP)=ADDRESS \
		UPPER(TOP)=MAXAD

125	RESTORE #1, ADDRESS
	FOR	I=ADDRESS TO MAXAD
	READ	#2, BYTE$
	WRITE	#1, BYTE$
	NEXT	I

	CURPOS	=CURPOS+5+MAXAD-ADDRESS+1
	RETURN


200	PRINT	"FROM","UP TO"
	PRINT	"====","====="

	FOR	I=1 TO TOP
	PRINT	HEX$(LOWER(I)),HEX$(UPPER(I))
	NEXT	I
	PRINT
	GOTO	10

300	INPUT	"OUTPUT FILE=" FILE$
	CREATE	#2,FILE$
	WRITE	#2,START$,STARTAD$
	STARTAD$[1]=STARTAD$[1] XOR :FF
	STARTAD$[2]=STARTAD$[2] XOR :FF
	WRITE	#2,STARTAD$
	CURPOS	=5

	GOTO	311
310	INPUT	"DONE? " FILE$
	IF	FILE$<>"" AND FILE$[1]="Y" THEN 330
311	OLDPOS	=CURPOS
	INPUT	"PUNCH FROM, TO (INCLUSIVE)? " FROM, DEST
	WRITE	#2, LOAD$
	TWOB$[1]=MSB(FROM)
	TWOB$[2]=LSB(FROM)
	WRITE	#2,TWOB$
	TWOB$[1]=MSB(DEST-FROM+1)
	TWOB$[2]=LSB(DEST-FROM+1)
	WRITE	#2,TWOB$

	RESTORE #1, FROM
	FOR	I=FROM TO DEST
	READ	#1, BYTE$
	WRITE	#2, BYTE$
	NEXT	I

	CURPOS	=OLDPOS+5+DEST-FROM+1
	GOTO	310

330	! FINISH FILE OFF
	RESTORE	#2, OLDPOS
	WRITE	#2, GO$
	CLOSE	#2

	END
