import os, sys
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
#from creader import ClusterFileReader
import creader as cr
import clustersFunctions as cf

imfname= "/mnt/moench_data/moenchLGAD_maxIV_202403/clust/En1600eV_300V_-20deg_W17_ExitSlit0/En1600eV_300V_-20deg_W17_xray_d0_f0_1_f00000.tiff"
fname = "/mnt/moench_data/moenchLGAD_maxIV_202403/clust/En1600eV_300V_-20deg_W17_ExitSlit0/En1600eV_300V_-20deg_W17_xray_d0_f{}_1.clust"
noisefile="/mnt/moench_data/moenchLGAD_maxIV_202403/clust/En1600eV_300V_-20deg_W17_ExitSlit0/En1600eV_300V_-20deg_W17_dark_d0_f0_0_var.tiff"
xmin=0
xmax=400
ymin=0
ymax=400
emin=0
emax=16000

csize=3
gain=1
nbins=100
indmin=0
indmax=0



im=None
h3d=None
h3d1=None



noisemap=np.sqrt(cf.read_tiff_map(noisefile))

cf.plot_colz(noisemap)



for i in range(indmin,indmax+1):
    #ff=fname
    ff=fname.format(str(i))
    print(ff)
    r = cr.ClusterFileReader(ff)
    #im, bins=cf.color_images(r, emin, emax, nbins, xmin, xmax, ymin, ymax,   im, csize, gain)
    h3d=cf.color_images_bh(r, emin, emax, nbins, xmin, xmax, ymin, ymax, h3d, csize, gain, 2*noisemap)



im,xx,yy,ee=h3d.to_numpy()

sp=np.sum(im,axis=(0,1))

#fig, ax = plt.subplots()
#ax.plot(ee[:-1],sp)
#ax.plot(bins[2][:-1],sp)
##ax.set_yscale('log')
#fig.show()

cu=np.sum(im,axis=2)
#cf.plot_colz(cu)



for i in range(indmin,indmax+1):
    #ff=fname
    ff=fname.format(str(i))
    print(ff)
    r = cr.ClusterFileReader(ff)
    h3d1=cf.color_images_bh(r, emin, emax, nbins, xmin, xmax, ymin, ymax, h3d1, csize, gain, None)



im,xx,yy,ee=h3d1.to_numpy()

sp1=np.sum(im,axis=(0,1))

fig, ax = plt.subplots()
ax.plot(ee[:-1],sp1-sp)
#ax.plot(bins[2][:-1],sp)
##ax.set_yscale('log')
fig.show()

cu1=np.sum(im,axis=2)
cf.plot_colz(cu1-cu)

