"""
File of helper functions for cbp exposures on the StarDICE system

N. Mondrik
"""

import numpy as np


def calc_exp_time(wavelength, charge_level=1e-7, tmin=1, tmax=300, return_nd_pos=True, nd_max=280., nd_min=40.):
    """
    :param wavelength: Wavelength[s] for which exposure time is to be calculated.  Must be in descending order.
    :param charge_level: Target charge level on integrating sphere photodiode
    :param tmin: Minimum exposure time.
    :param tmax: Maximum exposure time.
    :param return_nd_pos: Specifies whether to return an array of ND filter wheel positions
    :param nd_max: ND filter wheel angle for maximum throughput
    :param nd_min: ND filter wheel angle for minimum throughput

    :return t: Estimated exposure time 
    """
    wavelength = np.atleast_1d(wavelength) 
    scale_factor = charge_level / 1e-7

    mapfile = np.loadtxt('Expected_exp_times_1e-7.txt')
    t = np.interp(wavelength, mapfile[:,0], scale_factor*mapfile[:,1])
    nd_pos = np.ones_like(t)*nd_max
    nd_pos[t<tmin] = nd_min
    t[t<tmin] = tmin
    t[t>tmax] = tmax

    #  If only one point it requested, don't return an array
    if len(t) == 1:
        t = t[0]
        nd_pos = nd_pos[0]
    
    if return_nd_pos:
        return t, nd_pos
    else:
        return t
