#!/usr/bin/env python

from math import sqrt
import argparse
from marsyas import *
from os import path, mkdir, makedirs
import subprocess

################################################################################
# Parse Command-line Arguments
#
parser = argparse.ArgumentParser(description='Extract chroma features for classifier training.')
parser.add_argument('filelist', metavar='filelist', type=str, nargs=1,
                    help='List of files to extract chroma features from.')
parser.add_argument('resultsdir', metavar='resultsdir', type=str, nargs=1,
                    help='Results directory.')
parser.add_argument('reportfile', metavar='reportfile', type=str, nargs=1, help='Report File.')
args = parser.parse_args()

################################################################################
# Process
#
try:
    filelist = open(args.filelist[0], 'r')
except:
    print("Could not open " + args.filelist[0] + ".")
    exit(1)

results = []
for filename in filelist:
    print("Evaluating results for " + filename.strip())
    try:
        result = subprocess.check_output(['./scripts/evaluateChords.py', args.resultsdir[0] + '/' + path.basename(filename.strip()) + '.txt', filename.strip() + '.txt', '--report',  args.resultsdir[0] + '/' + path.basename(filename.strip()) + '.rpt'])
        results.append([filename.strip()] + result.strip().split(','))
    except:
        print("Could not evaluate " + filename.strip())
filelist.close();

# Output Results
reportfile = open(args.reportfile[0], 'w')
hit3 = 0
hit2 = 0
hit1 = 0
hit0 = 0
rol  = 0
ror  = 0
totalEval = 0
for result in results:
    hit3 += int(result[1])
    hit2 += int(result[2])
    hit1 += int(result[3])
    hit0 += int(result[4])
    totalEval += int(result[5])
    rol += int(result[6])
    ror += int(result[7])
    reportfile.write(result[1] + " " + result[2] + " " + result[3] + " " + result[4] + " " + result[5] + " " + result[6] + " " + result[7] + " " + str(float(result[1])/float(result[5])) + " " + result[0] + "\n")
reportfile.write(str(hit3) + " " + str(totalEval) + " " + str(float(hit3)/float(totalEval)) + " 3/3 Match\n")
reportfile.write(str(hit2) + " " + str(totalEval) + " " + str(float(hit2)/float(totalEval)) + " 2/3 Match\n")
reportfile.write(str(hit1) + " " + str(totalEval) + " " + str(float(hit1)/float(totalEval)) + " 1/3 Match\n")
reportfile.write(str(hit0) + " " + str(totalEval) + " " + str(float(hit0)/float(totalEval)) + " 0/3 Match\n")
reportfile.write(str(rol) + " " + str(totalEval) + " " + str(float(rol)/float(totalEval)) + " Left Rotation\n")
reportfile.write(str(ror) + " " + str(totalEval) + " " + str(float(ror)/float(totalEval)) + " Right Rotation\n")
reportfile.close()
    

