#!/usr/bin/env python
from flipper import *
import scipy.ndimage
import pickle
p = flipperDict.flipperDict()
p.readFromFile(sys.argv[1])


#read in the theory
X = numpy.loadtxt(p['theoryCls'])
l = X[:,0]
pi = numpy.pi
tcmb = 2.726e6
clkk =  X[:,4]/4./tcmb**2

Y = numpy.loadtxt(p['theoryCls'].replace('scal','lensed'))

cls = []
for i in xrange(int(sys.argv[2]),int(sys.argv[3])+1):
    map = liteMap.liteMapFromFits('phikappa_%03d/kappa_000.fits'%i)
    if i == 0:
        apod = map.copy()
        apod.data[:] = 0.
        apod.data[10:apod.Ny-10,10:apod.Nx-10] = 1.0
        apod.data = scipy.ndimage.gaussian_filter(apod.data,5,mode='constant')
        #apod.data /= apod.data.mean()
        
    map.data *= apod.data
    p2d = fftTools.powerFromLiteMap(map)
    p2d.divideByPixelWindow()
    lL,lU,lb,clb,clerrb,w  = p2d.binInAnnuli('BIN_100_LOG',nearestIntegerBinning=True)
    cls += [clb]


cl = numpy.mean(cls,axis=0)

fsky = apod.data.sum()/(apod.Ny*apod.Nx*1.0)
print fsky
pylab.loglog(lb,cl/fsky,'o')
pylab.plot(l, clkk)
utils.saveAndShow('clsKappa.png')
pickle.dump([lb,cl/fsky],open("clkappakappa.pkl","w"))

