%  [mix1_a mix2_a]=block_alignment(mix1, mix2, delta_al1 , rez, nblocos_i, nblocos_j );
%
% Aligns image mix2 relative to mix1. 
% Alignment is separatly applyed to block images (mixk2,mixk1).
% (calls: "alignment" function, which calls "imalign_" function)
%
% Images after alignment:  mix1_a , mix2_a 
% Input variables:
%   nblocos_i - nš of blocks in the vertical-axis   (yy). 
%   nblocos_j - nš of blocks in the horizontal-axis (xx). 
%   delta_al1 - maximal aligment size (in pixels).  
%   rez       - aligment resolution.  


function [mix1_a mix2_a]=block_alignment(mix1, mix2, delta_al1 , rez, nblocos_i, nblocos_j );

% Control variables:
ctr_fig = 0; % at 1 - enables to see figures,
             % at 0 - no firgures are printed.


[idim jdim] = size(mix1);
ni = ceil(idim/nblocos_i);  idelta = ceil(ni/4);
nj = ceil(jdim/nblocos_i);  jdelta = ceil(nj/4);

mix1_a=[]; mix2_a=[];
[idim jdim] = size(mix1);

% Aliment of each block 
for i = 1 : nblocos_i
    for j = 1 : nblocos_j

        indis_i = ( max( ni*(i-1)+1-idelta, 1) : min( ni*(i)+idelta, idim) );
        indis_j = ( max( nj*(j-1)+1-jdelta, 1) : min( nj*(j)+jdelta, jdim) );
        mix1k = mix1( indis_i , indis_j );
        mix2k = mix2( indis_i , indis_j );

        save  auxi.mat  mix1_a mix2_a mix1 mix2
        clear           mix1_a mix2_a mix1 mix2

        % Aliment of blocks mix1k and mix2k
        fprintf('Aligment of block : ( %d , %d ) \n',i,j); 
        % alignment_script;
        [mix1a mix2a]=alignment(mix1k, mix2k, delta_al1 , rez);
        fprintf('n');
        load  auxi.mat
        
      if  max( ni*(i-1)+1-idelta, 1) ~= 1;
            mix1a( 1:idelta ,:)=[]; mix2a( 1:idelta ,:)=[]; end
        if  min( ni*(i)+idelta, idim) ~= idim;
            mix1a( end-idelta+1:end, :)=[];  mix2a( end-idelta+1:end, :)=[];end
        if  max( nj*(j-1)+1-jdelta, 1) ~= 1;
            mix1a( : , 1:jdelta)=[]; mix2a(:, 1:jdelta  )=[]; end
        if  min( nj*(j)+jdelta, jdim) ~= jdim;
            mix1a( :, end-jdelta+1:end )=[];  mix2a(:, end-jdelta+1:end)=[];end
      
        indis_i2 = ( ( ni*(i-1)+1) : min( ni*(i) , idim ) );
        indis_j2 = ( ( nj*(j-1)+1) : min( nj*(j), idim) );
        
        mix1_a(indis_i2 , indis_j2 ) = mix1a;
        mix2_a(indis_i2 , indis_j2 ) = mix2a; 
    end
end

if ctr_fig
figure, imagesc( mix1_a-mix2_a), colormap gray , axis image, title('Alinhamento Final')
end
