#NAME: 
#  BFE_File_to_CommandArrArray.py 
#
#PURPOSE:
#  To convert the Black Forest Engineering commands consisting of 
#    WA__WD__
#  directives into SPI commands. 
#
import os
execfile(os.path.expanduser('~')+'/Desktop/Software/Python/CZTCubeSat/CZTCubeSatSetup.py')
import pdb

f = open('./runBFE322_Trigger.log.txt', 'r')
lines = f.readlines()
f.close()

f1 = open('./BFE_Addresses.txt', 'w')
f2 = open('./BFE_Values.txt', 'w')

#Keep track of both the line number and the number of the array element
LineNum=0
ArrayNum=0

#Go through all of the lines in the file
for line in lines:
 
  #Increment the file line number
  ArrayNum+=1

  #Only parse the line if you do not see WAIT
  if (line.find('Select column 2') != -1) : print 'Select column 2 : ' + str(LineNum)
  if ((line.find('WA') != -1) and (line.find('WAIT') == -1)): 

    #Print out the value to the screen
    #print str(ArrayNum) + ' : ' + str(int(line[2:4], 16)) + str('   ') + str(int(line[6:8],16))

    FirstByte  = int(line[2:4], 16)
    SecondByte = int(line[6:8], 16)

    #Form the words
    Word = FirstByte + (SecondByte << 8) 
    print hex(Word)
    TempWord = 0x0000
    #print Word
    for a in arange(16):
      BitMask = 1 << a
      #print hex(BitMask)
      print (Word & BitMask)
      if (Word & BitMask) > 0:
        TempWord = TempWord+2**(15-a)
      print str(a) + ',' +str(TempWord)  
      
    print hex(TempWord)
    pdb.set_trace()
    #Write out the values to a file as arrays
    f1.write('DetectorArrrayAddress['+str(LineNum)+']=0x'+line[2:4]+';\n')
    f2.write('DetectorArrrayValue['+str(LineNum)+']=0x'+line[6:8]+';\n')

    #Increment the number of commands
    if (line.find('WA2AWDA0') != -1) : print 'Line Num ' +str(LineNum)
    LineNum+=1

   

#Close the files
f1.close()
f2.close()
