#
# <20180722.1845.19>
#
# A small collection of routines to help read binary files and
# pull them apart.
#
proc OpenBinaryFile {filename} {
  set f [open $filename]
  chan configure $f -translation binary
  return $f
}

# Read n bytes from f
proc BinaryRead {n f} {
  set rtn 0
  switch -exact $n {
    2 {set conv "s"}
    4 {set conv "i"}
    8 {set conv "w"}
    default {return -code error "BinaryRead only handles 2,4 or 8 bytes"}
  }
  binary scan [chan read $f $n] $conv rtn
  return $rtn
}

proc ByteToHex { char } {
  binary scan $char c c1
  return [format %2x $c1]
}

# read a normal or a UNC string, null terminated or
# to end of file or fixed size.
#
proc GetArbNullTermString {f offset {size {}}} {
  # test if UNC or not
  chan seek $f $offset start
  if {[BinaryRead 2 $f] <= 0xff} {
    chan configure $f -encoding unicode
  }
  set result [GetNullTermString $f $offset $size]
  chan configure $f -encoding [encoding system]
  return $result
}
  
proc GetNullTermString { f offset {size {}}} {
  chan seek $f $offset start
  set result ""
  set count 0
  while { [set c [chan read $f 1]] != "\x00" } {
    append result $c
    if {[chan eof $f] || ($size != {} && [incr count] >= $size)} {
      break
    }
  }
  return $result  
}
proc GetNullTermStringUnc { f offset {size {}}} {
  chan configure $f -encoding unicode
  set result [GetNullTermString $f $offset $size]
  chan configure $f -encoding [encoding system]			  
  return $result  
}
 
