function database_ctu_code_integrity()
% This function loads existing database and performs integrity test
% This test checks if the: factorial(M+N-1)/(factorial(N)*factorial(M-1))
% combinations will be affected with different codes using a some based
% codification system. M gives the spectral resolution and N the spatial
% resolution.

% Copyright 2015 Abdelmounaime Safia
% Last Revision January , 4, 2015

CTU_Codes_Loaded=loadexistingcodes();
[~, nb_spec_res]=size(CTU_Codes_Loaded);

sr=0;
for i=1:nb_spec_res
    if CTU_Codes_Loaded(i).SpectralRes~=2
        sr=length(CTU_Codes_Loaded(i).SpatialRes)+sr;
    end
end



k=0;
for i=1:nb_spec_res
    if CTU_Codes_Loaded(i).SpectralRes~=2
        for j=1:length(CTU_Codes_Loaded(i).SpatialRes)
            NBposition=CTU_Codes_Loaded(i).SpatialRes(j);
            Temp_Code=CTU_Codes_Loaded(i).Codes(j,:);
            fprintf('\n\n Checking CTU code of the case M=%d, N=%d  ... ',length(CTU_Codes_Loaded(i).Codes(j,:)),NBposition);
            fprintf('\n ------------------------------------------');
            Temp_TextUnitComb=GeneralCodeCominationForTextUnit(NBposition,Temp_Code);
            Temp_CodeValidity=somecodificationvalidity (Temp_Code,Temp_TextUnitComb);
            
            
            if Temp_CodeValidity.valid==0
                error('Incorrect CTU code is stored in the database, blease check, N= %d, M=%d',NBposition,length(Temp_Code));
            else
                [HistResol,SpatialRes]=size(Temp_CodeValidity.Combinations);
                str_code=num2str(Temp_CodeValidity.code);
                fprintf('\n Code integrity:  OK');
                fprintf('\n    SpectralRes: %d',length(Temp_CodeValidity.code));
                fprintf('\n     SpatialRes: %d',SpatialRes);
                fprintf('\n      HistResol: %d',HistResol);
                fprintf('\n          Codes: %s',str_code);
                fprintf('\n**********************************************************************************\n');
                k=k+1;
                                
            end
        end
    end
end
fprintf('\n**********************************************************************************\n');
fprintf('\n      There are %d different codes in your database',sr);
fprintf('\n      %d of %d were successfully checked ',k,sr);
fprintf('\n**********************************************************************************\n');
end