## Copyright (C) 2015 Loriane Weber
## 
## 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 3 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 Octave; see the file COPYING.  If not, see
## <http://www.gnu.org/licenses/>.

## FresnelTransform

## Author: Loriane Weber <lweber@hpc2-0601>
## Created: 2015-07-01


function Id = FresnelTransform_2D(ph, B, D, lambda, oversamp, ftot, gtot)

[m, n]=size(ph);
[m_a, n_a] = size(B);

% check dimensions 
if (m_a != m || n_a != n)
	disp('error in the dimensions !! Phi and B should have the same dimension')
return;
end

u = exp(-B).*exp(+i.*ph);
    
% propagator for the distance D
Pd = exp(-i*pi*lambda*D*(ftot.^2+gtot.^2));  % ifftshift
ud = ones(2*m, 2*n);
ud(1:m,1:n) = u;

ud=fft2(ud);

ud = ud.*(Pd)';
ud = ifft2(ud); 

ud = ud(1:m,1:n);
Id = abs(ud).^2;
	
	if oversamp==2
		ipf = [0.25 0.5 0.25;
			   0.50 1.0 0.50;
			   0.25 0.5 0.25];
		Idd = conv2(Id,ipf,'same')./conv2(ones(size(Id)),ipf,'same');
		Idd = Idd(oversamp:oversamp:end, oversamp:oversamp:end);
		Id=Idd;
	elseif oversamp ==4
   
		ipf = [0.25 0.5 0.5 0.5 0.25;
			   0.50 1.0 1.0 1.0 0.50;
			   0.50 1.0 1.0 1.0 0.50;
			   0.50 1.0 1.0 1.0 0.50;
			   0.25 0.5 0.5 0.5 0.25];
		Idd = conv2(Id,ipf,'same')./conv2(ones(size(Id)),ipf,'same');
		Idd = Idd(oversamp:oversamp:end, oversamp:oversamp:end);
		Id=Idd;
	end % end binning detector
	 
endfunction
