#!   /usr/bin/env   python
#    coding: utf8

# Copyright CERN, 2011
# Author: Matthieu Cattin <matthieu.cattin@cern.ch>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org

import sys
import rr
import time
import os
from numpy import *
from pylab import *

from ptsexcept import *


"""
test10: Plot frequency response summary data from test09 log file

Note: Requires test00.py to run first to load the firmware and
      test09.py to generate the log file.
"""

def main (default_directory='.'):

    # open test09 log file in read mode
    file_name = raw_input('Enter a file name (default=log_test09.txt):')
    if file_name == "":
        file_name = "log_test09.txt"
    file = open(file_name, 'r+')

    # Read file
    points = []
    ch_diff = []
    for line in file:
        #print('Line:%s')%line
        freq,expect_val,tol,ch1,ch2,ch3,ch4 = line.split(',')
        #print('%s %s %s %s %s %s %s')%(freq,expect_val,tol,ch1,ch2,ch3,ch4)
        #print('%3.3f %d %d %d %d %d %d')%(float(freq),int(expect_val),int(tol),int(ch1),int(ch2),int(ch3),int(ch4))
        points.append([float(freq),int(expect_val),int(tol)])
        ch_diff.append(int(ch1))
        ch_diff.append(int(ch2))
        ch_diff.append(int(ch3))
        ch_diff.append(int(ch4))

    #print points
    #print('##########')
    #print ch_diff
    #sys.exit()

    # The following code is to show a graph of the test results
    # !! Don't forget to import numpy and pylab !!
    pt = array(points)
    freq = pt[:,0]
    a_min = pt[:,1] - pt[:,2]
    a_max = pt[:,1] + pt[:,2]
    semilogx(freq, ch_diff[0::4], 'b', label='Channel 1')
    semilogx(freq, ch_diff[1::4], 'g', label='Channel 2')
    semilogx(freq, ch_diff[2::4], 'r', label='Channel 3')
    semilogx(freq, ch_diff[3::4], 'c', label='Channel 4')
    semilogx(freq, a_min, 'r:', label='Lower limit')
    semilogx(freq, a_max, 'r:', label='Upper limit')
    legend()
    show()


if __name__ == '__main__' :
    main()
