from pylab import *
import scipy.signal as signal
import sys, wave, struct, re

INT = "([-+]?[0-9][0-9]*)"

wav_fond = wave.open("filter_fond.wav", "w")
wav_fond.setnchannels(1)
wav_fond.setsampwidth(2)
wav_fond.setframerate(5000)
wav_harm1 = wave.open("filter_harm1.wav", "w")
wav_harm1.setnchannels(1)
wav_harm1.setsampwidth(2)
wav_harm1.setframerate(5000)
wav_other = wave.open("filter_other.wav", "w")
wav_other.setnchannels(1)
wav_other.setsampwidth(2)
wav_other.setframerate(5000)

pow_fond = []
pow_harm1 = []
pow_other = []
cpt_filter = []
detected = []

while True:
    l = sys.stdin.readline()
    if l == "":
        break
    m = re.match("%s pow_fond=%s pow_harm1=%s pow_other=%s cpt_filter=%s detected=%s"%(INT, INT, INT, INT, INT, INT), l)
    if m:
        n, val_fond, val_harm1, val_other, val_cpt_filter, val_detected = map(int, m.groups())
        print "pow", n, val_other, val_harm1, val_other, val_cpt_filter, val_detected
        pow_fond.append(val_fond)
        pow_harm1.append(val_harm1)
        pow_other.append(val_other)
        cpt_filter.append(val_cpt_filter)
        detected.append(val_detected*500)
    m = re.match("%s fil_fond=%s fil_harm1=%s fil_other=%s"%(INT, INT, INT, INT), l)
    if m:
        n, val_fond, val_harm1, val_other = map(int, m.groups())
        print "fil", n, val_fond, val_harm1, val_other
        wav_fond.writeframes(struct.pack("<h", val_fond))
        wav_harm1.writeframes(struct.pack("<h", val_harm1))
        wav_other.writeframes(struct.pack("<h", val_other))

subplot(211)
print pow_fond
plot(range(len(pow_fond)), pow_fond)
plot(range(len(pow_fond)), pow_harm1)
plot(range(len(pow_fond)), pow_other)
ylabel('Power')
xlabel(r'Samples')
subplot(212)
plot(range(len(cpt_filter)), cpt_filter)
plot(range(len(detected)), detected)
ylabel('Detected')
xlabel(r'Samples')

# save in a file or display
if len(sys.argv) >= 2:
    savefig(sys.argv[1])
else:
    show()

sys.exit(0)
