import sys, os
import getopt
import re
import datetime, time
import types as pytypes


	
def parse_props( fileEntry, s ):

	strOut = "" 
	
	reg_aliases = []

 

	strToFind = "pragma  target  cpu"	
	pos = s.find( strToFind )
	
	if ( pos >= 0 ):
		pos1 = s.find( "PIC_12" )
		if ( pos1 >= 0 ):
			return "cpu_type = PIC_12"
		pos1 = s.find( "PIC_16" )
		if ( pos1 >= 0 ):
			return "cpu_type = PIC_16"

		pos1 = s.find( "PIC_14" )
		if ( pos1 >= 0 ):
			return "cpu_type = PIC_14"

	strToFind = "pragma  stack"	
	pos = s.find( strToFind )
	
	if ( pos >= 0 ):
		s1 = s[len(strToFind) : ]
		s1 = (s1.lstrip()).rstrip()
		return "stack_size = " + s1

	strToFind = "pragma  code"	
	pos = s.find( strToFind )
	
	if ( pos >= 0 ):
		pos1 = s.find( "-", )
		s1 = s[len(strToFind) : pos1 -1 ]
		s1 = (s1.lstrip()).rstrip()
		return "code_size = " + s1
		
	strToFind = "pragma  data"	
	
	pos = s.find( strToFind )
	if ( pos >= 0 ):
		strOut = "data = [ "
		s1 = s[len(strToFind):]
		s1 = (s1.lstrip()).rstrip()		
		spl = s1.split( "," )
		
		for s in spl :
			s1 = (s.lstrip()).rstrip()		
			spl1 = s1.split( "-" )
		
			# print "FROM " + spl1[0]
			# print "TO   " + spl1[1]
			strOut = strOut + "[" + spl1[0] + " , " + spl1[1] + "], "
		strOut = strOut + " ]"
		return strOut
			

	strToFind = "pragma  shared"	
	pos = s.find( strToFind )
	if ( pos >= 0 ):
		s1 = s[len(strToFind):]
		s1 = (s1.lstrip()).rstrip()		
		spl1 = s1.split( "-" )
		
		# print "FROM " + spl1[0]
		# print "TO   " + spl1[1]
		strOut = strOut + "shared = [ " + spl1[0] + " , " + spl1[1] + "]"
		return strOut

	strToFind = "pragma  eeprom"	
	pos = s.find( strToFind )
	if ( pos >= 0 ):
		s1 = s[len(strToFind):]
		s1 = (s1.lstrip()).rstrip()		
		spl1 = s1.split( "," )
		strOut = "eeprom_location = " + (spl1[0].lstrip()).rstrip() + "\n"
		strOut = strOut + "   eeprom_size = " + (spl1[1].lstrip()).rstrip() 		
		return strOut

		
def parse_alias( fileEntry, s ):
	curPos = s.find( "{" )
	varPos = s.find( "var" )
	commaPos = s.find( "," )
	uscore = s.find( "_" )
	
	reg_aliases = []
	
	#print "PARSE " + s	
	if ( commaPos >= 0 ) and ( curPos >= 0 ) and (varPos >= 0 ) and ( uscore < 0 ) :
		
		b1 = s.find( "0x" )
		c1 = s.find( ",", b1 )

		slice = s[b1:c1]
		reg_aliases.append( slice )

		strOut = ""

		# if ( b1 > 0 ) :
		#		print fileEntry + ":" + s
				
		while ( b1 > 0 ) :
			b1 = s.find( "0x",c1 )
			if ( b1 > 0 ):
				c1 = s.find( ",", b1 )	
				if ( c1 < 0 ):
					c1 = s.find( "}", b1 )	
						
				slice1 = s[b1:c1]
				slice1 = slice1.lstrip()
				slice1 = slice1.rstrip()
				#print "SLICE!!!! :" + slice + ":" + slice1 + ":"
				reg_aliases.append( slice1 )
		
		i = 0

		strOut = strOut + "\n"
		for i in range( 0, len( reg_aliases) ) :
			
			strOut = strOut + "      " + reg_aliases[i] + ":["
			for j in range( 0, len( reg_aliases) ) :
				strOut = strOut + reg_aliases[j] + ","
			strOut = strOut + "],\n"
					
		#if len(strOut ) > 0: 
		return strOut	

def parse_fsr( fileEntry, s ):
	varPos = s.find( "var volatile byte" )
	nulx = s.find( "0x" )
	underscore = s.find( "_" )
	
	sout = ""
	
	if (varPos >= 0 ) and ( nulx > 0 ) and (underscore < 0 ) :

		varStart = len( "var volatile byte" ) + 1

		sharedPos= s.find( "shared" )
		if sharedPos > 0 :
			varEnd = sharedPos
		else:	
			varEnd = s.find( "at " )

		
		varslice = s[ varStart : varEnd ]
		#print s
		# print "VAR S %d " % varStart + " var end %d" % varEnd
		
		b1 = s.find( "0x" )
		c1 = s.find( ",", b1 )
		if ( c1 < 0 ):
			c1 = s.find( "}", b1 )	

		slice = s[b1:c1]
		slice = slice.lstrip()
		slice = slice.rstrip()
		varslice = varslice.rstrip()
		varslice = varslice.lstrip()
		spacePos = varslice.find( " " )
		
		if ( len( varslice ) > 0 ) and ( spacePos < 0 )  :
			#print"'" + varslice +  "':"  + slice + ","
			return ( "'" + varslice +  "':"  + slice + ",")
		return None
					
def find_test_files(testdir):
	testfiles = []
	
	fileList = os.listdir(testdir)

	strout = "# generated by gen_picshell.py script \n"

	# outfname = fileEntry.replace( ".jal", ".py" )
	
	outfname  = "pics.py"
	
	# print outfname
	fout = file(outfname, 'w')
	
	
	
	fout.write( "\n# Generated from JALLIB device files" )
	fout.write( "\nPIC_UNKOWN = 0" )
	fout.write( "\nPIC_12 = 1" )
	fout.write( "\nPIC_14 = 2" )
	fout.write( "\nPIC_16 = 3\n" )
	
	for fileEntry in fileList:
		if fileEntry.endswith( ".jal" ) :
			print fileEntry
			testfiles.append( fileEntry )
			if not hasattr(fileEntry, "read"):
				
				
				picname = fileEntry[ :(len( fileEntry ) - 4 ) ]
				
				strout = "\nclass pic_" + picname + " : \n"

				f = file(fileEntry, "rU")
				strout = strout + "\n"	 
				for s in f:
					fsrNew = parse_props( fileEntry, s )
					if fsrNew != None :
						strout = strout + "   " + fsrNew + "\n"
				f.close()
				strout = strout + "\n"
				

				f = file(fileEntry, "rU")
				strout = strout + "   fsr_regs = { \n"	 
				for s in f:
					fsrNew = parse_fsr( fileEntry, s )
					if fsrNew != None :
						strout = strout + "      " + fsrNew + "\n"
				f.close()
				strout = strout + "   } \n"
				
				f = file(fileEntry, "rU")
				strout = strout + "   shadow_regs = { \n"	 
				for s in f:
					aliasNew = parse_alias( fileEntry, s )
					if aliasNew != None :
						strout = strout + "      " + aliasNew
				f.close()
				strout = strout + "   } \n"
				
					 
				#print strout
				#fout = getattr(outfname, "write", None)
	        	fout.write( strout )

	fout.write( "\ndef PicFactory( strName ): \n" )
	fout.write( "   return globals()[strName]() \n" )
	fout.close()

	return testfiles

if __name__ == "__main__":

	fsr_regs= {	0x41: [ 0x07, 0x40, ],
					2: 0x07,
					3: 0x09,
					4: 0x0A, }

	t1 = [ [ 0x00,0x56]  , [ 0x20,0x36 ] ]
	try:
		# First extract the action, then parse action's args
		#action = sys.argv[1]
		#action_args = sys.argv[2:]
		test_files = find_test_files( "" )
		#for e in fsr_regs:
		#	print e + " ::" + str( fsr_regs[e] )
		print "TEST " + str( t1[0][1])
			
	except IndexError,e:
		print >> sys.stderr, "Please provide an action: %s" % repr(ACTIONS.keys())
		sys.exit(255)
