#!/usr/bin/python

import glob
import os
import sys
import re
import string

rootdir=sys.argv[2]
x_range='5'


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

type=[];name=[];mode=[]


def regular_analyze(cmd_type,cmd_name,mode_flag):

	regular_one(cmd_type,cmd_name,mode_flag)
		
	fr=file(rootdir+"/mem_database.txt","r")

	for line in fr.readlines():
		for i in range(len(name)):
			regexp=re.compile(r"[0-9A-Za-z]+\s+"r"(%s)\s+"r"(x|y)\s+"r"(?P<argn>(%s)+)" % (type[i],name[i]))
			#print name[i]
			result=regexp.search(line)
			
			if regexp.search(line):
				argname=result.group("argn")
				if (line[12:-1] != argname):	#避免正規表示式找uMaxBits連uMaxBitsFast一起找到
					break
					
				# 用n1~n4代替address,type,xy,name
				n1="0x"+line[2:6]
				n2=line[7:9]
				n3=string.lower(line[10])
#				n4=line[12:-1]	#這段代表mem_database.txt中正確的name名稱
				n4=argname
				
				print n1+" "+n2+" "+n3+" "+n4
				if (mode_flag == '2'):
					regular_two(n1,n2,n3,n4)
				elif (mode_flag == '1'):
				#	print mode[i]
					analyze(int(n1,16),n2,n3,n4,"1",mode[i])

				#呼叫plotvar畫圖
#				plotvar(int(n1,16),n2,n3,n4)
#				fw.write("0x"+line[2:6]+" "+line[7:9]+" "+string.lower(line[10])+" "+argname+"\n")
	fr.close()

def regular_one(cmd_type_one,cmd_name_one,mode_flag):	#判斷是否有command line的參數輸入
	if (cmd_type_one == "")&(cmd_name_one == ""):		#如果沒有從command line接收到輸入參數,則分析cmd.arg的內容
		if (mode_flag == '2'):
			frcmdarg=file("cmd.arg","r")
		elif (mode_flag == '1'):
			frcmdarg=file("report.arg","r")
#		fr=file("mem_database.txt","r")
		cmdline=[]       #讀取cmd.arg的參數命令變數

		while True:
			cmdline = frcmdarg.readline()
			if len(cmdline) == 0:
				frcmdarg.close()
				break
			if (cmdline[0] != '\n')&(cmdline[0] != "#"):
				type.append(cmdline[0:2])
				if (mode_flag == "2"):
					name.append(cmdline[3:-1])
				elif (mode_flag == "1"):
					name.append(cmdline[3:-3])
					mode.append(cmdline[-2:-1])	#mode變數表示report.arg中的10 or 16進位的flag

	else:
		type.append(cmd_type)
		name.append(cmd_name)
		
	return type,name
	frcmdarg.close()
	
def regular_two(rn1,rn2,rn3,rn4):
	plotvar(int(rn1,16),rn2,rn3,rn4)


def regular_make_mem_data():
#	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+")
	#正規表示式解析的格式
	#6321      X:0026CC         RxWinLoadAddr1          ds  1	

	fw=file(rootdir+"/mem_database.txt","w")
	for i in type_loop:
		fr=file(rootdir+"/globalsg_"+i+".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(i)+" "+string.lower(line[10])+" "+argname+"\n")
	print "Create memory dayabase"
				
								
def gnuscript(name):
	#print name[3:-3] #這段代表距離
	#print name[-4:]
	snrcheck=name[-3:]
	
	noise=sys.argv[3]
	
	cmd=['show style data','set ytics autofreq','set grid','set xtics 250','set term png']
	cmd.append('set title "%s\"' % name)
	if snrcheck != "SNR":	#畫出cmd.arg中的設定
		cmd.append('set xlabel "Distance(feet)"')
		cmd.append('set style data linespoints')
		cmd.append('set xtics %s' % x_range)
		cmd.append('set output "%s/report/output/%s.png\"' % (rootdir,name))
		cmd.append('plot \"result.txt\" using 1:2 lt 1 title \"Award %s\"' % name)
#		if (name[7:9] == 'Ot') & (name[-4:]=='Rate'):
#			cmd.append('plot \"result.txt\" using 1:2 lt 1 title \"Award %s\" , \\' % name)
#		else:
#			cmd.append('plot \"result.txt\" using 1:2 lt 1 title \"Award %s\"' % name)
		
		fs=file("plot.scr","w")
	else:
		cmd.append('set style data lines')
		cmd.append('set ylabel "dB"')
		cmd.append('set xtics 200')
		cmd.append('set output "%s/report/snroutput/%s.png\"' % (rootdir,name))
		cmd.append('plot \"%s/%s/%s/snrs_showtime.txt\" using ($1*0.0029/64) lt 2 title \"snrs_showtime.txt\", \\' % (rootdir,name[:2],name[3:-4]) )
		cmd.append('\"%s/%s/%s/snrs_train.txt\" using ($1*0.0029/64) lt 3 title \"snrs_train.txt\"' % (rootdir,name[:2],name[3:-4]) )
		
		fs=file("plotsnr.scr","w")
	
	cmd='\n'.join(cmd)
	fs.write(cmd)
	fs.close()

def plotvar(address,type,xy,name):
	analyze(address,type,xy,'','2','')
	gnuscript(type+"_"+name)
	os.system('wgnuplot.exe plot.scr')

#畫所有距離的SNR
def plotsnr(type_snr):
	length_snr=analyze_directory(type_snr)
#	print length_snr
	for i in length_snr:
		gnuscript(type_snr+"_"+str(i)+"_SNR")
		print "Plot "+type_snr+"_"+str(i)+"_SNR"
		os.system('wgnuplot.exe plotsnr.scr')
			

def analyze_directory(type_directory):
#	print type_directory
	length=[]	#放置距離資料
	d=[]	#檔名字串轉換成整數排列暫存用
	filename=glob.glob(rootdir+'/%s/*'  % type_directory)
	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
	return length

def analyze(address,type,xy,name_analyze,mode_analyze,value_type_flag):
	data=[]	#放置每個檔案最後數據處理結果
	if (mode_analyze == "2"):
		lengths=analyze_directory(type)
		fw=file("result.txt","w")
	elif (mode_analyze == "1"):
		#print name_analyze
		#lengths=['1']
		lengths=analyze_directory(type)
#		print "mode 1"	

#	print lengths

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

#把length和data寫入result.txt
#	fw=file("result.txt","w")
	if (mode_analyze == "2"):
		for l,d in zip(lengths, data):
			#fw.write('%d\t%f\n' % (l,float(d)/1000))
			fw.write('%d\t%f\n' % (l,int(d)))
		fw.close()
	elif (mode_analyze == "1"):
	#	print value_type_flag
		for l,d in zip(lengths, data):
			fw=file(rootdir+'/report/connection/'+type+"_report_"+str(l)+".txt","a")
			if (value_type_flag == '2'):	#'2'=>代表16進位輸出		
			#	print 'length=%i\tvalue=%06x' % (l,int(d))
				fw.write('%s\t\t\t0x%06x\n' % (name_analyze,int(d)))
			#	fw.write('%s\t\t\t%s\n' % (name_analyze,hex(int(d))))
			elif (value_type_flag == '1'):	#'1'=>代表10進位輸出
			#	print 'length=%i\tvalue=%i' % (l,int(d))
				fw.write('%s\t\t\t%i\n' % (name_analyze,int(d)))
			elif (value_type_flag == '3'): #'3'=>代表2進制輸出
				connection_report_list=[]
				hex_num='%06x' % int(d)
				bin_num=''
				for b in hex_num:
					bin_num=bin_num+hex2bin(b)
					
				fw.write('%s\t\t\t%s\n' % (name_analyze,bin_num))
								
				frcfg=file('report.cfg','r')			
				report_line=frcfg.readlines()

				for times in range(len(report_line)):
					if (report_line[times][:-1] == name_analyze):
						as=times+1

						while(len(connection_report_list) < len(bin_num) ):
							if (type == 'OT'):
								if ((report_line[as][0] == '*') | (report_line[as][0] == '+')):
									connection_report_list.append(report_line[as][1:-1])
							elif (type == 'RT'):
								if ((report_line[as][0] == '*') | (report_line[as][0] == '-')):
									connection_report_list.append(report_line[as][1:-1])								
							as=as+1
					
					#	print '='+name_analyze+'_Connection_report_analyze='
						 
						for j in range(24):
							if(bin_num[-1*(j+1)] == '1'):
								if(len(connection_report_list[j]) > 13 ):
									fw.write(' %s\t\tYes\n' %  connection_report_list[j])
								else:
									fw.write(' %s\t\t\tYes\n' %  connection_report_list[j])
							elif(bin_num[-1*(j+1)] == '0'):
								if(len(connection_report_list[j]) > 13):
									fw.write(' %s\t\tNo\n' %  connection_report_list[j])
								else:
									fw.write(' %s\t\t\tNo\n' %  connection_report_list[j])
								#print connection_report_list[j]

				frcfg.close()
				  #name_analyze這名稱就是指report.arg中的name			
		fw.close()
		
def hex2bin(hexnum):
	if hexnum == '0':
		binnum = '0000'
	elif hexnum == '1':
		binnum = '0001'
	elif hexnum == '2':
		binnum = '0010'
	elif hexnum == '3':
		binnum = '0011'
	elif hexnum == '4':
		binnum = '0100'
	elif hexnum == '5':
		binnum = '0101'
	elif hexnum == '6':
		binnum = '0110'
	elif hexnum == '7':
		binnum = '0111'
	elif hexnum == '8':
		binnum = '1000'
	elif hexnum == '9':
		binnum = '1001'
	elif hexnum == 'a':
		binnum = '1010'
	elif hexnum == 'b':
		binnum = '1011'
	elif hexnum == 'c':
		binnum = '1100'
	elif hexnum == 'd':
		binnum = '1101'
	elif hexnum == 'e':
		binnum = '1110'
	elif hexnum == 'f':
		binnum = '1111'
	
	return binnum
	
	
def check_necessarily_dir():
	if (glob.glob(rootdir+'/report')):
		print "necessarily directory found"
	else:
		os.system('mkdir %s/report' % rootdir)
		os.system('mkdir %s/report/output' % rootdir)
		os.system('mkdir %s/report/snroutput' % rootdir)
		os.system('mkdir %s/report/connection' % rootdir)
				
#========================main()========================
check_necessarily_dir()
regular_make_mem_data()

if sys.argv[1] == 'default':
	regular_analyze("","","2")
	
elif sys.argv[1] == 'report':
	os.system('rm %s/report/connection/*.txt' % rootdir)
	regular_analyze("","","1")

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] == 'makedata':
	regular_make_mem_data()

elif sys.argv[1] == 'clean':
	os.system('rm %s/report/output/*.png' % rootdir)
	os.system('rm %s/report/snroutput/*.png' % rootdir)
	os.system('rm %s/report/connection/*.txt' % rootdir)
	print "Delete all report files in 'report' directory"


elif sys.argv[1] == 'help':
	print "Argument:\n\
	default:ploting depends cmd.arg\n\
	makedata:Creating mem_database.txt use \'regular expression\'\n\
	plotsnr:ploting all distance SNR\n\
	list:Show cmd.arg file\n\
	ver:Show version and date\n\
	clean:Delete all report files in 'report' directory"
	

elif sys.argv[1] == 'plotsnr':
	plotsnr('OT')
	plotsnr('RT')

elif sys.argv[1] == 'ver':
	print "Version 2.22 Date:06092006"

elif sys.argv[1] == 'all':
	regular_analyze("","","2")
	os.system('rm %s/report/connection/*.txt' % rootdir)
	type=[];name=[];mode=[]
	regular_analyze("","","1")
	plotsnr('OT')
#	plotsnr('RT')
	
else:
#	regular_analyze(sys.argv[1],sys.argv[2])
	print "No argument ro argument error"
