#!/usr/bin/python

import os, sys, string

# converts any .c file that contains a block of data (usually a texture file)
# on stdin and dumps on stdout the raw data from that.
# Tolerates quite a bit of non-data in the .c file, such as the output of
# rgb2c or sliutil -d.

# With command-line argument, also handles .s

lines = sys.stdin.readlines()

dotS = 0

if ( len( sys.argv) > 1 ):
  dotS = 1;

out = [];

for l in lines:

  if ( dotS ):
    if ( string.find( l, ".byte" ) == -1 ):
      continue;    
    
  if ( string.find( l, "MWERKS" ) != -1 ): continue;
  if ( l[0] == "#" ): continue;
  if ( l[0] == "*" ): continue;  
  if ( l[0] == "}" ): continue;

  if ( len(l) < 2 ): continue;

  if ( l[1] == "*" ): continue;  

  if ( len(l) < 8 ): continue;

  if ( string.find( l, "/*" ) != -1 ): continue;
  if ( string.find( l, "|" ) != -1 ): continue; 
  if ( string.find( l, "+" ) != -1 ): continue;
 
  if ( string.find( l, "*/" ) != -1 ): continue;
  if ( string.find( l, "FILE" ) != -1 ): continue;
  if ( string.find( l, "unsigned" ) != -1 ): continue;
  if ( string.find( l, "static" ) != -1 ): continue;

  s = string.split(l, ',')

  if ( len( s ) < 2 ): continue;

#  print "HI!"

#  print l
  for h in s:
#    print "[" + h + "]"
    if ( dotS ):
      if ( string.find( h, ".byte" ) != -1 ):
        h = h[(string.find( h, ".byte" ) ) + 5: ];
    if ( dotS or string.find(h, "\n") == -1  ):
      if ( h != "" ):
        if ( len( h ) <= 7 ):
          out.append(string.atoi(h, 16))
#          print "{ " +  str( string.atoi( h, 16 )) + " } " 
          
        else:
          # clip off the 0x, do two bytes extra
          long = 1;
          part1 = h[:7]
          part2 = "0x" + h[7:]

          print part1;
          
          out.append( string.atoi(part1, 16));
          out.append( string.atoi(part2, 16));
          
# figure out if this is shorts or chars

shorts = 0;

for i in out:
  if ( i > 256 ): shorts = 1

for i in out:

  if shorts:
    sys.stdout.write(chr(i >> 8 ) );
    sys.stdout.write(chr(i & 255 ) );
  else:
    sys.stdout.write(chr(i));


