set state 0

set memoryModel {}
set memoryName {}
set marchAlgo SMarchCHKBci

proc usage {} {
  puts "Usage: $::argv0 -s --memory (memoryModel.lvlib) \[--target (destinationmFolder)\] --name (prefix for connection) --algorithm (name of March algorithm or pointer to file)"
  puts "Arguments:"
  puts " -m | --memory    :   Memory modle file"
  puts " -o | --target    :   Target directory for generated time"
  puts " -n | --name      :   Name prefix for connections"
  puts " -a | --algorihtm :   File with description of March algorithm"
  puts "                       If filename doesn't end with .m then script will try to search for march/(name).m file in program directory"
  exit
}

foreach {opt} $argv {
  # State 0 - expecting option specifier
  # State 1 - expecting value for --memory
  # State 2 - expecting value for --target
  # State 3 - expecting value for --name
  # State 4 - need only to swallow unneeded option
  # State 5 - expecting value for --algorithm
  switch $state {
    0 {
      switch $opt {
        -m       -
        --memory { set state 1}
        --target -
        -o       { set state 2}
        -n       -
        --name   { set state 3}
        -d       { set state 4}
        -a       -
        --algorithm { set state 5}
        -s       -
        -h       { }
        default  {
          puts "Unknown option $opt"
          usage
        }
      }
    }
    1 {
      set memoryModel $opt
      set state 0
    }
    2 {
      set target $opt
      set state 0
    }
    3 {
      set memoryName $opt
      set state 0
    }
    4 {
      set state 0
    }
    5 {
      set marchAlgo $opt
      set state 0
    }
  }
}

if { $memoryModel eq {} || $memoryName eq {} || $marchAlgo eq {}} {
  usage
}

if {[file exists $marchAlgo] ne 1} {
  set marchAlgo march/${marchAlgo}.m
  if {[file exists $marchAlgo] ne 1} {
    puts "Can't find algorithm $marchAlgo"
    exit
  }
}

puts "Memory model file       : $memoryModel"
puts "Target directory        : $target"
puts "Memory interface prefix : $memoryName"
puts "Selected algorithm      : $marchAlgo"

set targetDir $target/hdl/rtl
set modelDir  $target/hdl/model
set configDir $target/config

set memories {}
set words {}
set memNames {}
lappend memories [createSS $targetDir $memoryModel]
lappend words [list 0 1 10 01 1100 0011 11110000 00001111] 
lappend memNames $memoryName

set ts [createTS $targetDir ${marchAlgo} $memories]
createTop $targetDir $memories $memNames $words
createTB  $modelDir $memories $memNames $words

#Copy static files - counters
puts "Copying counters to target folder"
exec cp templates/mbist_adr_cnt.cfsr.rtl.vhd $targetDir
exec cp templates/mbist_ncnt.dec.rtl.vhd $targetDir

#Generate model and FOF
createBfm $modelDir  $memories $memNames $ts
createFof $configDir $memories
