#!/usr/bin/python

import os, sys, string

# This is a utility to let you go surfing through a .o file that contains
# textures you might want.  It assumes that the textures are sli encoded
# and lets you guess at a width and height for the textures.  At the
# end you'll have a series of PPM files that you can browse.

# assumes you have tools/conversions/ in your PATH. 


if ( len (sys.argv) < 2 ):
    print("Usage: extractTextures.py <.o> [frag] [width] [height] ");
    sys.exit( -1 )

inputfile = sys.argv[ 1 ]
nameFrag = "" 
width = 32;
height = 32;

if ( len( sys.argv ) > 2 ):
    nameFrag = sys.argv[ 2 ]

if ( len( sys.argv ) > 3 ):
    width = string.atoi( sys.argv[ 3 ] );

if ( len( sys.argv ) > 4 ):
    height = string.atoi( sys.argv[ 4 ] );

def execute( command ):
    print ( command );
    os.system( command );

def getCommandOutput( command ):
    print ( command )
    temp = os.popen( command, "r" );
    lines = temp.readlines();
    temp.close();
    return lines;


lines = getCommandOutput( "mips-linux-objdump --all-headers " + inputfile );


donorDataOffset = 0;

donorName = [];
donorOffset = [];
donorSize = [];


for line in lines:
#    print line

    tokens = string.split( line )

    if ( len( tokens ) < 6 ): continue

    if ( tokens[ 1 ] == ".data" ):
        donorDataOffset = string.atoi(tokens[ 5 ], 16 )
    if ( ( tokens[ 3 ] == ".data" )  and string.find( tokens[5], nameFrag ) != -1 and tokens[ 5 ] != ".data" ):
        donorName.append(  tokens[ 5 ] )
        donorOffset.append( string.atoi(tokens[ 0 ], 16 ) )
        donorSize.append( string.atoi(tokens[ 4 ], 16 ) )

for i in range( 0, len( donorName) ):
    
    execute("dd bs=1 skip=" + str(donorDataOffset + donorOffset[ i ]) + " count=" + str(donorSize[ i ]) +"  < " + inputfile + " > " + donorName[ i ] + ".sli ");

#    execute("~/rf/tools/compress/sliutil -d " + donorName[ i ] + ".sli > tmp.raw" )
    execute("genPPMfrom1Color.pl " + donorName[ i ] + ".sli " + donorName[ i ] + ".ppm " + str(width) + " " + str(height) );


