#!/usr/bin/env python

import re
import sys
__doc__ = '''
Cut bigwav into mp3 pieces. Requries path to wav or trs file.
Usage:
    {0} /path/to/wav_or_trs
'''

if len(sys.argv) == 1:
    print __doc__.strip()
    sys.exit(1)

ptn = re.compile(r'<Sync time="([\d.]+)"')
filename = sys.argv[1]
if filename[-3:] in ('trs', 'wav'): filename = filename[:-4]
f = open(filename + '.trs', 'r')
bigwav = filename + '.wav'
if len(sys.argv) == 3:
    bigwav = sys.argv[2]

started = False
stopped = False
start = 0
stop = 0
for line in f.readlines():
    s = line.strip()
    if s == '*':
        stopped = True
        if start:
            print 'sox {0} {1}.mp3 channels 1 rate 22050 trim {2} {3}'.format(bigwav, name, start, stop - start)
        continue
    m = ptn.search(s)
    if not m:
        name = s
        continue
    time = float(m.group(1))
    if started:
        started = False
        stopped = True
        stop = time
    elif stopped:
        started = True
        stopped = False
        start = time
