text: # -*- coding: utf-8 -*-
  """
  Created on Wed Aug 15 15:06:08 2012
  
  @author: SBrink
  """
  
  from struct import unpack
  from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
  from matplotlib.figure import Figure
  from numpy import correlate
  import csv
  import os
  import datetime
  from scipy import fft, array
  
  class Wave:
  #Class Variables 
      wave_times = []
      wave_data = []
      wave_quantity = 0
      dir_path = ""
      csv_file_path = ""
      processed_waves_dir = ""
      max_quantity_to_process = 0
      start_time = datetime.datetime.now()
      time_difference_string = []
      valid_wave = []
  
  #Basic functions to set up class
      def __init__(self, dir_path_given, max_quantity_to_process_given = 0):
          self.dir_path = dir_path_given
          self.csv_file_path = self.dir_path + r"\analysis.csv"
          self.processed_waves_dir = self.dir_path + r"\out"
          self.max_quantity_to_process = max_quantity_to_process_given
          
          
  
      def read_data_from_csv(self):
          csv_reader = csv.reader(open(self.csv_file_path, 'rb'),delimiter=',')
          for row in csv_reader:
              if row[0] <> "Filename":
                  if row[0] == "Start_Time":
                      self.start_time = datetime.datetime.strptime(row[1], "%d/%m/%Y %H:%M:%S");
                  else:
                      try:
                          big_date = datetime.datetime.strptime(row[1], "%d/%m/%Y %H:%M:%S")
                          millisecond_date = datetime.timedelta(milliseconds=int(row[2]))
                      except (ValueError, IndexError):
                          self.wave_times.append(None)
                          self.time_difference_string.append(None)
                          self.valid_wave.append(0)
                          pass
                      else:
                          self.valid_wave.append(1)
                          full_start_date = big_date + millisecond_date                     
                          
                          time_difference = full_start_date - self.start_time
                          hours, remainder = divmod(time_difference.seconds, 3600)
                          minutes, seconds = divmod(remainder, 60)
                          hours += time_difference.days * 24
                          if ((time_difference.microseconds / 1000) > 150):
                              milliseconds = time_difference.microseconds / 1000 - 50
                          else:
                              milliseconds = 0
                          
                          
                          self.time_difference_string.append('%sh%sm%s.%ss' % (hours, minutes, seconds,milliseconds))
                          self.wave_times.append(full_start_date)
              
                  
      def read_wave_data(self):
          i = 0
          
          for dirname, dirnames, filenames in os.walk( self.processed_waves_dir ):
              for filename in filenames:
                  file_path = os.path.join(dirname, filename)
              
                  wave_raw_values =[]
                  wave_rectified_values = []
                  
                  bytes_read = open( file_path, "rb" ).read()
                  
                  
                  wave_raw_values = list(unpack(">%dh" % (len(bytes_read) / 2), bytes_read))
                          
                  sum_value = 0
                          
                  for x in wave_raw_values:
                      sum_value = sum_value + x
                          
                  dc_average = sum_value / len(wave_raw_values)
                          
                  for y in wave_raw_values:
                      dc_removed_value = y - dc_average
                      wave_rectified_values.append(dc_removed_value)
                  
                  self.wave_data.append(wave_rectified_values)
                  
                  i += 1
                  if i == self.max_quantity_to_process:
                      break
                  
          self.wave_quantity = i - 1
                         
      def generate_plots(self):
           fig = Figure()        
                   
           for j in range(self.wave_quantity):
                  canvas = FigureCanvas(fig)
                  fig.set_canvas(canvas)
                  ax = fig.add_subplot(1,1,1)
                  fig.suptitle("Event " + str(j) + ", Relative Time: " + self.time_difference_string[j]) 
                  ax.plot(self.wave_data[j], '-')
                  plotdir = self.dir_path + "\\plots"
                  fname = plotdir + "\\event" + str(j) + ".png"
                  fig.savefig(fname, format='png', dpi=100)
                  canvas.close()
                  fig.clear()
                  
      def generate_correlate_plots(self):
          fig = Figure()
          
          for j in range(self.wave_quantity):     
              
              canvas = FigureCanvas(fig)
              fig.set_canvas(canvas)
              
              ax1 = fig.add_subplot(2,1,1)
              fig.suptitle("Event " + str(j) + ", Relative Time: " + self.time_difference_string[j]) 
              ax1.plot(self.wave_data[j], '-')
              
              ax2 = fig.add_subplot(2,1,2)
              x = self.wave_data[j]
              y = correlate(x,x,mode='full')[len(x)-1:]       
              ax2.plot(y, '-')
              
              plotdir = self.dir_path + "\\correlate_plots"
              fname = plotdir + "\\event" + str(j) + ".png"
              fig.savefig(fname, format='png', dpi=100)
              canvas.close()
              fig.clear()
              
      def generate_fft_plots(self):
          fig = Figure()
          
          for j in range(self.wave_quantity):
              
              x = self.wave_data[j]
              
              canvas = FigureCanvas(fig)
              fig.set_canvas(canvas)
              
              ax1 = fig.add_subplot(2,1,1)
              
              fig.suptitle("Event " + str(j) + ", Relative Time: " + self.time_difference_string[j]) 
              #fig.suptitle(self.wave_times[j].strftime("%d/%m/%y %H:%M:%S %f"))
              ax1.plot(x, '-')
              
              ax2 = fig.add_subplot(2,1,2)
              y = fft(x)
              n = len(y)
              power = abs(y[1:(n/2)])**2
              nyquist=1./2
              freq=array(range(n/2))/(n/2.0)*nyquist
              period=1./freq[1:len(freq)]
      
              ax2.plot(period, power)
              ax2.set_xscale('log')
              
              plotdir = self.dir_path + "\\fft_plots"
              fname = plotdir + "\\event" + str(j) + ".png"
              fig.savefig(fname, format='png', dpi=100)
              canvas.close()
              fig.clear()
              
              
                       
  #Functions to derive information deriratives from waves
  
  
  
  #Main Program    
  
  dir_path = r"C:\Projects\sgm\analysis\trunk\continuous_c_extract"
  waves = Wave(dir_path)
  waves.read_data_from_csv()
  
  
  waves.read_wave_data()
  ##waves.generate_plots()
  ##waves.generate_correlate_plots()
  ##waves.generate_fft_plots()
  
  
  
  
  
  
  
  
  