% block_alignment:
%
% Sctipt which aligns image mix2 relative to mix1 (calls: "alignment" sctript)
% Alignment is separatly applyed to block images (mixk2,mixk1)
%
% Images after alignment:  mix1_a , mix2_a 
% Control variables:
%   nblocos_i - nš of blocks in the vertical-axis   (yy). Set at 2.
%   nblocos_j - nš of blocks in the horizontal-axis (xx). Set at 2.
%   ctr_fig   - at 1 - enables to see figures,
%               at 0 - no firgures are printed. Set at 0.


mix2=double(mix2);mix1=double(mix1);

% Control variables:
ctr_fig = 0;  % at 1 - enables to see figures,
              % at 0 - no firgures are printed.
nblocos_i = 2; % number of blocks in the vertical-axis   (yy)
nblocos_j = 2; % number of blocks in the horizontal-axis (xx)


[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;
        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_i = ( ( ni*(i-1)+1) : min( ni*(i) , idim ) );
        indis_j = ( ( nj*(j-1)+1) : min( nj*(j), idim) );
        %%% ++
        mix1_a(indis_i , indis_j ) = mix1a;
        mix2_a(indis_i , indis_j ) = mix2a;
        
    end
end

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