%% Input
% clear all
% output folder name
folderName = 'tmp';

%% Setup
sampleList = dir('./source');
deleteFilter = zeros(1, length(sampleList));
for iItem = 1:length(sampleList)
    if sampleList(iItem).isdir || ...
            ~strcmp(sampleList(iItem).name((end-3):end), '.mat')
        deleteFilter(iItem) = 1;
    end
end
sampleList(deleteFilter==1) = [];

% create folder
[a,b,c] = rmdir(['.' filesep folderName], 's');
mkdir(['.' filesep], folderName)
clear a b c deleteFilter iItem

%% process samples
timeVector = nan(1, length(sampleList));
for iSample = 1:length(sampleList)
    thisFileName = sampleList(iSample).name(1:(end-4));
    
    % copy image
    copyfile(['.' filesep 'source' filesep thisFileName '.png'], ...
        ['.' filesep folderName filesep num2str(iSample) '.png'], 'f');
    
    % load data
    load(['.' filesep 'source' filesep thisFileName '.mat'])
    clear bnd shapeFit
    M =double(M);
    
    % process data
    tic
    bnd = obtainBnd(M, 'cart', [], [], [], 1);
    shapeFit = fitShapeBnd(bnd);
%     shapeFit = fitShapeBnd(bnd);
    timeVector(iSample) = toc;
    
    % save data
    save(['.' filesep folderName filesep num2str(iSample) '.mat'])
    
    % draw image
    figure, hold on
    hBnd = viewBoundary(bnd);
    set(hBnd, 'lineStyle', 'none', 'marker', '.', 'markerSize', 2)
%     viewBoundaryShape(shapeFit);
    hShape = viewBoundaryShape(shapeFit);
    set(hShape, 'lineWidth', 1)
    % polar shape
%     cartX = cos(shapeFit.polarAngle).*shapeFit.polarDistance;
%     cartY = sin(shapeFit.polarAngle).*shapeFit.polarDistance;
%     plot(cartX, cartY, 'y.');
    print('-djpeg100', '-r300', ...
        ['.' filesep folderName filesep num2str(iSample) '.jpg']);
%     pause
    close all
    
    % write data
    fileHandle = fopen(['.' filesep folderName filesep num2str(iSample)], 'w');
    fprintf(fileHandle, ['S3=' num2str(shapeFit.sphericity3) '\n']);
    fprintf(fileHandle, ['S2=' num2str(shapeFit.sphericity2) '\n']);
    fprintf(fileHandle, ['S1=' num2str(shapeFit.sphericity) '\n']);
    fprintf(fileHandle, ['w=' num2str(shapeFit.meanWidth) '\n']);
    fprintf(fileHandle, ['l=' num2str(shapeFit.lambda) '\n']);
    fprintf(fileHandle, ['r=' num2str(shapeFit.roughness) '\n']);
    fprintf(fileHandle, ['R=' num2str(2*shapeFit.lambda / shapeFit.meanWidth) '\n']);
    fprintf(fileHandle, ['rr=' num2str(shapeFit.roughness/shapeFit.meanWidth^2*100) '\n']);
    fclose(fileHandle);
    
end
disp(timeVector)
sum(timeVector)