PRO stacking_photometry, imstack, flux, aper_param = aper_param, band = band, psf = psf

;+
; NAME: 
;  stacking_photometry
;
; PURPOSE:
;  perform photometry of the stacked image.
;
; CALLING SEQUENCE:
;  stacking_photometry, imstack, flux, [aper_param = aper_param, band =
;  band, psf = psf]
;
;
; INPUTS:
;  IMSTACK: (2*size+1,2*size+1) stacked image
;  
; KEYWORD PARAMETERS:
;  WARNING=> You must choose one (and only one) of the three keyword!!!
;  APER_PARAM: 4-elements vector containing the aperture radius in pixel, the
;  minimum and maximum radii of the sky annulus in pixel, and the
;  aperture correction.
;  BAND: Integer corresponding to the selected band. Use aperture
;  photometry with standard parameters corresponding to a Spitzer
;  band (1 to 4:IRAC bands, 5 to 7: MIPS band). New bands can be
;  added in load_std_aper_param_stacking.pro. Works only for the
;  following size of pixels: IRAC->0.6''/pix; 24um->1.2''/pix;
;  70um->4.''/pix; 160um->8.''/pix
;  PSF: (2*size+1,2*size+1) array representing a centered PSF for a
;  unit flux source. Perform PSF fitting photometry.
;
; OUTPUTS:
;  FLUX: flux of the stacked source in the center of the map
;
; MODIFICATION HISTORY:
;  06/10/2009: written M. Bethermin (IAS)
;
;     Copyright Insitut d'Astrophysique Spatiale
;
;     This program is free software: you can redistribute it and/or modify
;     it under the terms of the GNU General Public License as published by
;     the Free Software Foundation, either version 2 of the License, or
;     (at your option) any later version.
;
;     This program is distributed in the hope that it will be useful,
;     but WITHOUT ANY WARRANTY; without even the implied warranty of
;     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;     GNU General Public License for more details.
;
;     You should have received a copy of the GNU General Public License
;     along with this program.  If not, see <http://www.gnu.org/licenses/>.
;
;-

if keyword_set(aper_param) eq 0 and  keyword_set(band) eq 0 and keyword_set(psf) eq 0 then begin
   print, 'You must choose an option of photometry: user-defined aperture photometry (aper_param keyword), standard aperture photometry corresponding to a predefined band (band keyword) or a psfftting photometry (psf keyword)!!!!!!!'
endif

N = (sqrt(n_elements(imstack))-1)/2

if keyword_set(band) then load_std_aper_param_stacking, band, aper_param

if keyword_set(aper_param) or keyword_set(band) then begin
   badpix = [-1.e10,1.e10]
   phpadu = 1.e10
   apr = aper_param(0)
   skyrad = aper_param[1:2]

   aper, imstack, 1.*N, 1.*N, mags, errap, sky, skyerr, phpadu, apr, skyrad, badpix, /flux, /silent
   flux = aper_param(3)*mags
endif

if keyword_set(psf) then begin
   if n_elements(psf) gt n_elements(imstack) then print, 'PSF larger than stacked image!!!!!!!'
   imstack_conv = imstack-median(imstack)
   imstack_conv = convolve(imstack_conv,psf)*1./total(psf*psf)
   flux = imstack_conv(N,N)
endif

END
