'''
Created on Jan 29, 2014

@author: vital
'''
import pyfits

import CodeTools.vitools as vit
import numpy as np
import scipy as sp


def Fits2Data(FolderName,FileName):
    
    #Get the fits file main data and header
    Data, Header_0 = pyfits.getdata(FolderName + FileName, 1, header=True)

    if ('WHTJOINW' in Header_0) or ("STALIGHT" in Header_0) or ("NEBUSPEC" in Header_0):
        x = Data['Wave']
        y = Data['Int']

        return y, x, [Header_0]
    
    #Procedure for dr10 spectra 
    #It returns the spectra redshift corrected and in absolute units
    elif ("COEFF0" in Header_0 and "dr10" in FileName):
        FitsFile = pyfits.open(FolderName + FileName) 
        Spectra = FitsFile[1].data
        Header_2  = FitsFile[2].data
        Header_3 = FitsFile[3].data
        
        Int = Spectra['flux']
        Int_abs = Int / 1e17
        
        WavelenRange = 10.0**Spectra['loglam']
        SDSS_z = float(Header_2["z"][0] + 1)
        Wavelength_z = WavelenRange / SDSS_z

        Headers = (Header_0,Header_2,Header_3)

        return Int_abs, Wavelength_z, Headers
        
    else:
        if Data.ndim == 1: 
            Int = Data
        else:
            Int = Data[0]
            
        if "COEFF0" in Header_0:
            dw = 10.0**Header_0['COEFF1']               # dw = 0.862936 INDEF (Wavelength interval per pixel)
            Wmin = 10.0**Header_0['COEFF0']
            pixels = Header_0['NAXIS1']                 # nw = 3801 number of output pixels
            Wmax     = Wmin + dw * pixels
            WavelenRange = sp.linspace(Wmin,Wmax,pixels,endpoint=False)
            return Int, WavelenRange, [Header_0]
        
        elif "LTV1" in Header_0:
            StartingPix     = -1 * Header_0['LTV1']                   # LTV1 = -261. 
            Wmin_CCD        = Header_0['CRVAL1']
            dw              = Header_0['CD1_1']                       # dw = 0.862936 INDEF (Wavelength interval per pixel)
            pixels          = Header_0['NAXIS1']                      # nw = 3801 number of output pixels
            Wmin            = Wmin_CCD + dw * StartingPix
            Wmax            = Wmin + dw * pixels
            WavelenRange    = np.linspace(Wmin,Wmax,pixels,endpoint=False)
            
            return Int, WavelenRange, [Header_0]
        
        else:
            Wmin            = Header_0['CRVAL1']
            dw              = Header_0['CD1_1']                       # dw = 0.862936 INDEF (Wavelength interval per pixel)
            pixels          = Header_0['NAXIS1']                      # nw = 3801 number of output pixels
            Wmax            = Wmin + dw * pixels
            WavelenRange    = np.linspace(Wmin,Wmax,pixels,endpoint=False)
                            
            return WavelenRange, Int, [Header_0]


def Fits2Data_Old(FolderName,FileName):
    FitsFile = pyfits.open(FolderName + FileName) 
    TotalInt = FitsFile[0].data
    if TotalInt.ndim == 1: 
        Int = TotalInt
        MaxInten = max(Int)
    else:
        Int = TotalInt[0,0,:]
        MaxInten = max(Int)
    N_Inten = Int / MaxInten

    if "COEFF0" in FitsFile[0].header:
        dw = 10.0**FitsFile[0].header['COEFF1']               # dw = 0.862936 INDEF (Wavelength interval per pixel)
        Wmin = 10.0**FitsFile[0].header['COEFF0'] + dw
        pixels = FitsFile[0].header['NAXIS1']                 # nw = 3801 number of output pixels
        Wmax = Wmin + dw * pixels
        WavelenRange = sp.linspace(Wmin,Wmax,pixels,endpoint=False)
        FitsFile.close()
        return Int, N_Inten, WavelenRange, Wmin, Wmax 
    
    else:
        if "LTV1" in FitsFile[0].header:
            StartingPix = -1 * FitsFile[0].header['LTV1']     # LTV1 = -261. 
            Wmin_CCD = FitsFile[0].header['CRVAL1']
            dw = FitsFile[0].header['CD1_1']                  # dw = 0.862936 INDEF (Wavelength interval per pixel)
            pixels = FitsFile[0].header['NAXIS1']             # nw = 3801 number of output pixels
            Wmin = Wmin_CCD + dw * StartingPix
            Wmax = Wmin + dw * pixels
            WavelenRange = sp.linspace(Wmin,Wmax,pixels,endpoint=False)
            FitsFile.close()
            return Int, N_Inten, WavelenRange, Wmin, Wmax
        else:
            Wmin = FitsFile[0].header['CRVAL1']
            dw = FitsFile[0].header['CD1_1']                  # dw = 0.862936 INDEF (Wavelength interval per pixel)
            pixels = FitsFile[0].header['NAXIS1']             # nw = 3801 number of output pixels
            Wmax = Wmin + dw * pixels
            WavelenRange = sp.linspace(Wmin,Wmax,pixels,endpoint=False)
            FitsFile.close()
            return Int, N_Inten, WavelenRange, Wmin, Wmax 
       
def StarlightFileManager(FileFolder, FileName):
    DataFile = open(FileFolder + FileName,"r")
    
    StarlightOutput = DataFile.readlines()
    
    DataFile.close()
        
    ## Synthesis Results - Best model ##
    Chi2Line = vit.LineFinder(StarlightOutput, "[chi2/Nl_eff]")
    AdevLine = vit.LineFinder(StarlightOutput, "[adev (%)]")
    SumXdevLine = vit.LineFinder(StarlightOutput, "[sum-of-x (%)]")
    v0_min_Line = vit.LineFinder(StarlightOutput, "[v0_min  (km/s)]")