#!/usr/bin/python
#########################################################################
#Author by Peter.Kung 5/30/2006
#	Argument:
#	default:ploting depends cmd.arg
#	regot:Creating save_ot.txt use 'regular expression'
#	regrt:Creating save_rt.txt use 'regular expression'
#	allot:ploting depends save_ot.txt
#	allrt:ploting depends save_rt.txt
#	list:Show cmd.arg file
#	clean:Delete all .png files in output directory
########################################################################

import glob
import os
import sys
import re
import string

rootdir='repeat'
#rootdir='0530m'
x_range='10'
#因為目錄名稱長度不同,多用一個len_tmp變數來作轉換
#讓後面的檔名字串可以正確抓出來
len_tmp=len(rootdir)+4


def regular_memdata():
	fw=file("save_all.txt","w")
	frcmdarg=file("cmd.arg","r")
        cmdline=[]       #讀取cmd.arg的參數命令變數
	type=[]
	regname=[]
        while True:
                cmdline = frcmdarg.readline()
                if len(cmdline) == 0:
                        frcmdarg.close()
                        break
                if (cmdline[0] != '\n')|(cmdline[0] != '#'):
                        type.append(cmdline[0:2])
                        regname.append(cmdline[3:-1])
#         	print type
#		print regname

	fr=file("mem_data.txt","r")
	for line in fr.readlines():
		for i in range(len(regname)):
		#	regexp=re.compile(r"[0-9A-Za-z]+\s+"r"(OT|RT)\s+"r"(x|y)\s+"r"(?P<argn>(%s)+)" % i )
			regexp=re.compile(r"[0-9A-Za-z]+\s+"r"(%s)\s+"r"(x|y)\s+"r"(?P<argn>(%s)+)" % (type[i],regname[i]))
			if regexp.search(line):
				result=regexp.search(line)
				print line,
				argname=result.group("argn")
				fw.write("0x"+line[2:6]+" "+line[7:9]+" "+string.lower(line[10])+" "+argname+"\n")



#接受default或是all這個參數處理資料
def argfile(name_arg):
	cmdarg=[]	#讀取cmd.arg的參數命令變數
        fc=file(name_arg,'r')
        while True:
                cmdline = fc.readline()
                if len(cmdline) == 0:
                        fc.close()
                        break
		if cmdline[0] != '\n':
	                cmdarg.append(cmdline[0:6])
			cmdarg.append(cmdline[7:9])
			cmdarg.append(cmdline[10:11])
			cmdarg.append(cmdline[12:-1])
			print cmdarg
			plotvar(int(cmdarg[0],16),cmdarg[1],cmdarg[2],cmdarg[3])
                cmdarg=[]


#正規表示式分析OT/RT list
def regular(tname,regname):
	print tname
	print regname

	if regname != "":
		print 1111111111111
		regexp=re.compile(r"[0-9]+\s+"r"[X-Y]:+"r"[0-9A-F]+\s+"r"(?P<argn>(%s)+)\s+"r"(ds|dc)\s+"r"[0-9]+" % regname)
	else:
		print 22222222222222
		regexp=re.compile(r"[0-9]+\s+"r"[X-Y]:+"r"[0-9A-F]+\s+"r"(?P<argn>[a-zA-Z0-9]+)\s+"r"(ds|dc)\s+"r"[0-9]+")

	#regexp=re.compile(r"[0-9]+\s+"r"[X-Y]:+"r"[0-9A-F]+\s+"r"(?P<argn>[a-zA-Z0-9]+)\s+"r"(ds|dc)\s+"r"[0-9]+")
	#正規表示式解析的格式
	#6321      X:0026CC         RxWinLoadAddr1          ds  1

#	regexp=re.compile(r"[0-9]+\s+"r"[X-Y]:+"r"[0-9A-F]+\s+"r"(?P<argn>(%s)+)\s+"r"(ds|dc)\s+"r"[0-9]+" % regname)

	fw=file("save_"+tname+".txt","w")
	fr=file(rootdir+"/globalsl_"+tname+".lst","r")
	for line in fr.readlines():
		result=regexp.search(line)
		if regexp.search(line):
#			print line,
			argname=result.group("argn")
			fw.write("0x"+line[14:18]+" "+string.upper(tname)+" "+string.lower(line[10])+" "+argname+"\n")

def regularall():
	fr1=file("save_ot.txt",'r')
	fr2=file("save_rt.txt",'r')
	fwdata=file("mem_data.txt",'w')
	line1=fr1.readlines()
	line2=fr2.readlines()
	for i in line1:
		fwdata.write(i)

	for i in line2:
		fwdata.write(i)

	fr1.close()
	fr2.close()
	fwdata.close()


#接收main()所傳的資料
def plotvar(mem,type,xy,name):
	analyze(mem,type,xy)
	gnuscript(type+'_'+name)
	#os.system('/usr/bin/gnuplot plot.scr')
	os.system('wgnuplot plot.scr')



#建立gnuplot所需要的script
def gnuscript(name):
#	print name
	cmd=['show style data','set style data linespoints','set ytics autofreq','set xlabel "Distance(feet)"','set grid','set xtics 250','set term png']
	cmd.append('set xtics %s' % x_range)
	cmd.append('set title "%s\"' % name)
	cmd.append('set output "output/%s.png\"' %name)
	cmd.append('plot \"result.txt\" using 1:2 lt 1 title \"Award 2 %s\"' % name)
	fs=file("plot.scr","w")
	cmd='\n'.join(cmd)
	fs.write(cmd)
	fs.close()


#取出檔案中的某一行資料
def analyze(mem,type,xy):
	data=[]	#放置每個檔案最後數據處理結果
	length=[]	#放置距離資料
	d=[]	#檔名字串轉換成整數排列暫存用
	filename=glob.glob(rootdir+'/%s/*'  % type)
	filename.sort()

	d = [z[len_tmp:] for z in filename]	#Albert
#	print d

#將字串d轉換成整數做大小排列存到length
	length = [int(dn) for dn in d]  #Albert
	length.sort()
#	print length

#取出某一行的數值
	for i in range(len(length)):
		fr=file(rootdir+'/'+type+'/'+str(length[i])+'/'+xy+'_mem_16k.txt')
		line=fr.readlines()
		s=line[mem]	#取出檔案中第3行的資料,改999就取第1000行  US
#		print s
		data.append(s[:-2])
#	print data
	
	fr.close() # close the file

#把length和data寫入result.txt
	fw=file("result.txt","w")

#Albert
	for l,d in zip(length, data):
		#fw.write('%d\t%f\n' % (l,float(d)/1000))
		fw.write('%d\t%f\n' % (l,int(d)))
	fw.close()



#======================main()==============================


if sys.argv[1] == 'default':
	regular_memdata()
	argfile('save_all.txt')

elif sys.argv[1] == 'def2':
	argfile('save_all.txt')

elif sys.argv[1] == 'allot':
	regular('ot')
	argfile('save_ot.txt')

elif sys.argv[1] == 'allrt':
	regular('rt')
	argfile('save_rt.txt')

elif sys.argv[1] == 'list':
	print "Format:Memory_address  OT/RT  x/y_memory   Name"
        fc=file('cmd.arg','r')
        while True:
                cmdline = fc.readline()
                if len(cmdline) == 0:
                        fc.close()
                        break
                print cmdline,
                cmdarg=[]

elif sys.argv[1] == 'clean':
	os.system('rm output/*.png')
	print "Delete *.png in output directory"

elif sys.argv[1] == 'regot':
	regular('ot',"")

elif sys.argv[1] == 'regrt':
	regular('rt',"")


elif sys.argv[1] == 'sregot':
	regular('ot',sys.argv[2])

elif sys.argv[1] == 'help':
	print "Argument:\n\
	default:ploting depends cmd.arg\n\
	regot:Creating save_ot.txt use \'regular expression\'\n\
	regrt:Creating save_rt.txt use \'regular expression\'\n\
	allot:ploting depends save_ot.txt\n\
	allrt:ploting depends save_rt.txt\n\
	list:Show cmd.arg file\n\
	clean:Delete all .png files in output directory"


elif sys.argv[1] == 'makelist':		#建立mem_data.txt
	regular('ot',"")
	regular('rt',"")
#	cmdline2=[]
#	regular2('cmd.arg2')
	regularall()

elif sys.argv[1] == 'memdata':
	regular_memdata()

else:
       plotvar(int(sys.argv[1],16),sys.argv[2],sys.argv[3],sys.argv[4])

