# Path: apogee/tools/download.py
# def _download_file(downloadPath,filePath,dr,verbose=False,spider=False):
#     sys.stdout.write('\r'+"Downloading file %s ...\r" \
#                          % (os.path.basename(filePath)))
#     sys.stdout.flush()
#     try:
#         # make all intermediate directories
#         os.makedirs(os.path.dirname(filePath))
#     except OSError: pass
#     # Safe way of downloading
#     downloading= True
#     interrupted= False
#     file, tmp_savefilename= tempfile.mkstemp()
#     os.close(file) #Easier this way
#     ntries= 1
#     while downloading:
#         try:
#             cmd= ['wget','%s' % downloadPath,
#                   '-O','%s' % tmp_savefilename,
#                   '--read-timeout=10',
#                   '--tries=3']
#             if not verbose: cmd.append('-q')
#             if spider: cmd.append('--spider')
#             subprocess.check_call(cmd)
#             if not spider: shutil.move(tmp_savefilename,filePath)
#             downloading= False
#             if interrupted:
#                 raise KeyboardInterrupt
#         except subprocess.CalledProcessError as e:
#             if not downloading: #Assume KeyboardInterrupt
#                 raise
#             elif 'exit status 5' in str(e):
#                 raise IOError("Download failed because of wget SSL certification error; you can turn off SSL certification checking by setting the option\n\ncheck_certificate = off\n\nin the file $HOME/.wgetrc (create this if it does not exist)")
#             elif ntries > _MAX_NTRIES:
#                 raise IOError('File %s does not appear to exist on the server (as %s) ...' % (os.path.basename(filePath),downloadPath))
#             elif not 'exit status 4' in str(e):
#                 interrupted= True
#             os.remove(tmp_savefilename)
#         except OSError as e:
#             if e.errno == os.errno.ENOENT:
#                 raise OSError("Automagically downloading catalogs and data files requires the wget program; please install wget and try again...")
#             else:
#                 raise
#         finally:
#             if os.path.exists(tmp_savefilename):
#                 os.remove(tmp_savefilename)
#         # Try the mirror and the data both
#         if ntries % 2 == 1:
#             downloadPath= downloadPath.replace('data.sdss','mirror.sdss')
#         else:
#             downloadPath= downloadPath.replace('mirror.sdss','data.sdss')
#         ntries+= 1
#     sys.stdout.write('\r'+_ERASESTR+'\r')
#     sys.stdout.flush()
#     return None
# 
# Path: apogee/spec/plot.py
# _LAMBDASUB= 15000
# _STARTENDSKIP= 30
# def specPlotInputDecorator(func):
#     def input_wrapper(*args,**kwargs):
# def waveregions(*args,**kwargs):
# def detector(*args,**kwargs):
# def windows(*args,**kwargs):
# def highres(*args,**kwargs):
# def highres2pdf(*args,**kwargs):
# def elements(elem,*args,**kwargs):
# def _mark_lines(linewavs,wavemin,wavemax,thisax,lams,spec):
# def _label_all_lines(wavemin,wavemax,thisax,lams,spec,noMolecLines=False):
# def _label_lines(elem,wavemin,wavemax,thisax,lams,spec):


import os, os.path
import warnings
import math
import numpy
import scipy.sparse.linalg
    import fitsio
    import astropy.io.fits as pyfits
import apogee.tools.read as apread
import apogee.tools.path as appath
from functools import wraps
from scipy import special, interpolate, sparse, ndimage
from apogee.tools.download import _download_file
from apogee.spec.plot import apStarWavegrid
        wave0= _WAVEPIX_B[300-fiber]
    if chip == 'c':
        wave0= _WAVEPIX_C[300-fiber]
    pix0= numpy.arange(len(wave0))
    # Need to sort into ascending order
    sindx= numpy.argsort(pix0)
    wave0= wave0[sindx]
    pix0= pix0[sindx]
    # Start from a linear baseline
    baseline= numpy.polynomial.Polynomial.fit(pix0,wave0,1)
    ip= interpolate.InterpolatedUnivariateSpline(pix0,wave0/baseline(pix0),
                                                 k=3)
    out= baseline(pix)*ip(pix)
    # NaN for out of bounds
    out[pix < 0]= numpy.nan
    out[pix > 2047]= numpy.nan
    return out

def _load_precomp(dr=None,fiber='combo',sparse=True):
    """Load a precomputed LSF"""
    if dr is None: dr= appath._default_dr()
    if dr is 'current':
        warnings.warn("Preloaded LSFs for current DR not yet available, falling back on DR12 files")
        dr= '12'
    fileDir= os.path.dirname(appath.apLSFPath('a',dr=dr))
    filePath= os.path.join(fileDir,'apogee-lsf-dr%s-%s.fits' % (dr,fiber))
    # Download the file if necessary
    if not os.path.exists(filePath):
        dlink= \
            filePath.replace(fileDir,'https://zenodo.org/record/16147/files')

# Path: apogee/tools/download.py
# def _download_file(downloadPath,filePath,dr,verbose=False,spider=False):
#     sys.stdout.write('\r'+"Downloading file %s ...\r" \
#                          % (os.path.basename(filePath)))
#     sys.stdout.flush()
#     try:
#         # make all intermediate directories
#         os.makedirs(os.path.dirname(filePath))
#     except OSError: pass
#     # Safe way of downloading
#     downloading= True
#     interrupted= False
#     file, tmp_savefilename= tempfile.mkstemp()
#     os.close(file) #Easier this way
#     ntries= 1
#     while downloading:
#         try:
#             cmd= ['wget','%s' % downloadPath,
#                   '-O','%s' % tmp_savefilename,
#                   '--read-timeout=10',
#                   '--tries=3']
#             if not verbose: cmd.append('-q')
#             if spider: cmd.append('--spider')
#             subprocess.check_call(cmd)
#             if not spider: shutil.move(tmp_savefilename,filePath)
#             downloading= False
#             if interrupted:
#                 raise KeyboardInterrupt
#         except subprocess.CalledProcessError as e:
#             if not downloading: #Assume KeyboardInterrupt
#                 raise
#             elif 'exit status 5' in str(e):
#                 raise IOError("Download failed because of wget SSL certification error; you can turn off SSL certification checking by setting the option\n\ncheck_certificate = off\n\nin the file $HOME/.wgetrc (create this if it does not exist)")
#             elif ntries > _MAX_NTRIES:
#                 raise IOError('File %s does not appear to exist on the server (as %s) ...' % (os.path.basename(filePath),downloadPath))
#             elif not 'exit status 4' in str(e):
#                 interrupted= True
#             os.remove(tmp_savefilename)
#         except OSError as e:
#             if e.errno == os.errno.ENOENT:
#                 raise OSError("Automagically downloading catalogs and data files requires the wget program; please install wget and try again...")
#             else:
#                 raise
#         finally:
#             if os.path.exists(tmp_savefilename):
#                 os.remove(tmp_savefilename)
#         # Try the mirror and the data both
#         if ntries % 2 == 1:
#             downloadPath= downloadPath.replace('data.sdss','mirror.sdss')
#         else:
#             downloadPath= downloadPath.replace('mirror.sdss','data.sdss')
#         ntries+= 1
#     sys.stdout.write('\r'+_ERASESTR+'\r')
#     sys.stdout.flush()
#     return None
# 
# Path: apogee/spec/plot.py
# _LAMBDASUB= 15000
# _STARTENDSKIP= 30
# def specPlotInputDecorator(func):
#     def input_wrapper(*args,**kwargs):
# def waveregions(*args,**kwargs):
# def detector(*args,**kwargs):
# def windows(*args,**kwargs):
# def highres(*args,**kwargs):
# def highres2pdf(*args,**kwargs):
# def elements(elem,*args,**kwargs):
# def _mark_lines(linewavs,wavemin,wavemax,thisax,lams,spec):
# def _label_all_lines(wavemin,wavemax,thisax,lams,spec,noMolecLines=False):
# def _label_lines(elem,wavemin,wavemax,thisax,lams,spec):


# Path: apogee/spec/lsf.py
import os, os.path
import warnings
import math
import numpy
import scipy.sparse.linalg
    import fitsio
    import astropy.io.fits as pyfits
import apogee.tools.read as apread
import apogee.tools.path as appath
from functools import wraps
from scipy import special, interpolate, sparse, ndimage
from apogee.tools.download import _download_file
from apogee.spec.plot import apStarWavegrid

        wave0= _WAVEPIX_B[300-fiber]
    if chip == 'c':
        wave0= _WAVEPIX_C[300-fiber]
    pix0= numpy.arange(len(wave0))
    # Need to sort into ascending order
    sindx= numpy.argsort(pix0)
    wave0= wave0[sindx]
    pix0= pix0[sindx]
    # Start from a linear baseline
    baseline= numpy.polynomial.Polynomial.fit(pix0,wave0,1)
    ip= interpolate.InterpolatedUnivariateSpline(pix0,wave0/baseline(pix0),
                                                 k=3)
    out= baseline(pix)*ip(pix)
    # NaN for out of bounds
    out[pix < 0]= numpy.nan
    out[pix > 2047]= numpy.nan
    return out

def _load_precomp(dr=None,fiber='combo',sparse=True):
    """Load a precomputed LSF"""
    if dr is None: dr= appath._default_dr()
    if dr is 'current':
        warnings.warn("Preloaded LSFs for current DR not yet available, falling back on DR12 files")
        dr= '12'
    fileDir= os.path.dirname(appath.apLSFPath('a',dr=dr))
    filePath= os.path.join(fileDir,'apogee-lsf-dr%s-%s.fits' % (dr,fiber))
    # Download the file if necessary
    if not os.path.exists(filePath):
        dlink= \
            filePath.replace(fileDir,'https://zenodo.org/record/16147/files')

        _download_file(dlink,filePath,dr)