%**************************************************************************
% This function can be used to update the enumeration of the results of
% classification saved in a parent folder, the output is a file in .xlsx
% format.
%
% Input: None
% Output: is_success, a logical variable.if the progress finisihed
% correctely,is_success return True, otherwise it return Flase.
%**************************************************************************
% Author: Kaichang CHENG
% Date: Mar. 3, 2019
%**************************************************************************
% Updated by Hongsheng Bi
% Date April 15 2019
% Major changes: i) removed excel link app.
%                ii) Fixed bugs in the original copy which trunicates group
%                    and generate false counts. 
%                iii) clean up working flow and generated a new excel file.
%                 iv) This procedure now requires function dirPlus.
%**************************************************************************
%clear
%is_success=false;
% Test the oparation system of environment
My_sys=computer;
if My_sys(1)=='P'
    note='\';% For Windows
else
    note='/';% For Linux
end
%%
% Choose the parent folder including the adjusted classification result
rootDir1 = uigetdir('..','Choose parent directory.'); 
resultDir = [rootDir1, note, char(GetSubDirsFirstLevelOnly(rootDir1))];  % Return a list of directories and files
subDir = GetSubDirsFirstLevelOnly(resultDir);

% The new name of the Excel file to be built
fileUpdate = [resultDir, note, 'countResults_Updated_' datestr(now,'yyyy-mm-dd-HH-MM-SS') '.xlsx'];
% create a list of image
tempList1 = dirPlus(rootDir1, 'Struct', true, 'Depth', 0, 'FileFilter', '\.(jpg|bmp|png|tif)$');
imList = {tempList1.name};

tempCount = zeros(length(imList), length(subDir));
for i=1:length(imList)
    % Write category to Excel
    imageName = string(imList(i));
    
    for j=1:length(subDir)

        tempList = dirPlus([resultDir, note, subDir{j}], 'Struct', true, 'FileFilter', '\.(jpg|bmp|png|tif)$');
     
        if isempty(tempList) == 1
            tempCount(i, j) = 0;
        else
            imageListGroup = {tempList.name};
            trueListGroup = cell(length(imageListGroup), 1);
            for k = 1:length(imageListGroup)
                temp1 = imageListGroup{k};
                indfir = max(strfind(temp1,'_'));
                trueListGroup{k} = temp1(1:(indfir-1));
            end
            ind = find(strcmp(imageName, trueListGroup));
            tempCount(i, j) = length(ind);
        end
    end
    disp(imList(i));
end
 
countMatrix = [[{'ImageName'}; imList'] [string(subDir); tempCount]];%Join cell arrays
xlswrite(fileUpdate,countMatrix);

% Update completed!£¡
msgbox('Update complete!','Caution!','warn');
