
# TODO: this file should probably be merged with libgame/misc.rb

# TODO: move addNullPadding() and removeNullPadding() right into File#(get|put)Characters()

def removeNullPadding(bin)
  bin[0, bin ~= /x00/]
end

def addNullPadding(str, length)
  str = str[0, length] # shorten the string
  str + ("\x00" * (length - str.length)) # add trailing \x00-s
end

# these are mostly taken from libgame/misc.[ch]

class File
  def getChar
    getc.chr
  end
  def getBool
    getc == 1
  end
  def get8
    getc
  end
  def get16be
    (getc << 8) | (getc << 0)
  end
  def get16le
    (getc << 0) | (getc << 8)
  end
  def get32be
    (getc << 24) | (getc << 16) | (getc << 8) | (getc << 0)
  end
  def get32le
    (getc << 0) | (getc << 8) | (getc << 16) | (getc << 24)
  end
  def getChunkName
    getChar + getChar + getChar + getChar
  end
  def getCharacters(length)
    arr = []
    length.times { arr.push(getc) }
    removeNullPadding(arr.pack('c*'))
  end
  
  def putBool(x)
    putc(x ? 1 : 0)
  end
  def put8(x)
    putc(x)
  end
  def put16be(x)
    putc(0xff & (x >> 8))
    putc(0xff & (x >> 0))
  end
  def put16le(x)
    putc(0xff & (x >> 0))
    putc(0xff & (x >> 8))
  end
  def put32be(x)
    putc(0xff & (x >> 24))
    putc(0xff & (x >> 16))
    putc(0xff & (x >>  8))
    putc(0xff & (x >>  0))
  end
  def put32le(x)
    putc(0xff & (x >>  0))
    putc(0xff & (x >>  8))
    putc(0xff & (x >> 16))
    putc(0xff & (x >> 24))
  end
  def putChunk(name, size = -1)
    print(name)
    put32be(size) if size >= 0
  end
  def putCharacters(str, length)
    addNullPadding(str, length)
    print str
  end
end
