import sys
import os

if len(sys.argv) <= 1:
  print("filenames as arguments")
  exit()
  
for fn in sys.argv[1:]:
  fname, fend = fn.strip(" .,/\\\"").split(".", 2) # only keep file name
  if not os.path.isfile(fname + "." + fend):
    print("file: {} does not exist".format(fname))
    continue
  
  with open((fname + "." + fend), "r") as f,  open((fname + ".vcd"), "w+") as fo, open((fname + ".txt"), "w+") as fu:
    timescale = 50 ####### TIMESCALE IN µs #######
    
    fo.write( "$timescale {0:d} us $end\n\
$scope module none $end\n\
$var wire 1 ! D0 $end\n\
$upscope $end\n\
$enddefinitions $end\n".format(timescale))
    fu.write("time:   , MSB, LSB first\n")
    start = False;
    ch1_val = 0
    ch1_lav = 0
    ch1_cnt = 0
    
    ####### LENGTH #######
    UART_bit_cnt = 10
    ####### BAUDRATE #######
    UART_baud = 1 # baud in multiples of time base
    
    U_start = False
    U_st_time = 0
    U_bit = 0
    U_data = 0
    U_dat2 = 0
    
    for h in f:
      if not start:
        if (not h.startswith("0, ")):
          continue
        else:
          ch1_val = int(h.strip().split(',')[5][7])
          fo.write("#{0:d} {1:1d}!\n".format(ch1_cnt, ch1_val))
          start = True
          continue
      # else start:
      
      ch1_lav = ch1_val
      ch1_val = int(h.strip().split(',')[5][7]) # get the binary string for all channels, then the 7th char for the valid channel
      ch1_cnt += 1
      
      if (ch1_lav != ch1_val):
        fo.write("#{0:d} {1:1d}!\n".format(ch1_cnt, ch1_val))
        
      if (ch1_lav != ch1_val) and (U_start == False) and (ch1_val == 0):
        #found start condition
        U_start = True
        U_st_time = ch1_cnt
      
      if (U_start):
        if ( ch1_cnt - (U_st_time + (U_bit * UART_baud) + (UART_baud // 2)) >= UART_baud):
          #time for next bit
          if (U_bit < UART_bit_cnt):
            # add another bit
            U_bit += 1
            # MSB first
            U_data <<= 1
            U_data += ch1_val
            # LSB first
            U_dat2 >>= 1
            U_dat2 += (ch1_val << (UART_bit_cnt - 1))
          else:
            # stop bit now
            fu.write("{0:6.3f}ms, {1:03X}, {2:03X}".format((U_st_time*timescale/1000), U_data, U_dat2)) ####### TIMESCALE #######
            # 6.3F, 6 is total lenght including "."
            # X makes the 0x also uppercase
            if (ch1_val == 0):
              # frame error
              fu.write(" Frame Error")
            fu.write("\n")
            U_start = False
            U_data = 0
            U_dat2 = 0
            U_bit = 0
        
    #end for h in f
  #end with open(...)