#!/usr/bin/env python

import numpy as np
import h5py
import matplotlib.pyplot as plt
import sys

def get_wave(frame, ch):
  print(frame.shape)
  wave = frame[:, ch]
  return wave

def comp(fn1, fn2, key1, key2, ch1, ch2):

  # ref
  data  = h5py.File(fn1, 'r')
  frame = np.array(data[key1])
  print(frame.shape)
  # frame = np.transpose(frame, axes=[1, 0])
  # frame = frame[:,800:1600]
  w1 = get_wave(frame, ch1)

  # test
  data  = h5py.File(fn2, 'r')
  frame = np.array(data[key2])
  # frame = np.transpose(frame, axes=[1, 0])
  # frame = frame[:,800:1600]
  w2 = get_wave(frame, ch2)

  labels = [
    '{}, {}, {}'.format(fn1, key1, ch1),
    '{}, {}, {}'.format(fn2, key2, ch2)
  ]
  #labels = [
  #  "CPU-ref",
  #  "Kokkos-CUDA",
  #]

  fontsize = 20
  large_fontsize = 24

  fig, axs = plt.subplots(1,2)
  # axs.set_title('{} {}'.format(fn1, fn2))

  xlim = [1100,1300]
  xlim = [0,6000]

  plt.sca(axs[0])
  axs[0].plot(w1,'-o', label=labels[0])
  axs[0].plot(w2,'-',  label=labels[1])
  #axs[0].plot(w2-w1,'-o',  label='abs. diff.')
  #axs[0].legend(loc='best',fontsize=large_fontsize)
  axs[0].legend(loc='best')
  plt.xlim(xlim)
  # axs[0].xaxis.set_major_locator(plt.MaxNLocator(5))
  plt.xticks(fontsize=fontsize)
  plt.yticks(fontsize=fontsize)
  axs[0].get_yaxis().get_offset_text().set_fontsize(fontsize)
  plt.xlabel('time [tick]', fontsize=fontsize)
  axs[0].grid()

  plt.sca(axs[1])
  plot_rel = False
  if plot_rel :
    cut = 0.01
    w1m = np.ma.masked_where(abs(w1/np.max(w1))<cut,w1)
    w2m = np.ma.masked_where(abs(w1/np.max(w1))<cut,w2)
    axs[1].plot((w2m-w1m)/w1m,'-o',  label='rel. diff.')
  else :
    axs[1].plot(w2-w1,'-o',  label='diff.')
  axs[1].legend(loc='best',fontsize=large_fontsize)
  plt.xlim(xlim)
  plt.xticks(fontsize=fontsize)
  plt.yticks(fontsize=fontsize)
  axs[1].get_yaxis().get_offset_text().set_fontsize(fontsize)
  plt.xlabel('time [tick]', fontsize=fontsize)
  axs[1].grid()

  plt.show()
  
  #print('mean = %f' % np.mean(wave))
  #print('std. = %f' % np.std(wave))


if __name__ == '__main__':
  '''
  fn1: input hdf5 file name 1
  fn2: input hdf5 file name 2
  key1: frame name in fn1
  ch1:  channel number from frame1
  key2: frame name in fn2
  ch2:  channel number from frame2
  '''
  fn1  = sys.argv[1]
  fn2  = sys.argv[2]
  key1 = sys.argv[3]
  ch1  = int(sys.argv[4])
  key2 = key1
  ch2  = ch1
  if len(sys.argv) > 5:
    key2 = sys.argv[5]
  if len(sys.argv) > 6:
    ch2 = sys.argv[6]
  
  comp(fn1, fn2, key1, key2, ch1, ch2)
