SECTION "UNHEXIT"

GET "NLIBHDR"

LET START() BE
$( LET V = VEC 100
   LET N, R, S = ?, ?, ?
   LET OOUT = OUTPUT()
   LET buf = v
   let oin = input()
   LET cnt = ?

   s := findinput("SYSIN")
   IF s=0 DO
   $( writes("*nCan*'t find input.*n")
      stop(25)
   $)

   n := findoutput("HUNKOUT")
   IF n=0 DO
   $( writes("*nCan't find output.*n")
      selectinput(s)
      endread()
      selectinput(oin)
      stop(30)
   $)

   selectinput(s)
   selectoutput(n)

   more: cnt := 0
   FOR i = 1 TO 100 DO
   $( UNLESS readw(@r) DO BREAK
      buf!i := r
      cnt := cnt+1
   $)
   UNLESS cnt=0 writewords(buf+1, cnt)
   UNLESS cnt<100 GOTO more

   WHILE GCH(@R) DO LOOP

   endwrite()
   endread()
   selectoutput(oout)
   selectinput(oin)
$)

AND READW(AR) = VALOF
$( LET BL = ?
   LET BH = ?

   UNLESS GETB(@BL) RESULTIS FALSE
   UNLESS GETB(@BH) RESULTIS FALSE

   !AR := (BH<<8) | BL
   RESULTIS TRUE
$)

AND GETB(AB) = VALOF
$( LET NL = ?
   LET NH = ?

   UNLESS GCH(@NH) RESULTIS FALSE
   UNLESS GCH(@NL) RESULTIS FALSE

   !AB := (NH<<4) | NL
   RESULTIS TRUE
$)

AND GCH(AN) = VALOF
$( LET C = RDCH()

   UNTIL C=endstreamch | ('0'<=C<='9') | ('A'<=C<='F') DO C := RDCH()

   IF C=endstreamch RESULTIS FALSE

   !AN := C>='0' -> C-'0', C-'A'+10
   RESULTIS TRUE
$)


AND writewords(v, n) BE
$( LET bh = ?

   FOR i = 0 TO n-1 DO
   $( bh := (v!i)>>8
      binwrch(v!i)
      binwrch(bh)
   $)
$)