 function img = feldkamp(proj, mask, varargin)
%function img = feldkamp(proj, mask, [options])
%
% FBP reconstruction of cone-beam tomography data collected with
% a circular source trajectory.
% See feldkamp_example.m for example.
%
% in:
%	proj	[ns,nt,na]	cone-beam projectons (line integrals)
%	mask	[nx,ny]		logical array of desired (2d) fov support
%
% options:
%	window	[npad]		'ramp' (default), or 'hann', or array.
%				if array, then use samples [-K/2, K/2).
%	'dx' 'dy' 'dz'		voxel dimensions
%	'nz'			# of slices
%	'center_xyz'		image center [pixels] (default: 0)
%	'ds' 'dt'		detector sample spacing (horiz, vert)
%	'offset_st'		detector offset_s,t [integer number of samples
%				or fraction thereof, for 1/4-detector offset.
%	'orbit'			default 360 degrees
%	'orbit_start'		default 0 degrees
%	'dis_src_det'
%	'dis_iso_det'
%	'dis_foc_src'		default inf (flat), or 0 for arc
%	'offset_source'		distance from isocenter to perpendicular ray
%				[the same units (e.g., mm) as pixel_size etc.]
%	'ia_skip' [int]		downsample in angle to save time for tests
%	'use_mex' 0|1		backprojector: 0 for matlab, 1 for mex (default)
%
% out:
%	img	[nx,ny,nz]		reconstructed image
%
% offset_s is an integer or fraction thereof, e.g., 0.25,
% relative to centerline between two central channels.
%
% References: Feldkamp, Davis, Kress, JOSA-A, 1(6):612-9, June 1984.
% Fessler tomography chapter.
%
% Copyright 2004-8-28 Nicole Caparanis, Patty Laskowsky, Taka Masuda,
% and Jeff Fessler, The University of Michigan
% arc detector case contributed by Yingying Zhang 2005-6-13

if nargin == 1 && streq(proj, 'test'), run_mfile_local('feldkamp_example'), return, end
if nargin < 2, help(mfilename), error(mfilename), end

% defaults
arg.use_mex = 1;
arg.window = 'ramp';
arg.dx = nan;
arg.dy = [];
arg.dz = [];
arg.nz = size(proj,2);
arg.center_xyz = [0 0 0]; % center_x,y,z (pixels)
arg.flip_y = 1;

arg.Dsd = []; % 'dis_src_det'
arg.Dod	= []; %	'dis_iso_det'
arg.Dfs = inf; % 'dis_foc_src' default flat
arg.offset_source = 0; % r_off, distance between rotation iso-center
			% and ray from source that is orthogonal to detector.

arg.ds = nan;
arg.dt = [];
arg.offset_st = [0 0]; % offset_s,t
arg.ia_skip = 1;
arg.orbit = 360;
arg.orbit_start = 0;
arg = vararg_pair(arg, varargin, 'subs', ...
	{'dis_src_det', 'Dsd';
	'dis_iso_det', 'Dod'; 
	'dis_foc_src', 'Dfs'});

arg.orbit = deg2rad(arg.orbit);	% to radians
arg.orbit_start = deg2rad(arg.orbit_start);

if isempty(arg.dy), arg.dy = arg.dx; end
if isempty(arg.dz), arg.dz = arg.dx; end
if isempty(arg.dt), arg.dt = arg.ds; end

arg.Dso = arg.Dsd - arg.Dod; 	% src to "isocenter" distance

% step 1: weight the projections as in fan-beam case
proj = feldkamp_weight1(proj, arg.Dsd, arg.Dso, arg.Dfs, ...
		arg.ds, arg.dt, arg.offset_st(1), arg.offset_st(2));

% step 2: filter the (zero padded) projections
[ns nt na] = size(proj);
if arg.use_mex
	pad1 = 0;
else
	pad1 = 2;
end
proj = feldkamp_filter(proj, arg.window, arg.Dsd, arg.Dfs, arg.ds, pad1);

if pad1 % trick: zero at end saves indexing in loop
%	proj = [proj; zeros(2, nt, na)];
	proj(:,end+1,:) = 0;
end

% step 3: cone-beam backprojection of the filtered views
cpu tic
img = feldkamp_back(proj, ns, nt, na, ...
	mask, arg.nz, arg.center_xyz, ...
	arg.dx, arg.dy, arg.dz, arg.flip_y, arg.ds, arg.dt, ...
	arg.offset_st(1), arg.offset_st(2), ...
	arg.Dsd, arg.Dso, arg.Dfs, arg.offset_source, ...
	arg.orbit, arg.orbit_start, arg.ia_skip, arg.use_mex);
cpu toc 'fdk backprojection cpu time:'


%
% feldkamp_weight1()
% step 1: weight the projections as in fan-beam case
%
function proj = feldkamp_weight1(proj, ...
	Dsd, Dso, Dfs, ds, dt, offset_s, offset_t)
[ns nt na] = size(proj);
ss = ([-(ns-1)/2:(ns-1)/2]' - offset_s) * ds;
tt = ([-(nt-1)/2:(nt-1)/2]' - offset_t) * dt;

[ss tt] = ndgrid(ss, tt);
if isinf(Dfs) % flat
	ww1 = Dso * sqrt(1 + (tt/Dsd).^2) ./ sqrt(Dsd^2 + ss.^2 + tt.^2);
elseif Dfs == 0 % arc
	ww1 = (Dso/Dsd) * cos(ss ./ (Dsd * sqrt(1 + (tt/Dsd).^2)));
else
	error('other configurations not implemented.')
end

for ia=1:na % same weighting for each view angle
	proj(:,:,ia) = proj(:,:,ia) .* ww1;
end


%
% feldkamp_filter()
% step 2: filter the (zero padded) projections
%
function proj = feldkamp_filter(proj, window, Dsd, Dfs, ds, pad1)
[ns nt na] = size(proj);
npadh = 2^ceil(log2(2*ns-1));
printf('ns=%d npadh=%d', ns, npadh)

if isinf(Dfs)
	H = fan_filter('flat', npadh, ds, [], window);	% [nb,1]
elseif Dfs == 0
	H = fan_filter('arc', npadh, ds, Dsd, window);
end
H = ds * H; % differential for discrete-space convolution vs integral

proj = ifft_sym( fft(proj, npadh, 1) .* repmat(H, [1 nt na]) );
proj = proj(1:(ns+pad1),:,:); % trick: extra zero at end saves indexing in loop


%
% fan_filter()
% apodized filter frequency response
%
function H = fan_filter(type, n, ds, Dsd, window)

if streq(type, 'flat')
	h = fbp_ramp('flat', n, ds);
else
	h = fbp_ramp('arc', n, ds, Dsd);
end
H = reale(fft(fftshift(h)));

if ischar(window)
	if streq(window, 'ramp')
		window = ones(n,1);
	elseif streq(window, 'hann')
		window = hann(n, 'periodic');
	else
		error 'unknown window'
	end
elseif length(window) ~= n
	error 'bad window length'
end

H = H .* fftshift(window);


%
% feldkamp_back()
% step 3: cone-beam backprojection of the filtered views
%
function img = feldkamp_back(proj, ns, nt, na, mask, nz, center_xyz, ...
	dx, dy, dz, flip_y, ds, dt, offset_s, offset_t, ...
	Dsd, Dso, Dfs, offset_source, orbit, orbit_start, ia_skip, use_mex)
[nx ny] = size(mask);

% precompute as much as possible
wx = (nx+1)/2 + center_xyz(1);
wy = (ny+1)/2 + center_xyz(2);
wz = (nz+1)/2 + center_xyz(3);
[xc yc] = ndgrid(([1:nx] - wx) * dx, -flip_y * ([1:ny] - wy) * dy);
zc = ([1:nz] - wz) * dz;
rr = sqrt(xc.^2 + yc.^2);	% [nx,ny]
smax = ((ns-1)/2-abs(offset_s)) * ds; % maximum detector s coordinate

if isinf(Dfs)
	gamma_max = atan(smax/Dsd);
elseif Dfs == 0
	gamma_max = smax / Dsd;
end

rmax = Dso * sin(gamma_max);
mask = mask & (rr < rmax);
clear wx wy wz rr smax rmax

betas = orbit_start + orbit * [0:na-1] / na;	% [na] source angles

% mex backprojector
if use_mex
	fdk_type = 'fdk,ts';
	if Dfs==0
		fdk_type = [fdk_type ',arc,back'];
	elseif isinf(Dfs)
		fdk_type = [fdk_type ',flat,back'];
	else
		error 'unknown type'
	end

	proj = single(proj);
	proj = permute(proj, [2 1 3]); % ts

	nthread = int32(1);
	img = 0;
	for ia=1:na
		ticker(mfilename, ia, na)
		% trick: -dy
		tmp = jf_mex(fdk_type, int32([nx ny nz]), [dx -dy dz], ...
			center_xyz, int8(mask), ...
                	Dso, Dsd, [ds dt], [offset_s offset_t], ...
			proj(:,:,ia), betas(ia), nthread);
		tmp = double6(tmp);
		img = img + tmp;
	end
	img = permute(img, [2 3 1]); % ts
	img = (0.5 * orbit / (na/ia_skip)) * img; % final "\der angle" scale
return
end

xc = xc(mask);	% [np] pixels within mask
yc = yc(mask);

% loop over slices
img = zeros([size(mask) nz]);
ticker reset
for iz=1:nz

	% loop over each projection angle
	img2 = 0;
	for ia=1:na
		ticker(mfilename, [iz ia], [nz na])
		beta = betas(ia);

		x_beta = +xc * cos(beta) + yc * sin(beta);
		y_beta = -xc * sin(beta) + yc * cos(beta);

		% detector indices
		mag = Dsd ./ (Dso - y_beta);

		if isinf(Dfs)
			sprime = mag .* x_beta;
		elseif (Dfs == 0)
			d_loop = Dso - y_beta;
			r_loop = x_beta - offset_source;
			sprime = Dsd * atan2(r_loop, d_loop);
		end

		tprime = mag * zc(iz);
		bh = sprime / ds + (ns+1)/2 + offset_s;
		bv = tprime / dt + (nt+1)/2 + offset_t;

		% bi-linear interpolation:
		ih = floor(bh); % left bin
		iv = floor(bv);
		igood = 1<=ih & ih<ns & 1<= iv & iv<nt;

		ih(~igood) = ns+1; % trick! point at harmless zeros
		iv(~igood) = 1;

		wr = bh - ih;	% left weight
		wl = 1 - wr;	% right weight
		wu = bv - iv;	% upper weight
		wd = 1 - wu;	% lower weight

		sdim = size(proj);
		ia1 = ia * ones(size(ih));

		p1 =	wl .* proj(sub2ind(sdim, ih,iv,ia1)) + ...
			wr .* proj(sub2ind(sdim, ih+1,iv,ia1));
		p2 =	wl .* proj(sub2ind(sdim, ih,iv+1,ia1)) + ...
			wr .* proj(sub2ind(sdim, ih+1,iv+1,ia1));

		p0 = wu .* p1 + wd .* p2; % vertical interpolation

		if isinf(Dfs)
			p0 = p0 .* mag.^2; % back-projection weighting for flat
		elseif Dfs == 0
			p0 = p0 .* (Dsd.^2) ./ (r_loop.^2 + d_loop.^2);
		end

		img2 = img2 + p0;
	end % ia

	img(:,:,iz) = embed(img2, mask);
end % iz

img = (0.5 * orbit / (na/ia_skip)) * img; % final "\der angle" scale
