# Part of DML (Digital Music Laboratory)
# Copyright 2014-2015 Samer Abdallah, University College London
 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

# -*- coding: utf-8 -*-
__author__="samer"

from rdfutils import *
from n3Parser import *
from pitchutils import *
from aggregate import *
from csvutils import csv_map_rows
from warnings import warn

def tonic_from_n3(filename):
    graph=get_rdf_graph_from_n3(filename)
    max_time = 0
    tonic = None
    for ev, time in graph.subjects_objects(ev_ns.time):
        t = parse_xsd_duration(graph.value(time,tl_ns.at))
        if t>max_time: tonic = graph.value(ev,af_ns.feature)
    return tonic-1

def tonic_from_csv(filename):
    # format: time, pitch_class_number, pitch_class_name
    return int(csv_map_rows(filename,3,lambda row:row[1])[-1])-1


def aggregate(inputs):
    parser_table = { 'n3':tonic_from_n3, 
                     'csv':tonic_from_csv }
    hist = 12*[0]
    def accum(f): hist[decode_tagged(parser_table,f)] += 1
    stats=for_each(inputs,accum)
    return { 'result': discrete_hist(pitch_class_names,hist), 'stats':stats }
