#!/usr/bin/python
#
# $Id: bin2c.py,v 1.2 2006/02/28 20:31:03 jlivesey Exp $
#
# This take a binary file and outputs a character string named for the
# file, where each byte is the acii of a character in the input file
#
# % od -c foo
#   0000000   a   b   c   d  \n
#   0000005
# % ./bin2c.py foo bar
# % cat bar
#   unsigned char foo[] = {
#       0x61, 0x62, 0x63, 0x64, 0x0a, 
#   };
#

import os, sys, getopt

#
# Output and error message and a usage message if the number of
# arguments is incorrect.
#
def usage(err=""):
  if err != "":
    sys.stderr.write(err+'\n')
  sys.stderr.write("Usage: %s <options> [input [output]]\n" % os.path.basename(sys.argv[0]))
  sys.stderr.write("    -n name\n")
  sys.stderr.write("    -o outfile\n")
  sys.exit(0)

try:
  ops, args = getopt.getopt(sys.argv[1:], "n:o:")
except getopt.GetoptError, reason:
  usage(str(reason))

name = "data"

input = sys.stdin
output = sys.stdout
if len(args) == 1:
  input = open(args[0])
  name = args[0]
elif len(args) == 2:
  input = open(args[0])
  name = args[0]
  output = open(args[1], "w")
elif len(args) > 2:
  usage("Too many arguments")

i = name.find('.')
if i != -1:
  name = name[:i]

for op, a in ops:
  if op == '-n':
    name = a
  if op == '-o':
    output = open(a, "w")

i = input.read()
#
# Write the start of the character vector
#
output.write("unsigned char %s[] = {\n    " % name)

#
# Initialise the column number.
#
col = 0
s = ""

#
# Write the character data, inserting a newline at col 12.
#
for x in i:
    output.write("0x%02x, " % ord(x))
    if col == 11:
        output.write("\n    ")
        col = 0
    else:
       col = col + 1
  
#
# Write the end of the character vector
#
output.write("\n};\n")

# eof
