#python
'''This counts pauses in poetry and plots them against the number of lines.
Input: segmentation'''

import sys
import os
import pylab
import numpy

from gmisclib import fiatio
from gmisclib import wavesurfer_lab as ws


PROC = '/proj/aesop/proc'

def get_s(f):
    out = 0
    try:
	open(f, 'r')
    except IOError:
	print "%s missing" % (f)
	return 'x'
    (header, data) = ws.read(f)
    for (s, e, l) in data:
	if l == 'S':
	    out += 1
    return out


def get_l(f):
    n = 0
    for line in open(f, 'r'):
       if len(line)<5:
	   continue
       else:
	   n += 1
    return n
   
def read_line(line, segm):
    s = get_s(os.path.join(PROC, 'rhythm_measures', line['d'], line['f'], segm+'.lab'))
    l = get_l(os.path.join(PROC, 'rhythm_measures', line['textfile'].rstrip('.txt')+'.phones'))
    return s, l

def read_data(data, segm):
    out = {}
    for line in data:
	if line['property'] != 'poetry':
	    continue
	if line['language'] not in ['English', 'Russian', 'Greek']:
	    continue
	if not line['language'] in out.keys():
	    out[line['language']] = []
	(s, l) = read_line(line, segm)
	print line['language'], s, l
	if not s == 'x':
	    out[line['language']].append((s-1)/float(l))
    return out
	
def plot_data(data):
    pylab.figure()
    n = 1
    for l in data.keys():
	pylab.subplot(1, len(data.keys()), n)
	pylab.hist(data[l])
	pylab.title(l)
	pylab.xlabel('(silences-1)/lines')
	print l, numpy.mean(data[l]), numpy.median(data[l])
	n += 1
    pylab.show()


if __name__ == '__main__':
    segm = sys.argv[1]
    (header, data, comments) = fiatio.read(open(os.path.join(PROC, 'rhythm_measures', segm+'.fiat'), 'r'))
    plot_data(read_data(data, segm))