# 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
    """
    NAME:
       convolve
    PURPOSE:
       convolve with the APOGEE LSF and resample to APOGEE's apStar wavelength grid
    INPUT:
       wav - wavelength array (linear in wavelength in \AA)
       spec - spectrum on wav wavelength grid [nspec,nwave]
       lsf= (None) pre-calculated LSF array from apogee.spec.lsf.eval
       Either:
          xlsf= (None) 1/integer equally-spaced pixel offsets at which the lsf=lsf input is calculated
          dxlsf= (None) spacing of pixel offsets
       fiber= if lsf is None, the LSF is calculated for this fiber
       vmacro= (6.) Gaussian macroturbulence smoothing to apply as well (FWHM or a [sparse] matrix like lsf on the same x grid; can be computed with apogee.modelspec.vmacro)
    OUTPUT:
       spectrum on apStar wavelength grid
    HISTORY:
       2015-03-14 - Written - Bovy (IAS)
    """
    # Parse LSF input
    if lsf is None:
        xlsf= numpy.linspace(-7.,7.,43)
        lsf= eval(xlsf,fiber=fiber)
    if not isinstance(lsf,sparse.dia_matrix):
        lsf= sparsify(lsf)
    if dxlsf is None:
        dx= xlsf[1]-xlsf[0]
    else:
        dx= dxlsf
    hires= int(round(1./dx))

# 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

    """
    NAME:
       convolve
    PURPOSE:
       convolve with the APOGEE LSF and resample to APOGEE's apStar wavelength grid
    INPUT:
       wav - wavelength array (linear in wavelength in \AA)
       spec - spectrum on wav wavelength grid [nspec,nwave]
       lsf= (None) pre-calculated LSF array from apogee.spec.lsf.eval
       Either:
          xlsf= (None) 1/integer equally-spaced pixel offsets at which the lsf=lsf input is calculated
          dxlsf= (None) spacing of pixel offsets
       fiber= if lsf is None, the LSF is calculated for this fiber
       vmacro= (6.) Gaussian macroturbulence smoothing to apply as well (FWHM or a [sparse] matrix like lsf on the same x grid; can be computed with apogee.modelspec.vmacro)
    OUTPUT:
       spectrum on apStar wavelength grid
    HISTORY:
       2015-03-14 - Written - Bovy (IAS)
    """
    # Parse LSF input
    if lsf is None:
        xlsf= numpy.linspace(-7.,7.,43)
        lsf= eval(xlsf,fiber=fiber)
    if not isinstance(lsf,sparse.dia_matrix):
        lsf= sparsify(lsf)
    if dxlsf is None:
        dx= xlsf[1]-xlsf[0]
    else:
        dx= dxlsf
    hires= int(round(1./dx))

    l10wav= numpy.log10(apStarWavegrid())