def linename_to_restwl(linelistfile = '/Users/adam/work/IRAS05358/code/linelist.txt',outfile='/Users/adam/work/IRAS05358/code/newlinelist.txt'):

    lines = readcol.readcol(linelistfile,fsep='|',twod=False,dtype='S')
    outf = open(outfile,'w')

    for line in transpose(lines):
        name = line[0]
        jre = re.compile('\(([0-9]*)\)').search(name)
        if jre == None:
            print >>outf, "%10s|%10s" % (line[0],line[1])
            continue
        else:
            jl = int( jre.groups()[0] )
        if name[4] == 'S':
            ju = jl + 2
        elif name[4] == 'Q': 
            ju = jl
        elif name[4] == 'O':
            ju = jl - 2
        else:
            print >>outf, "%10s|%10s" % (line[0],line[1])
            continue
        vu = int( name[0] )
        vl = int( name[2] )
        rwl = restwl(vu,vl,ju,jl)
        if rwl == 0:
            rwl = float(line[1])
        print >>outf,"%10s|%10.8f" % (name,rwl)
def readspec(image,noiseimage,
    linelistfile = '/Users/adam/work/IRAS05358/code/linelist.txt',
    path_obs='/Users/adam/work/IRAS05358/spectra/nearir/', #'/Users/adam/observations/IRAS05358/UT090108/',
    noiseaperture=[0,10],
    aperture=[],
    nameregex='2-1 S\(1\)|1-0 S\([1379028]\)|1-0 Q\([1234]\)|3-2 S\([35]\)|4-3 S\(5\)',
    apname='',
    vlsrcorr=0):

    regex = re.compile(nameregex)
    im = pyfits.open(path_obs+image)
    noiseim = pyfits.open(path_obs+noiseimage)
    wlA = im[0].header['CRVAL1'] + im[0].header['CD1_1'] * ( arange(im[0].data.shape[1]) - im[0].header['CRPIX1'] + 1)
    data = im[0].data
    atmospec = median(noiseim[0].data[noiseaperture[0]:noiseaperture[1]],axis=0)

    countsperflux = 2.25e18
    stdatmo = noiseim[0].data[noiseaperture[0]:noiseaperture[1]].std(axis=0)            # std. dev. of non-backsubtracted data
    poisserr = sqrt(abs(noiseim[0].data).mean(axis=0) * countsperflux) / countsperflux  # Poisson noise (very approximate correction)
    errspec = sqrt( stdatmo**2 + 2*poisserr**2 )                 # poisson statistics - once for estimation of the noise, once for the subtraction
    errspec /= atmotrans_vect(wlA)**2                                                  # Weight by inverse of atmospheric transmission^2

    lines = readcol.readcol(linelistfile,fsep='|',twod=False,dtype='S')
    lines[1] = asarray(lines[1],dtype='float')*1e4 # convert microns to angstroms

    specsegments=[]
    for line in transpose(lines):
        wl = float(line[1])
        name = line[0]
        if wl > wlA.min() and wl < wlA.max() and regex.search(name) != None:
            closest = argmin(abs(wlA-wl))
            minind = closest-7
            maxind = closest+7

            if len(aperture) != 0:
                savedata = data[aperture[0]:aperture[1],minind:maxind].sum(axis=0)
            else:
                savedata = data[:,minind:maxind]
            specsegments.append({
                'name':name,
                'apname':apname,
                'linewl':wl,
                'index':closest,
                'minind':minind,
                'maxind':maxind,
                'vlsrcorr':vlsrcorr,
                'wavelength':wlA[minind:maxind],
                'data':savedata,
                'noback':atmospec[minind:maxind],
                'err':errspec[minind:maxind],
                'model':data[0,minind:maxind]*0
#                'smoothdata':convolve( data[:,minind:maxind] , hanning(3) , 'same')
                })

    print "Done finding lines"            

    return specsegments
def readspexspec(image,
    linelistfile = '/Users/adam/work/IRAS05358/code/linelist.txt',
    path_obs='/Users/adam/work/IRAS05358/spectra/nearir/', #'/Users/adam/observations/IRAS05358/UT090108/',
    nameregex='2-1 S\(1\)|1-0 S\([1379028]\)|1-0 Q\([1234]\)|3-2 S\([35]\)|4-3 S\(5\)',
    vlsrcorr=0,
    backsub=False,
    **kwargs):

    regex = re.compile(nameregex)
    im = pyfits.open(path_obs+image)
    wlA = im[0].data[0,:] * 1e4
    data = im[0].data[1,:]

    countsperflux = 2.25e18
    errspec = im[0].data[2,:]

    lines = readcol.readcol(linelistfile,fsep='|',twod=False,dtype='S')
    lines[1] = asarray(lines[1],dtype='float')*1e4 # convert microns to angstroms

    specsegments=[]
    for line in transpose(lines):
        wl = float(line[1])
        name = line[0]
        if wl > wlA.min() and wl < wlA.max() and regex.search(name) != None:
            closest = argmin(abs(wlA-wl))
            minind = closest-7
            maxind = closest+7

            savedata = data[minind:maxind]
            if backsub:
                savedata -= median(savedata[savedata<median(savedata)])
            specsegments.append({
                'name':name,
                'linewl':wl,
                'index':closest,
                'minind':minind,
                'maxind':maxind,
                'vlsrcorr':vlsrcorr,
                'wavelength':wlA[minind:maxind],
                'data':savedata,
                'noback':data[minind:maxind]*0,
                'err':errspec[minind:maxind],
                'model':data[minind:maxind]*0
                })

    print "Done finding lines"            

    return specsegments
    http://webbook.nist.gov/cgi/cbook.cgi?ID=C1333740&Units=SI&Mask=1000#Diatomic
    (see the bottom of the table)
    """

    We=4401.21
    Be=60.853
    WeXe=121.33 
    De=.0471
    Ae=3.062
    re=.74144

    return h * c * (We*(V+0.5) + Be*(J*(J+1)) - WeXe*(V+.5)**2 - De*J**2*(J+1)**2 - Ae*(V+.5)*(J+1)*J)

# read in rest energies before calling function
tablepath='/Users/adam/work/IRAS05358/code/'
resten = readcol.readcol(tablepath+'dalgarno1984_table5.txt',verbose=0)

def restwl(vu,vl,ju,jl):
    """ Uses energy levels measured by Dalgarno, Can J. Physics, 62,1639,1984 
    vu,vl - upper and lower vibrational states
    ju,jl - upper and lower rotational states 
    returns wavelength in microns"""
    if ju >= resten.shape[0] or vu >= resten.shape[1]:
        return 0
    dl = .01/(resten[ju][vu]-resten[jl][vl])
    return dl * 1e6

def linename_to_restwl(linelistfile = '/Users/adam/work/IRAS05358/code/linelist.txt',outfile='/Users/adam/work/IRAS05358/code/newlinelist.txt'):

    lines = readcol.readcol(linelistfile,fsep='|',twod=False,dtype='S')
    outf = open(outfile,'w')