import glob, sys
from astropy.io import fits
import statistics
import pandas as pd
import numpy as np
import csv
from uds.config import *

colnames=['Match', 'Ref', 'Dup', 'RA', 'Dec', 'Incl']

flist=glob.glob('../products/tm[1,5,6,7]*en0*.xfm')
total1=0
total2=0

for f in flist:

    pos = f.find("_SourceCatalog")
    key=f[12:pos]
    
    hdul = fits.open(f)
    try:
        tab=hdul[1].data
    except:
        continue
    hdul.close()

    dsrc=f.replace(".xfm",".shu2019.src.fits")
    hdul = fits.open(dsrc)
    try:
        hdr=hdul[0].header
        cdelt=hdr['CDELT2']*3600
    except:
        continue
    hdul.close()

    a11=tab[0]['a11']
    a12=tab[0]['a12']
    a22=tab[0]['a22']
    a21=tab[0]['a21']
    x_scale=tab[0]['x_scale']
    y_scale=tab[0]['y_scale']

    t1=tab[0]['t1']*cdelt
    t2=tab[0]['t2']*cdelt

    sx1=np.sign(a11)*np.sqrt(a11**2 + a12**2)
    sy1=np.sign(a22)*np.sqrt(a21**2 + a22**2)

    sx2=np.sign(a11)*np.sqrt(a11**2 + a21**2)
    sy2=np.sign(a22)*np.sqrt(a12**2 + a22**2)
    
    a1 = np.arctan2(a12/sx1,a11/sy2) * 180 / np.pi * 60
    a2 = np.arctan2(a12/sx1,a22/sy2) * 180 / np.pi * 60

    b1 = np.arctan2(a21,a11) * 180 / np.pi * 60
    b2 = np.arctan2(a21,a22) * 180 / np.pi * 60

    det=a11*a22-a12*a21
    
    alpha=355*np.pi/180
    a3 = np.arctan2(np.sin(alpha),np.cos(alpha)) * 180 / np.pi 

    print("{:+.8} {:+.8}".format(a11,a12))
    print("{:+.8} {:+.8}".format(a21,a22))
    
    #print("{} d {:.10f} s {:.8f} {:.8f} {:.8f} {:.8f} | {:+.8f} {:+.8f} {:+.8f} {:+.8f} t {:+.2f} {:+.2f}".format(obslist[key],np.sqrt(det)*cdelt,sx1*cdelt,sx2*cdelt,sy1*cdelt,sy2*cdelt,a1,a2,b1,b2,t1,t2))
    #print("{} d {:.10f} s {:.8f} {:.8f} {:.8f} {:.8f} | {:+.8f} {:+.8f} {:+.8f} {:+.8f} t {:+.2f} {:+.2f}".format(obslist[key],np.sqrt(det)*cdelt,sx1*cdelt,sx2*cdelt,sy1*cdelt,sy2*cdelt,a1,a2,b1,b2,t1,t2))
