import sys
import os

if len(sys.argv) <= 1:
  print("filenames as arguments")
  exit()
  
for fn in sys.argv[1:]:
  fname = fn.split(".", 1)[0] # only keep file name
  if not os.path.isfile(fname + ".CSV"):
    print("file: {} does not exist".format(fname))
    continue
  
  with open((fname + ".CSV"), "r") as f,  open((fname + ".vcd"), "w+") as fo:
    fo.write( "$timescale 500 us $end\n\
$scope module none $end\n\
$var wire 1 ! D0 $end\n\
$upscope $end\n\
$enddefinitions $end\n")
    start = False;
    ch1_val = 0
    ch1_lav = 0
    ch1_cnt = 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))
    #end for h in f
  #end with open(...)