#!/usr/bin/env python

# See LICENSE for license details.

import os.path
import argparse
from subprocess import Popen

parser = argparse.ArgumentParser(
  description = 'Replay each sample in a separate simulation instance')
parser.add_argument("-s", "--sample", dest="sample", type=str,
                    help='sample files', required=True)
parser.add_argument("-e", "--sim", dest="sim", type=str,
                    help='simulator executable for sample replays', required=True)
parser.add_argument("-d", "--dir", dest="dir", type=str,
                    help='output directory for waveform, log', required=True)
parser.add_argument("-m", "--match", dest="match", type=str, default=None,
                    help='match file generated by fm-match.py', required=False)
parser.add_argument("-n", "--num", dest="num", type=str, default=10,
                    help='# instances of gate-level simulation', required=False)
args = parser.parse_args()

prefix = os.path.basename(os.path.splitext(args.sample)[0])
abspath = os.path.abspath(args.sim)
dirname = os.path.dirname(abspath)
basename = os.path.basename(abspath)
if not os.path.exists(args.dir):
  os.makedirs(args.dir)

""" Split Sample """
prologue = list()
samples = list()
with open(args.sample) as f:
  for line in f:
    tokens = line.split(" ")
    head = tokens[0]
    if head == '0':
      prologue.append(line)
    elif head == '1':
      assert tokens[1] == 'cycle:'
      samples.append(list(line))
    else:
      samples[-1].append(line)

""" Save samples """
for i, sample in enumerate(samples):
  f = open(os.path.join(args.dir, "%s-replay-%d.sample" % (prefix, i)), 'w')
  for line in prologue:
    f.write("%s" % line)
  for line in sample:
    f.write("%s" % line)
  f.close()

""" Execute replays """
ids = range(len(samples))
for k in xrange(0, len(samples), args.num):
  ps = list()
  logs = list()
  for i in ids[k:k+min(args.num,len(samples)-k)]:
    cmd = ["./%s" % basename,
           "+verbose",
           "+match=%s" % (args.match) if args.match != None else "",
           "+sample=%s/%s-replay-%d.sample" % (args.dir, prefix, i),
           "+vcdfile=%s/%s-replay-%d.vcd" % (args.dir, prefix, i),
           "+waveform=%s/%s-replay-%d.vpd" % (args.dir, prefix, i)]
    print " ".join(cmd)
    log = open("%s/%s-replay-%d.out" % (args.dir, prefix, i), 'w')
    ps.append(Popen(cmd, cwd=dirname, stderr=log))
    logs.append(log)

  while any(p.poll() == None for p in ps):
    pass

  assert all(p.poll() == 0 for p in ps)

  for log in logs:
    log.close()
