#!/usr/bin/python

# This script converts stuff and puts it in the appropriate directories.

import sys, string, os, re, tempfile

def execute( command ):
    print ( command );
    if ( os.system( command ) != 0 ):
        print("ERROR! Commmand" + command + " returned -1" );
        sys.exit(-1);

def getCommandOutput( command ):
    print ( command )
    temp = os.popen( command, "r" );
    lines = temp.readlines();
    for line in lines:
        if ( string.find( line, "ERROR") != -1 ):
            print("ERROR!" + line );
            sys.exit(-1);
    temp.close();
    return lines;

f = open ( sys.argv[ 1 ] )
things = f.readlines()
f.close()

texIn = []
texOut = []

for thing in things:
    tokens = string.split( thing )

    if ( len( tokens ) < 1 ): continue
    if ( thing[ 0 ] == "#" ): continue

    # Convert first file from rgba to i8
    if ( tokens[ 0 ][len( tokens[ 0 ] )-3:] == "sgi" or tokens[ 0 ][len( tokens[ 0 ] )-3:] == "rgb" ):
        execute("convert sgi:" + tokens[ 0 ] + " " + tokens[ 0 ] + ".rgba")
        execute("rgba2i8.pl " + tokens[ 0 ] + ".rgba " + tokens[ 0 ] + ".raw") 
    else:
        execute("chmod 666 " + tokens[ 0 ] + " ") 
        execute("cp -f " + tokens[ 0 ] + " " + tokens[ 0 ] + ".raw") 



    texIn.append( tokens[ 0 ] + ".raw" )

f = open( sys.argv[ 2 ] )
files = f.readlines();
f.close()

# First, de-sli the sli files
for line in files:
    fileName = line[ :len( line) -1 ]

#    execute( "ascii2raw.py asdf < " + fileName + " > " + fileName + ".sli " )
#    execute( "$SLI/sliutil -d " + fileName + ".sli > " + fileName + ".raw" )
   


for i in range( 0, len( texIn ) ):

    replaced = 0
    
    for line in files:
        fileName = line[ :len( line) -1 ]
        textureFile = texIn[ i ]

        # Now, check for it
        outputs = getCommandOutput( "binaryReplacer " + fileName + ".raw " + fileName + ".raw2 " + textureFile + " " + textureFile )

        for out in outputs:
            if ( string.find( out, "position" ) != -1 ):
                print("REPLACED " + textureFile + " in " + fileName );
                replaced = 1


    if ( replaced != 1 ): print("PING: NOT THERE:  Couldn't find " + texIn[ i ] + " anywhere!" )
    else: print("PING: FOUND: " + texIn[ i ] )
        
