/****************************************************************************
 * Copyright (c) 2007 Einir Valdimarsson and Chrysanthe Preza
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 ****************************************************************************/

#include "estimateEMSVPCA.h"
#include "arrayManip.h"
#include "RectDomainIter.h"

namespace cosm {

// class constructor
template<typename T, int N>
EstimateEMSVPCA<T,N>::EstimateEMSVPCA(
    Array<Array<T,1>, 1>& constant,
    Array< Array<T,N>, 1>& psfs,
    Array<T,N>& img,
    int iterations,
    EstimatePenalty<T,N>* penalty,
    T epsilon

) : 
    EstimateIterative<T,N>(psfs(0), img, iterations, penalty),
    epsilon_(epsilon), constant_(constant)
{
    constant_.resize(constant.length(0));
    psfsF_.resize(psfs.length(0));
    TinyVector<int,N> extent(this->img_.extent());
    s_.resize(extent);
    s1_.resize(extent);
    extent(N-1) = extent(N-1)/2+1;
    estF_.resize(extent);
    sF_.resize(extent);

    sumPsf_.resize(psfs.length(0));
    sumConstant_.resize(constant(0).length(0));

    // resize the psfs and compute the Fourier transform (OTF)
    for ( int m = 0; m < psfs.length(0); m++ ) 
    {
		Array<T,N> psfResized(this->img_.extent()); 
        padCenter(psfs(m), psfResized); 
		psfsF_(m).resize(extent);
        psfsF_(m) = forwardFFT(psfResized);
        sumPsf_(m) = sum(psfs(m));
    }

    // resize constant
    for ( int m = 0; m < constant.length(0); m++ ) 
    {
        constant_(m).resize(constant(m).length(0));
        constant_(m) = constant(m);
    }

    // compute the scaling factors
    //scale_ = T(1.0)/strata.length(0);
}

// Function to specify the psf for new estimation
template<typename T, int N>
void EstimateEMSVPCA<T,N>::setPSF(
    Array<T,N>& psf
) {
    // not implemented
}

// Function to specify the image for new estimation
// NOTE: new img has to be the same size as previous img
template<typename T, int N>
void EstimateEMSVPCA<T,N>::setImage(
    Array<T,N>& img
) {
    EstimateIterative<T,N>::setImage(img);
}

// Function for single iteration of the em algorithm
template<typename T, int N>
void EstimateEMSVPCA<T,N>::iterate(
){
    int m;
    // get convolution of est with interpolation of psfs 
    // (multiplication and in Fourier domain)
    this->old_ = this->est_;
    estF_ = 0;

    for (int m = 0; m < psfsF_.length(0); m++ )
    {
        s_ = this ->est_;
        for (int n = 0; n < s_.extent(0); n++)
        {
            //s(n)* = a(m)(n);
            for (int ind_col = 0; ind_col< s_.extent(1); ind_col++)
                for (int ind_depth = 0; ind_depth< s_.extent(2); ind_depth++)
                    s_(n, ind_col, ind_depth) *= constant_(m)(n);
        }
        fftw_.plan(s_, sF_);
        fftw_.execute();
        estF_ += sF_ * psfsF_(m);
    }

    // convert back to time domain
    fftw_.plan(estF_, this->est_);
    fftw_.execute();
    this->est_ /= this->est_.size();
    // get the ratio of image and convolution
    s_ = where( this->est_ > epsilon_, this->img_/this->est_, this->img_/epsilon_);
    fftw_.plan(s_, estF_);
    fftw_.execute();

    // update estimate by convolving psf with ratio (do it in Fourier domain)
    // and interpolate 
    this->est_ = 0;
    s_ = 0;
    sumConstant_ = 0;
    for ( m = 0; m < psfsF_.length(0); m++ ) 
    {
        sF_ = conj(psfsF_(m)) * estF_; 
        fftw_.plan(sF_, s1_);
        fftw_.execute();
        s1_ /= s1_.size();

        for (int n = 0; n < s1_.extent(0); n++)
        {
            for (int ind_col = 0; ind_col< s1_.extent(1); ind_col++)
                for (int ind_depth = 0; ind_depth< s1_.extent(2); ind_depth++)
                    s1_(n, ind_col, ind_depth) *= constant_(m)(n);
            sumConstant_(n) += sumPsf_(m) * constant_(m)(n);
        }
        s_ += s1_;
    }

    //Normalization
    for (int n = 0; n < s1_.extent(0); n++)
    {
        for (int ind_col = 0; ind_col< s1_.extent(1); ind_col++)
            for (int ind_depth = 0; ind_depth< s1_.extent(2); ind_depth++)
                s_(n, ind_col, ind_depth) /= sumConstant_(n);
     }

    this->est_ = s_ * this->old_;
//    this->est_ *= scale_;
    this->est_ = where( this->est_ > epsilon_, this->est_, 0);

    if ( this->penalty_ != NULL ) 
    {
	this->penalty_->operator()(this->est_);
    }
}

}
