beam = (ch['BMAJ']*ch['BMIN'] * np.pi * u.deg**2)
cont_offset = (2.73*u.K).to(u.Jy,u.brightness_temperature(beam,14.488*u.GHz))

extra_cont_offset = 0.05

contlev = cont_offset.value + extra_cont_offset + noisefloor


#spec2 = f2[0].data[0,350:600,:,:] + 0.03
spec2 = f2[0].data[190:293,:,:] + contlev + cont2
# try to "subtract out" the negative continuum...
#spec2[:,cont2<0] -= cont2[cont2<0]
dosmooth = False
if dosmooth:
    spec2s = cube_regrid.spatial_smooth_cube(spec2,kernelwidth=1.5)

    cont2s = agpy.smooth(cont2+contlev,kernelwidth=1.5)
else:
    spec2s = spec2
    cont2s = cont2
spec2s[:,cont2s<0] -= cont2s[cont2s<0]
#cont2s[cont2s<contlev]=contlev

#cont2 += contlev
#cont2[cont2<contlev+noisefloor]=contlev+noisefloor

# "noise floor" (not really)
#spec2[spec2<0.01] = 0.01

#tau2 = -np.log((spec2/cont2))
def extract_subcube(cubefilename, outfilename, linefreq=218.22219*u.GHz,
                    debug=False, smooth=False, vsmooth=False):
    ffile = fits.open(cubefilename)
    # I don't know why this is necessary, but there were weird bugs showing up
    # if I did not add this (some parts of the cube defaulted to 3e-319)
    ffile[0].data = ffile[0].data.astype('float32')
    hdr = ffile[0].header

    cdk = 'CD3_3' if 'CD3_3' in hdr else 'CDELT3'

    if debug:
        xarr = (np.arange(hdr['NAXIS3'])+1-hdr['CRPIX3']) * hdr[cdk] + hdr['CRVAL3']
        print xarr.min(),xarr.max()

    hdr['CTYPE3'] = 'VELO'
    cdfrq = hdr[cdk]
    crvfreq = hdr['CRVAL3']
    crpixf = hdr['CRPIX3']
    hdr[cdk] = -((cdfrq/crvfreq)*constants.c).to(u.km/u.s).value
    hdr['CRVAL3'] = 0.0
    hdr['CRPIX3'] = (linefreq.to(u.Hz).value-crvfreq)/cdfrq + crpixf
    hdr['CUNIT3'] = 'km/s'

    if debug:
        xarr = (np.arange(hdr['NAXIS3'])+1-hdr['CRPIX3']) * hdr[cdk] + hdr['CRVAL3']
        print xarr.min(),xarr.max()

    for k in ['CTYPE3','CRVAL3',cdk,'CRPIX3','CUNIT3']:
        assert ffile[0].header[k] == hdr[k]

    outhdr = hdr.copy()
    outhdr[cdk] = 1.0
    outhdr['RESTFREQ'] = linefreq.to(u.Hz).value
    outhdr['RESTFRQ'] = linefreq.to(u.Hz).value
    outhdr['CRVAL3'] = 50
    outhdr['CRPIX3'] = 199.5
    outhdr['NAXIS3'] = 400

    if smooth:
        #cubesm = gsmooth_cube(ffile[0].data, [3,2,2], use_fft=True,
        #                      psf_pad=False, fft_pad=False)
        # smoothed with 2 pixels -> sigma=10", fwhm=23"
        # this is an "optimal smooth", boosting s/n and smoothing to 36"
        # resolution.
        kw = 2 if not vsmooth else 4
        cubesm = cube_regrid.spatial_smooth_cube(ffile[0].data, kw,
                                                 use_fft=False,
                                                 numcores=4)
        cubesm = cube_regrid.spectral_smooth_cube(cubesm, 3/2.35,
                                                  use_fft=False,
                                                  numcores=4)
        ffile[0].data = cubesm

        outhdr[cdk] = 3.0
        outhdr['CRVAL3'] = 50
        outhdr['CRPIX3'] = 70
        outhdr['NAXIS3'] = 140
    
    if debug:
        xarr = (np.arange(outhdr['NAXIS3'])+1-outhdr['CRPIX3']) * outhdr[cdk] + outhdr['CRVAL3']
        print xarr.min(),xarr.max()
        xarr = (-xarr/3e5) * linefreq + linefreq
        print xarr.min(),xarr.max()
        return hdr,outhdr

    newhdu = cube_regrid.regrid_cube_hdu(ffile[0], outhdr, order=1,
                                         prefilter=False)

    newhdu.writeto(outfilename, clobber=True)
    
    return newhdu
    makecube.make_flats(cubename,vrange=[-20,60],noisevrange=[150,200])


#import FITS_tools
from astropy.io import fits
from FITS_tools.cube_regrid import gsmooth_cube,spatial_smooth_cube

for cubename in ('LimaBean_H2CO33_cube', 'LimaBean_H213CO33_cube', 'LimaBean_H2C18O33_cube'):

    cubename = os.path.join(outpath,cubename)
    cube = fits.open(cubename+"_sub.fits")
    # OUT OF DATE: for 2-2....
    # kernel = ((2.5*60)**2 -  50.**2)**0.5 / sqrt(8*log(2)) = 60 arcsec
    # 60 arcsec / 15 "/pixel = 4
    cubesm2 = gsmooth_cube(cube[0].data, [5,4,4], use_fft=True, psf_pad=False, fft_pad=False)
    cubesm = spatial_smooth_cube(cube[0].data, kernelwidth=4, interpolate_nan=True)
    cube[0].data = cubesm
    cube.writeto(cubename+"_sub_smoothtoCband.fits",clobber=True)
    cube[0].data = cubesm2
    cube.writeto(cubename+"_sub_smoothtoCband_vsmooth.fits",clobber=True)

    # etamb = 56-64% * 1.37 from GTBpg
    makecube.make_taucube(cubename,
                          cubename+"_continuum.fits",
                          etamb=1.37*0.6,
                          tex=2.0,
                          suffix="_sub_smoothtoCband_vsmooth.fits",
                          outsuffix="_smoothtoCband_vsmooth.fits",
                          TCMB=2.7315+0.4)

    makecube.make_taucube(cubename,