import numpy as np

def dic_grav2iss (header):
    '''dictionary to convert gravity beam [0,1,2,3] to ISS ids'''
    grv = {7:0,5:1,3:2,1:3}
    iss = [1,2,3,4]
    return dict([(grv[header['ESO ISS CONF INPUT%i'%i]],i) for i in iss])

def dic_grav2dl (header):
    '''dictionary to convert gravity beam [0,1,2,3] to DL ids'''
    grv = {7:0,5:1,3:2,1:3}
    iss = [1,2,3,4]
    return dict([(grv[header['ESO ISS CONF INPUT%i'%i]], int(header['ESO ISS CONF DL%i'%i][2])) for i in iss])

def get_opl (beam, header):
    '''return the OPL in header of a given gravity beam [0,1,2,3]'''
    iss = dic_grav2iss (header)[beam]
    return float(header['HIERARCH ESO ISS CONF A%iL'%iss]) + (float(header['ESO DEL DLT%i OPL START'%iss]) + float(header['ESO DEL DLT%i OPL END'%iss])) * 0.5

def get_air_index (s, header):
    '''return the air index s is wavenumber isn m-1'''
    T = header['HIERARCH ESO ISS AMBI TEMP'] + 273.15 # % K
    H = header['HIERARCH ESO ISS AMBI RHUM'] * 1.0# %
    p = header['HIERARCH ESO ISS AMBI PRES'] * 100.0 # Pa
    return p_mathar(s/100.0,T,H,p) # s in cm-1

def p_mathar(s,T,H,p):
    '''return 1-n of air from Mathar 2007. s in cm-1 ; T in K ; H in % p in Pa'''
    Tref = (273.15 + 16) # K
    pref = 74400.00 # hP
    Href = 10. # %
    sref = 4444.4 # cm-1

    ciref = [0.000199594, 0.113225e-9, -0.438053e-14, 0.101921e-16, -0.296872e-20,  0.311755e-24] # /[cm^i]
    ciT = [0.0583358, -0.330288e-7, 0.811015e-10,-0.514801e-13, 0.150602e-16,-0.157482e-20] # /[cm^i K]
    ciH = [-0.904550e-8, 0.119196e-11, -0.149163e-14, 0.985685e-18, -0.288288e-21, 0.301528e-25] # / [cm^i / %]
    cip = [0.268437e-8, 0.136651e-14, 0.136002e-18, 0.822304e-23, -0.224090e-26, 0.251260e-30] # / [cm^i/Pa]

    nred = s * 0.0
    for i in range(0,6):
        ci = ciref[i] + ciT[i] * (1/T-1/Tref) + ciH[i] * (H-Href) + cip[i] * (p-pref)
        nred += ci * (s - sref)**i

    return nred
