# parse SDS flags, based on a simple state machine:
# 1. wait (everything is ignored until -sds-hw)
# 2. sdshw (when finding -sds-hw: 2 positional arguments)
# 2.1. sdshwopt (in -sds-hw: options)
# 2.2. hwfiles (if finding -files options)
def parse_sdsflags(arg)
  toplevel = nil
  hwfiles = []
  mode = :wait

  args = arg.split(' ')

  while opt = args.shift do
    case mode
    when :wait then
      mode = :sdshw if opt == "-sds-hw"
    when :sdshw then
      toplevel = opt
      hwfiles << args.shift
      mode = :sdshwopt
    when :sdshwopt
      mode = :hwfiles if opt == "-files"
      mode = :wait if opt == "-sds-end"
      # otherwise, ignore
    when :hwfiles
      if opt[0] == "-" then
        mode = :sdshwopt
        args.insert(0, opt) # insert back option to be parsed again
      else
        hwfiles << opt
      end
    end
  end
  return toplevel, hwfiles
end

# parse positionnal arguments:
def parse(args)
  command = args.pop
  srcdir = args.shift
  toplevel, hwfiles = parse_sdsflags(args.shift)
  files = args

  return command, srcdir, toplevel, hwfiles, files
end

command, srcdir, toplevel, hwfiles, files = parse(ARGV)
filename = toplevel + "_" + command + "_run.tcl"

# Generate a new tcl file, based on the one generated by SDSoC
File.open(filename, 'w') do |file|
  cflags = nil
  tcl = File.open(toplevel + "_run.tcl").readlines.each do |line|
    case line
    when /^add_files .* -cflags (.*)$/
      file.write("set cflags #{$1}\n")

      # Generate line for each file
      hwfiles.each do |f|
        file.write("add_files #{srcdir}/#{f} -cflags $cflags\n")
      end

      files.each do |f|
        file.write("add_files -tb #{srcdir}/#{f} -cflags $cflags\n")
      end
    when /^open_solution/
      # Remove reset: will use already synthesized solution
      file.write(line.sub '-reset', '')
    when /^csynth_design/
      # Replace synthesis by given command
      file.write(command + "\n")
    when /^export_design/
      # Skip
    else
      # Duplicate other lines
      file.write(line)
    end
  end
end

exec("vivado_hls -f #{filename} -l #{toplevel}_#{command}.log")
