#!/usr/bin/env python3

import csv
import numpy as np
import os
import struct
import sys
import tarfile
import matplotlib.pyplot as plt
from dfatool.loader import MIMOSA
from dfatool.utils import running_mean

voltage = float(sys.argv[1])
shunt = float(sys.argv[2])
mimfile = sys.argv[3]

mim = MIMOSA(voltage, shunt)

charges, triggers = mim.load_data(mimfile)
trigidx = mim.trigger_edges(triggers)
cal_edges = mim.calibration_edges(
    running_mean(mim.currents_nocal(charges[0 : trigidx[0]]), 10)
)

# charges = charges[charges > 20000]
# charges = charges[charges < 21000]


def show_hist(data):
    bins = np.max(data) - np.min(data)
    if bins == 0:
        bins = 1
    if bins > 1000:
        bins = bins / 10
    # bins = 500
    n, bins, patches = plt.hist(data, bins, normed=0, facecolor="green", alpha=0.75)
    plt.grid(True)
    plt.show()
    print(np.histogram(data, bins=bins))


# show_hist(charges[cal_edges[0]:cal_edges[1]])
# show_hist(charges[cal_edges[4]:cal_edges[5]])
# show_hist(charges[cal_edges[2]:cal_edges[3]])
# show_hist(charges[trigidx[7]:trigidx[8]])
# show_hist(np.array(charges))

# print(charges[cal_edges[0]:cal_edges[1]])
# print(charges[cal_edges[4]:cal_edges[5]])
# print(charges[cal_edges[2]:cal_edges[3]])

plt.hist(
    mim.charge_to_current_nocal(charges[cal_edges[2] : cal_edges[3]]) * 1e-3,
    100,
    normed=0,
    facecolor="blue",
    alpha=0.8,
)
plt.xlabel("mA MimosaCMD")
plt.ylabel("#")
plt.grid(True)
plt.show()
plt.hist(
    mim.charge_to_current_nocal(charges[cal_edges[4] : cal_edges[5]]) * 1e-3,
    100,
    normed=0,
    facecolor="blue",
    alpha=0.8,
)
plt.xlabel("mA MimosaCMD")
plt.ylabel("#")
plt.grid(True)
plt.show()
plt.hist(
    mim.charge_to_current_nocal(charges[cal_edges[0] : cal_edges[1]]) * 1e-3,
    100,
    normed=0,
    facecolor="blue",
    alpha=0.8,
)
plt.xlabel("mA MimosaCMD")
plt.ylabel("#")
plt.grid(True)
plt.show()
plt.hist(
    charges[cal_edges[0] : cal_edges[1]], 100, normed=0, facecolor="blue", alpha=0.8
)
plt.xlabel("Rohwert MimosaCMD")
plt.ylabel("#")
plt.grid(True)
plt.show()