function SectorAnalysisToolbox
% function SectorAnalysisToolbox
%
% Example:
%
% SectorAnalysisToolbox;
%
%   Dr. A. I. Hanna (2007) CMP, UEA, 2008.

% check that all the required libraries are available
str = SAToolboxLibraryCheck;
if ~isempty(str)
    return;
end

% Open, move, and get the handles from the figure file.
ad.figMain = openfig(mfilename, 'reuse');
[ad.version, matfilespath] = getVersion;
fprintf('SectorAnalysisToolbox version: %s\n', ad.version);
% Move the gui and then show it, rather than have it jump all over the
% place.
movegui(ad.figMain, 'center');
handles = guihandles(ad.figMain);
set(ad.figMain, 'DoubleBuffer', 'on');
ad.handles = setupcallbacks(handles);

ad.handles = guihandles(ad.figMain);
ad.handles.dat.StagedDirString = 'Staged';
ad.handles.dat.OriginalsDirString = 'Original';
ad.handles.dat.ProcessedDirString = 'Processed';
ad.handles.segmentation_algs_dir = [matfilespath, filesep, 'SectorAnalysisToolbox' filesep 'SegmentationAlgorithms'] ;
set(ad.figMain, 'Color', get(ad.handles.DetailsPanel, 'BackgroundColor'));


enableButtons(pwd, ad.handles);
ad.handles = UpdateIcons(ad.handles);

setappdata(0,'SectorAnalysisToolboxData',ad);

set(ad.figMain,'visible','on')
% try
%     uiwait(ad.figMain);
% catch
%     if ishandle(ad.figMain)
%         delete(ad.figMain)
%     end
% end
return;
%%
%
function [ver, matlab_files_dir] = getVersion
matlab_files_dir = which('SectorAnalysisToolbox');
[matlab_files_dir] = fileparts(fileparts(matlab_files_dir));
vers = dir([matlab_files_dir, filesep, '*.version']);
vers = {vers.name};
if isempty(vers)
    ver = '1.0';
else
    [p, ver, e, v] = fileparts(vers{1});
end
%%
%
function handles = setupcallbacks(handles)
set(handles.AboutMenuItem, 'callback', {@showAboutBox});
set(handles.HelpMenuItem, 'callback', {@showHelp});
set(handles.BrowseProjectsBtn, 'callback', {@ChangeProject});
set(handles.newProjectBtn, 'callback', {@NewProject});
set(handles.SegmentImagesBtn, 'callback', {@SegmentImages});
set(handles.export_data_menu, 'callback', {@exportDataToFEM});
set(handles.export_to_canvas_menu, 'callback', {@exportDataToCanvas});
set(handles.export_sectorstats_menu, 'callback', {@exportSectorStatsToExcel});
set(handles.export_individualsectorstats_menu,'callback', {@exportIndividualSectorStatsToExcel});
set(handles.export_growth_data_to_excel, 'callback', {@exportGrowthDataToExcel});
set(handles.export_avsectordata_to_excel, 'callback', {@exportAvSectorDataToExcel});
set(handles.showalignededges_menu, 'callback', {@doShowAlignedEdges});
set(handles.SectorEditorBtn, 'callback', {@OpenSectorEditor});
set(handles.shape_align_tool_btn, 'callback', {@OpenSectorWarpingTool});
set(handles.filtering_btn, 'callback', {@OpenFilteringTool});
set(handles.imageProcBtn, 'callback', {@OpenImageProcessingTool});
set(handles.GridEditorBtn, 'callback', {@OpenGridEditorTool});
set(handles.StatViewerBtn, 'callback', {@OpenStatViewer});
set(handles.show_growth_btn, 'callback', {@OpenShowGrowthTool});
set(handles.UngrowingBtn, 'callback', {@OpenUngrowingTool});
set(handles.femReGrowBtn, 'callback', {@OpenFEMGrowthTool});
set(handles.comparewarpedellip_menu, 'callback', {@compareWarpedEllipses});
%set(handles.export_sectornumber_to_excel, 'callback', {@ExtractSectorNumbers});
return

%%
%
function compareWarpedEllipses(menu, evd)
SATLib_RunCompareWarpedCloneTool;
return
%%
%
function OpenSectorEditor(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
SectorEditorTool;
set(ad.figMain, 'Visible','on');
return
%%
%
function doShowAlignedEdges(menu, evd)
show_aligned_edges
return
%%
%
function exportAvSectorDataToExcel(menu, evd)
satio_export_av_grid_data_to_excel;
uiwait(msgbox('Successfully exported data!','Done','modal'));
return
%%
%
function exportGrowthDataToExcel(menu, evd)
satio_export_growth_data_to_excel;
uiwait(msgbox('Successfully exported data!','Done','modal'));
return
%%
%
function exportSectorStatsToExcel(menu, evd)
satlib_sectorStats2Excel
uiwait(msgbox('Successfully exported data!','Done','modal'));
return
%%
%
function exportIndividualSectorStatsToExcel(menu, evd)
satlib_individualsectorStats2Excel
return
%%
%
function exportDataToCanvas(exportcanvas, evd)
ExportGrowthData2Canvas;
return;
%%
%
function exportDataToFEM(menu, evd)
Export2FEMGrowthTool
return
%%
%

function ExtractSectorNumbers(menu, evd)
ExportSectorNumbersToExcel;
return

function showAboutBox(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
D=1:64;D=(D'*D)/64;
uiwait(msgbox(sprintf(...
    'Sector Analysis Toolbox\n\nDr. A. I. Hanna (2006)\nA.Hanna@uea.ac.uk\nVersion %s', ad.version), 'About SectorAnalysisToolbox', 'custom', D, hot(64), 'modal'));
return
%%
%
function OpenFilteringTool(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
NoiseRemovalTool;
set(ad.figMain, 'Visible','on');
return
%%
%
function OpenImageProcessingTool(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
ImageProcessingTool;
set(ad.figMain, 'Visible','on');
return
%%
%
function OpenSectorWarpingTool(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
SectorWarpingTool;
set(ad.figMain, 'Visible','on');
return
%%
%
function OpenGridEditorTool(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
GridEditorTool;
set(ad.figMain, 'Visible','on');
return
%%
%
function OpenStatViewer(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
StatViewerTool;
set(ad.figMain, 'Visible','on');
return
%%
%
function OpenShowGrowthTool(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
ShowGrowthTool;
set(ad.figMain, 'Visible','on');
return
%%
%
function OpenUngrowingTool(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
UngrowingTool;
set(ad.figMain, 'Visible','on');
return
%%
%
% function OpenAlignShapeTool(menu, evd)
% ad = getappdata(0,'SectorAnalysisToolboxData');
% set(ad.figMain, 'Visible', 'off');
% AlignShape;
% set(ad.figMain, 'Visible','on');
% return
% %%
% %
% function OpenOptimiseGridTool(menu, evd)
% ad = getappdata(0,'SectorAnalysisToolboxData');
% set(ad.figMain, 'Visible', 'off');
% OptimiseGridTool;
% set(ad.figMain, 'Visible','on');
% return
%%
%
function OpenFEMGrowthTool(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'Visible', 'off');
FEMGrowthTool;
set(ad.figMain, 'Visible','on');
return

%%
function [handles] = UpdateIcons(handles)
if checkSATDir(pwd)==0
    fprintf('This is not a valid project directory...please use the browse button to select a valid project\n');
    return;
end
if exist([pwd, filesep, 'example.jpg'], 'file')
    I = imread([pwd, filesep, 'example.jpg']);
    if isfield(handles, 'SectorAnalysisToolboxExampleImageAxis')
        imagesc(I, 'Parent', handles.SectorAnalysisToolboxExampleImageAxis);
    end
else
    FILES = findfilesext('jpg', handles.dat.StagedDirString);

    if isempty(FILES)
        I = zeros(200, 200);
    else
        I = imread(FILES{1});
        factor = 200/size(I,1);
        I = imresize(I, factor);
        imwrite(I, 'example.jpg', 'JPG');
    end
    imagesc(I, 'Parent', handles.SectorAnalysisToolboxExampleImageAxis);

end
if isfield(handles, 'SectorAnalysisToolboxExampleImageAxis')
    axis(handles.SectorAnalysisToolboxExampleImageAxis, 'image', 'ij');
    set(handles.SectorAnalysisToolboxExampleImageAxis, 'XTick', [], 'YTick', []);
end
%%
%
function [] = enableButtons(d, handles)
if checkSATDir(d)
    set([handles.filtering_btn, handles.show_growth_btn,handles.imageProcBtn, handles.SegmentImagesBtn, handles.SectorEditorBtn, handles.GridEditorBtn, handles.StatViewerBtn, handles.UngrowingBtn, handles.shape_align_tool_btn], 'Enable', 'on');
else
    set([handles.filtering_btn, handles.show_growth_btn,handles.imageProcBtn, handles.SegmentImagesBtn, handles.SectorEditorBtn, handles.GridEditorBtn, handles.StatViewerBtn, handles.UngrowingBtn, handles.shape_align_tool_btn], 'Enable', 'off');
end
set(handles.cwdTxt, 'String', strlenn(d, 50));
set(handles.matlabFilesTxt, 'String', strlenn(which('SectorAnalysisToolbox'), 103));
return;
%%
%
function ChangeProject(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
directoryname = uigetdir(pwd, 'Select Project Directory');
if directoryname==0
    disp('User pressed Cancel');
else
    [pathname, rootDir] = fileparts(directoryname);
    cd(directoryname);
    enableButtons(pwd, ad.handles);
    ad.handles = UpdateIcons(ad.handles);
end
setappdata(0,'SectorAnalysisToolboxData', ad);
%%
function NewProject(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
directoryname = uigetdir(pwd);
if directoryname == 0
    return;
end
prompt={'Enter the name of the new project:'};
name='New Project Name';
numlines=1;
defaultanswer={''};
answer=inputdlg(prompt,name,numlines,defaultanswer);
if ~isempty(answer)
    project_directory = [directoryname, filesep, 'SAP_', answer{1}];
    if ~exist(project_directory, 'dir'); mkdir(project_directory); end;
    if ~exist([project_directory, filesep, 'Original'], 'dir'); mkdir([project_directory, filesep, 'Original']); end;
    if ~exist([project_directory, filesep, 'Staged'], 'dir'); mkdir([project_directory, filesep, 'Staged']); end;
    if ~exist([project_directory, filesep, 'Processed'], 'dir'); mkdir([project_directory, filesep, 'Processed']); end;
    cd(project_directory);
    if ~checkSATDir(project_directory)
        error('Could not create directory structure properly please contact the administrator for SectorAnalysisToolbox');
    end
end
enableButtons(pwd, ad.handles);
setappdata(0,'SectorAnalysisToolboxData', ad);
return;
%%
function SegmentImages(menu, evd)
ad = getappdata(0,'SectorAnalysisToolboxData');
set(ad.figMain, 'visible', 'off');
algorithm = get_project_segmentation_algorithm(ad.handles.segmentation_algs_dir);
if isempty(algorithm)
    set(ad.figMain, 'visible', 'on');
    return;
end
StagedDirString = ad.handles.dat.StagedDirString;
%FILES = [FindFilenames('JPG', StagedDirString), FindFilenames('jpg', StagedDirString)];
FILES = findfilesext('jpg', StagedDirString);

if isempty(FILES); set(ad.figMain, 'visible', 'on'); return; end;
[s,v] = listdlg('Name', 'Files To Segment', 'PromptString','Select the files you wish to segment:', 'SelectionMode','multiple', 'ListString',FILES, 'ListSize', [300, 200]);
FILES = FILES(s);
for i=1:length(FILES)
    name = FILES{i};
    parent_dir = get_parent_dir(name);
    [path, name, ext, versn] = fileparts(name);
    I = imread([path, filesep, name, ext]);
    fprintf('Proseccing image %s\n', [path, filesep, name, ext]);
    if (size(I,1)>2500) && (size(I,2)>2500)
        fprintf('%s exceeds maximum dimensions. Maximum Dimensions: 2500x2500\n', [path, filesep, name, ext]);
    else
        w = waitbar(0, sprintf('%s', ['Processing Image ', name]));
        set(findall(w,'type','text'),'Interpreter','none')
         
    if exist([path, filesep,'lastval.mat'])
       close(w);
       w =  open([path, filesep,'lastval.mat']);      
    end 
        [w, orig, im, binim, sectors] = feval(algorithm, I, w);

        ad.oldval = w;

        if sum(binim(:))>0
            E = binim2SortedEdge(binim);
       
            if strcmp(parent_dir, name)==0
                %if ~exist([path, filesep, name], 'dir');
                mkdir([path, filesep, name]);
                [STATUS,MESSAGE,MESSAGEID] = movefile([path, filesep, name, ext], [path, filesep, name,filesep, name, ext]);
                path = [path, filesep, name]; %#ok<AGROW>
            end
            imwrite(sectors, [path, filesep, name, '_sectors.tif'], 'TIFF');
            imwrite(binim, [path, filesep, name, '_organ.tif'], 'TIFF');
            save([path, filesep, 'edge_xy.mat'], 'E');
              if ishandle(w)   
                close(w);
              else
                save([path, filesep,'lastval.mat'], 'w');
             end
        else
            fprintf('WARNING: Empty binary image %s\n', name);
        end
    end
end
set(ad.figMain, 'visible', 'on');
setappdata(0,'SectorAnalysisToolboxData', ad);
return
