

function [Dist,D]=dicw(d_patch,l)
% Dynamic Image-to-Class Warping Algorithm
% Calculate the DICW distance 
%
% PROTOTYPE
% function [Dist,D]=dicw(d_patch,l)
% 
%
% 
% REFERENCES
% - X. Wei, C.-T. Li, Z. Lei, D. Yi, Stan Z. Li, "Dynamic Image-to-Class ...
% Warping for Occluded Face Recognition", IEEE Trans. Information Forensics...
% and Security (TIFS), vol. 9, no. 12, Dec. 2014 
% 
% INPUTS:
% d_patch         - M * N * K local distance matrix, the distance between probe and all
%                   gallery samples per class
%                   M: number of probe patches
%                   N: number of patches in one gallery image
%                   K: number of gallery images 
% l               - the window length
%
% OUTPUTS:
% Dist            - unnormalized distance matrix
% D               - accumulated distance, the DICW distance between probe
%                   and gallery
%		
%
% NOTES / COMMENTS
% Developed using Matlab 2012a
%
% 
% 
% ABOUT
% Created:        August 2013
% Last Update:    -
% Revision:       1.0
% 
% AUTHOR:   Xingjie Wei
% mailto:   xingjie.wei6@gmail.com
% URL:      

[M, N, K]=size(d_patch);
l = max(l,abs(M-N));

D = ones(M+1,N+1,K)*inf;
% note that matlab array index starts from 1 instead of 0
D(1,1,:) = 0;

for m = 2 : M+1
    for n = max(2,m-l) : min(N+1, m+l)
        minAccum = min(min([D(m-1, n-1,:),D(m-1,n,:),D(m,n-1,:)]));
        D(m,n,:) = d_patch(m-1,n-1,:)  + minAccum;
        
    end
end


 Dist=min(D(M+1,N+1,:));
 





