#!/usr/bin/python

import string, sys, os

i8P = 0

sizeX = 32
sizeY = 32
justRawP = 0

def checker( symbol ):
    global i8P;
    global sizeX, sizeY;
    global justRawP

    if ( symbol == "-i8" ):
        i8P = 1;
        return;
        
    if ( symbol == "-justRaw" ):
        print "Just raw files!"
        justRawP = 1
        return

    print("symbol = " + symbol[:5] );
    
    if ( symbol[:5] == "sizeX" ): sizeX = string.atoi( symbol[6:] );
    if ( symbol[:5] == "sizeY" ): sizeY = string.atoi( symbol[6:] );

if ( len ( sys.argv ) < 4 ):
    print "Usage: multiAscii2Raw.py inputFile outputDir index.txt"
    sys.exit( -1 )
    

inputFileName = sys.argv[1]
outputDirName = sys.argv[2]
indexFileName = sys.argv[3]

for i in range( 4, len( sys.argv) ):
    checker( sys.argv[ i ] );

def execute( command ):
    print ( command );
    os.system( command );


indexFile = open ( indexFileName, "w")

inputFile = open ( inputFileName, "r")
lines = inputFile.readlines();
inputFile.close();

count = 0;

for i in range( 0, len( lines ) ):

    if ( string.find( lines[ i ], "unsigned" ) != -1
         and string.find( lines[ i ], "extern" ) == -1 ):
                
        tokens = string.split( lines[ i ] )

        theName = "Unnamed" + str( count );

        # find the name
        for token in tokens:
            if ( string.find( token, "[" ) != -1  ):
                # Ahah!
                theName = token[ : len( token )-2 ]
                break;

        outputFileName = ( theName +".ascii" );
        outputFile = open( outputDirName +  "/" + outputFileName, "w+" )
        
        for j in range( i+1, len( lines ) ):
            if ( string.find ( lines[ j ], "}" ) != -1 ):
                # The end!
                break;

            outputFile.write( lines[ j ] );


        outputFile.close()

        print "Found symbol = " + theName 

        execute("ascii2raw.py < " + outputDirName +  "/" + outputFileName + " > " + outputDirName + "/" + theName +".raw" );

        if (justRawP == 0 ):

            if ( i8P == 1 ):
                execute("i82rgba.pl " + outputDirName + "/" + theName + ".raw " + outputDirName + "/" + theName + ".rgba" )
            else:
                execute("cp " + outputDirName + "/" + theName + ".raw " + outputDirName + "/" + theName + ".rgba" )


            execute("genPPMfromRGBA.pl " + outputDirName + "/" + theName + ".rgba " + outputDirName + "/" + theName + ".ppm " + str( sizeX ) + " " + str( sizeY ) )
                
            indexFile.write( theName + ".raw\n" );

indexFile.close()

