%% runMotionAutofocus.m script
%%  This is an example of perfoming autofocusing motion
%%  correction using the localized gradient entropy criterion.
%%
%%  Run this script after executing runBflyMotionEstimate.m.
%%  This example uses motionAutofocus.m which is a completely 
%%  matlab-based implementation of the algorithm. A compilable 
%%  mex version (with omp/acml/cuda) is available that runs 
%%  significantly faster.
%%
%% (c) Joseph Y Cheng (jycheng@mrsrl.stanford.edu) 2012

%% SVN info: 
%%   Date:     $Date: 2014-10-17 17:10:46 -0700 (Fri, 17 Oct 2014) $
%%   Revision: $Revision: 1 $
%%   Author:   $Author: jycheng $
%%   Id:       $Id: runMotionAutofocus.m 1 2014-10-18 00:10:46Z jycheng $


%% example1.mat was acquired with partial k-space in the readout
%% direction. Fortunately, the homodyne reconstruction can be 
%% performed post-autofocusing because the autofocusing algorithm
%% depends heavily on the high-frequency contents.

DEBUG_MOTION = 220;
KERNRMM      = 40;

KERNR = round(KERNRMM./res);

% Zero-fill partial k-space
%DATAAh = [zeros(nFRead-nx,ny,nz,nc); DATAA];

% Perform autofocusing!
dbdisp('starting autofocusing...');
[IMC,MOUT] = motionAutofocus3(DATAAc,DDX,DDY,DDZ,...
                              yorder,zorder,KERNR,...
                              DEBUG_MOTION);

% Perform homodyne recon
dbdisp('starting homodyne recon...');
tic;
IMH  = DATAAc;
IMCH = IMC;
for C=1:size(IMC,4)
    tempc = fftnc(IMC(:,:,:,C));
    IMCH(:,:,:,C) = homodyne3D(tempc(end-nx+1:end,:,:),nFRead,1);
    tempo = (IMH(:,:,:,C));
    IMH(:,:,:,C) = homodyne3D(tempo(end-nx+1:end,:,:),nFRead,1);
end
clear tempc tempo;
toc

figure(DEBUG_MOTION+10),imshow3s(flipdim([sumofsq(IMH) sumofsq(IMCH)],1));