#!python
import subprocess
import os
import sys
import re  # for regular expression
import shutil

#
# variable definition
#
INCLUDES = []
CFG1_DEF_TABLES = []

# set relative path from top proj
proj_rel_dir = ""

# call definition file
common.Source("./def.py")

# path
src_abs_path = os.path.abspath(SRCDIR)

# call common file
common.Source(src_abs_path + "/arch/ccrx/common.py")

#
# convert map file
#
inputfile = open("./DefaultBuild/asp.map")
outputfile = open("./DefaultBuild/asp.syms", 'w')

r1 = re.compile("^\s+(_\w+)")
r2 = re.compile("^\s+([0-9a-f]+)\s+")
line = inputfile.readline() 
while line:
    line = line.replace('\r\n','')   #delete newline
    m1 = r1.search(line)
    if m1:
        line = inputfile.readline() 
        line = line.replace('\r\n','')   #delete newline
        m2 = r2.search(line)
        outputfile.write("0x" + m2.group(1) + " T " + m1.group(1) + "\n")
    line = inputfile.readline()

inputfile.close()
outputfile.close()

#
# copy pass 2 generated files
#
print "Copy pass 2 generated file"
shutil.copy("./cfg/cfg2_out.db", ".")

#
# Execute cfg path 3
#
# make command
cfg_command = cfg + " --pass 3 " + "--kernel " + CFG_KERNEL + " -O"
cfg_command += " " + cfg_includes 
cfg_command += " --rom-image ./DefaultBuild/asp.srec --rom-symbol ./DefaultBuild/asp.syms"
cfg_command += " -T " + cfg_check_trb

print cfg_command

# Execute 
try:
   output = subprocess.check_output(cfg_command, stderr=subprocess.STDOUT,)
except subprocess.CalledProcessError, e:
    print "ERROR!! : ", e.output
    sys.exit()

output.replace('\r','')
print output

#
# dlete pass 2 generated files
#
print "Delete pass 2 generated file"
os.remove("cfg2_out.db")
