#est_y = np.load(os.path.join(sim_dir, "estimated_y.npy"))

sky_avg = np.empty((3, 12*1024**2))
sky_leak = np.empty((3, 12*1024**2))
sky_res_leak = np.zeros((3, 12*1024**2))

for i in range(3):
    sky_avg[i] = 0.5*(sky_a[i] + sky_b[i])
    if noise:
        sky_avg[i] -= 0.5*(sky_a_noise[i] + sky_b_noise[i])
    sky_leak[i] = sky_pair[i] - sky_avg[i]
    if noise:
        sky_leak[i] -= sky_pair_noise[i]

for i in range(2):
    sky_res_leak[i+1] = sky_corr[i] - sky_avg[i+1]
    if noise:
        sky_res_leak[i+1] -= sky_diff_noise[i]

if action=="load":
    spectra_leak = np.load(os.path.join(sim_dir, "spectra_leak.npy"))
    spectra_res_leak = np.load(os.path.join(sim_dir, "spectra_residual_leak.npy"))
elif action=="create":
    spectra_leak = st.estimate_cl(sky_map=sky_leak, lmax=2000, binary_mask=sky_mask, fwhm=np.radians(beam_fwhm/60.0), pol=True) 
    spectra_res_leak = st.estimate_cl(sky_map=sky_res_leak, lmax=2000, binary_mask=sky_mask, fwhm=np.radians(beam_fwhm/60.0), pol=True) 
    np.save(os.path.join(sim_dir, "spectra_leak"), spectra_leak)
    np.save(os.path.join(sim_dir, "spectra_residual_leak"), spectra_res_leak)
    pass
else:
    print "Provide correct action : (load/create)"
    #sky_avg_all[i] = (1.0/6.0)*(sky_1a[i] + sky_1b[i] + sky_2a[i] + sky_2b[i] + sky_3a[i] + sky_3b[i])
    sky_avg_all[i] = 0.25*(sky_1a[i] + sky_1b[i] + sky_2a[i] + sky_2b[i])
    sky_leak_1[i] = sky_pair_1[i] - sky_avg_1[i]
    sky_leak_2[i] = sky_pair_2[i] - sky_avg_2[i]
    #sky_leak_3[i] = sky_pair_3[i] - sky_avg_3[i]
    sky_leak_all[i] = sky_all[i] - sky_avg_all[i]

del sky_1a
del sky_1b
del sky_2a
del sky_2b
#del sky_3a
#del sky_3b

if action=="load":
    spectra_leak_1 = np.load(os.path.join(sim_dir, "spectra_leak_1.npy"))
    spectra_leak_2 = np.load(os.path.join(sim_dir, "spectra_leak_2.npy"))
    #spectra_leak_3 = np.load(os.path.join(sim_dir, "spectra_leak_3.npy"))
    spectra_leak_all = np.load(os.path.join(sim_dir, "spectra_leak_all.npy"))
elif action=="create":
    spectra_leak_1 = st.estimate_cl(sky_map=sky_leak_1, lmax=2000, binary_mask=sky_mask, fwhm=np.radians(beam_fwhm/60.0), pol=True) 
    spectra_leak_2 = st.estimate_cl(sky_map=sky_leak_2, lmax=2000, binary_mask=sky_mask, fwhm=np.radians(beam_fwhm/60.0), pol=True) 
    #spectra_leak_3 = st.estimate_cl(sky_map=sky_leak_3, lmax=2000, binary_mask=sky_mask, fwhm=np.radians(beam_fwhm/60.0), pol=True) 
    spectra_leak_all = st.estimate_cl(sky_map=sky_leak_all, lmax=2000, binary_mask=sky_mask, fwhm=np.radians(beam_fwhm/60.0), pol=True) 
    np.save(os.path.join(sim_dir, "spectra_leak_1"), spectra_leak_1)
    np.save(os.path.join(sim_dir, "spectra_leak_2"), spectra_leak_2)
    #np.save(os.path.join(sim_dir, "spectra_leak_3"), spectra_leak_3)
    np.save(os.path.join(sim_dir, "spectra_leak_all"), spectra_leak_all)
else:
    print "Provide correct action : (load/create)"