#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug  4 18:32:07 2024

plotramp.py

Pinta 32 píxeles de una serie raw de una rampa. Sólo una.
Pinta la rampa y la pendiente ajustada.

@author: fgl
"""
import numpy as np
from astropy.io import fits
import os
import sys
import matplotlib.pyplot as plt


# las zonas para pintar
cl=[[	39	,	89	,	462	,	562	], \
    [	167	,	217	,	462	,	562	], \
    [	295	,	345	,	462	,	562	], \
    [	423	,	473	,	462	,	562	], \
    [	551	,	601	,	462	,	562	], \
    [	679	,	729	,	462	,	562	], \
    [	807	,	857	,	462	,	562	], \
    [	935	,	985	,	462	,	562	], \
    [	1486	,	1586	,	39	,	89	], \
    [	1486	,	1586	,	167	,	217	], \
    [	1486	,	1586	,	295	,	345	], \
    [	1486	,	1586	,	423	,	473	], \
    [	1486	,	1586	,	551	,	601	], \
    [	1486	,	1586	,	679	,	729	], \
    [	1486	,	1586	,	807	,	857	], \
    [	1486	,	1586	,	935	,	985	], \
    [	1063	,	1113	,	1486	,	1586	], \
    [	1191	,	1241	,	1486	,	1586	], \
    [	1319	,	1369	,	1486	,	1586	], \
    [	1447	,	1497	,	1486	,	1586	], \
    [	1575	,	1625	,	1486	,	1586	], \
    [	1703	,	1753	,	1486	,	1586	], \
    [	1831	,	1881	,	1486	,	1586	], \
    [	1959	,	2009	,	1486	,	1586	], \
    [	462	,	562	,	1063	,	1113	], \
    [	462	,	562	,	1191	,	1241	], \
    [	462	,	562	,	1319	,	1369	], \
    [	462	,	562	,	1447	,	1497	], \
    [	462	,	562	,	1575	,	1625	], \
    [	462	,	562	,	1703	,	1753	], \
    [	462	,	562	,	1831	,	1881	], \
    [	462	,	562	,	1959	,	2009	]]


ncan=32

if (len(sys.argv) - 1)<3:
    print('This script needs 3 arguments: ')
    print('\t* the point from which to fit the slope.')
    print('\t* the folder to get the raw data.')
#    print('\t* the suffix of the raw data.')
    print('\t* the first id number of the raw data.')
    sys.exit()


frseci=int(sys.argv[1])
dir_in=sys.argv[2]
if dir_in[-1]!='/':
    dir_in+='/'
regini=int(sys.argv[3])

for root,dirs,files in os.walk(dir_in):
    for name in files:  
      if (sys.argv[3] in name) and ('.fits' in name):
        suffix=name.split(sys.argv[3])[1]
        break



#plt.close('all')
#fig=plt.figure(figsize=(6.56,9.28))

i=regini
while True:
    fname_fits=dir_in+str("%010d" % i)+suffix
    if not os.path.exists(fname_fits):
        i +=1
        continue
    frsec=int(fits.getval(fname_fits,'frsec'))
    ts=float(fits.getval(fname_fits,'tsutc2'))
#    print (frsec)
    if i==regini:  # comienzo
        ts0 = ts
        nfrsec=fits.getval(fname_fits,'nfrsec',0)
        xp=np.arange(nfrsec)
        yp=np.zeros((ncan,nfrsec))
        if frseci < 0 : frseci=int(np.ceil(nfrsec/2))

    data=fits.getdata(fname_fits).astype(float)
    xp[frsec-1]=ts-ts0
    for k in range(ncan):
        xc=int((cl[k][0]+cl[k][1])/2)
        yc=int((cl[k][2]+cl[k][3])/2)
        yp[k,frsec-1]=data[yc,xc]

    if frsec<frseci:
        i += 1
        continue
    elif frsec==frseci:
        reglist=np.zeros(nfrsec-frseci+1,dtype=int)
#        print ('\t\t',tread_nd,tread,exptime,nfrsec,dt)
    reglist[frsec-frseci]=i
    # print (i,frsec,frsec-frseci,*reglist)
    if frsec==nfrsec:
        break
    i += 1    

print ('Procesados ficheros: ',*reglist)
figname=dir_in+str(regini)+'-'+str(i)+'.png'
fig=plt.figure(figsize=(8.2,11.6),dpi=300)

for k in range(ncan):
    xc=(cl[k][0]+cl[k][1])/2
    yc=(cl[k][2]+cl[k][3])/2
    ax = fig.add_subplot(8,4,k+1)
    p= np.polyfit(xp[frseci-1:],yp[k,frseci-1:],1)
    pp= np.poly1d(p)
    plt.plot(xp,yp[k],'rx',xp[frseci-1:],pp(xp[frseci-1:]),'b--',markersize=2)
    plt.text(0.1,0.8,str('%.3f' % p[0])+' adu/s',ha='left',\
             va='center',transform=ax.transAxes,fontsize=5)
    txt=str('%d'%xc)+':'+str('%d'%yc)
    plt.text(.03, 1.07,txt ,ha='left',va='top',\
             transform=ax.transAxes,fontsize=6)
    ax.tick_params(axis='both',pad=1)
    plt.yticks(rotation=90,fontsize=5,va='center')
    plt.xticks(fontsize=5)

fig.tight_layout()
fig.savefig(figname)
plt.close(fig)      
#plt.show()
