import re



def split_exp_results(exp, path="."):
    in_fn = "%s/exps_%s_accuracies.txt" % (path, exp)
    with open(in_fn) as f:
        data = [l for l in f]
        var_names = []
        var_open_indices = {}
        var_close_indices = {}

        var_name = None
        for index, l in enumerate(data):
            if l.count("________"):
                if var_name is not None:
                    var_close_indices[var_name] = index - 1
                var_name = re.search("_+([a-z]*)_+", l).group(1)
                var_names.append(var_name)
                var_open_indices[var_name] = index + 1
                var_close_indices[var_name] = -1

        for var_name in var_names:
            output = "".join(data[var_open_indices[var_name]: var_close_indices[var_name]]).strip()
            out_fn = "%s/exps_%s_%s_accuracies.txt" % (path, exp, var_name)

            with open(out_fn, "w") as out_file:
                out_file.write(output)


def get_arguments(path="."):
   from sys import argv
   from os.path import isfile
   arguments = argv
   if len(argv) == 1:
      print("Arguments are experiment ids:\n Example: d a f\n")
      exit(1)
   arguments = arguments[1:]
   for argument in arguments:
      filepath = "%s/exps_%s_accuracies.txt" % (path, argument)
      try:
         assert( isfile(filepath))
      except AssertionError:
         print("%s does not exist!\nCheck experiment id is correct!\n" % filepath)
         exit(2)
   return arguments


if __name__ == "__main__":
   
   experiments_path = "Data/Experiments/"
   experiments = get_arguments(experiments_path)

   for exp in experiments:
       split_exp_results(exp, experiments_path)

