function []=SectorAnalysisToolbox(arg, argoption)
%Hanna, 2005
% Global figure handles
global SectorAnalysisToolbox_figure_handle
matlab_files_dir = which('SectorAnalysisToolbox');
[matlab_files_dir, f, e, v] = fileparts(matlab_files_dir);
[matlab_files_dir, f, e, v] = fileparts(matlab_files_dir);
vers = dir([matlab_files_dir, filesep, '*.version']);
vers = {vers.name};
if isempty(vers)
    VersionNumber = '1.0';
else
   [p, VersionNumber, e, v] = fileparts(vers{1});
end
if nargin>0
    if strcmpi(arg, '-version')
        fprintf('SectorAnalysisToolbox version: %s\n', VersionNumber);
        return;
    end
end

if nargin<1
   str = SAToolboxLibraryCheck;
    if ~isempty(str)
        return;
    end
    arg='Initialise';
    
end
if nargin<2
    argoption='';
end
%  in case the window is invisible
if exist('SectorAnalysisToolbox_figure_handle') %#ok<EXIST>
    if ishandle(SectorAnalysisToolbox_figure_handle)
        set(SectorAnalysisToolbox_figure_handle,'visible','on');
    end
end
if ~strcmp(arg,'Quit')
    switch arg
        case 'Initialise'
            Data=Initialise(arg,argoption);
            Data.version = VersionNumber;
            SectorAnalysisToolbox_figure_handle=Data.handles.figMain;
        otherwise
            Data = guidata(findobj('Tag', 'SectorAnalysisToolbox'));
            switch arg
                case 'help'
                    uiwait(msgbox('Web help should be here','Help','help'));
                case 'ShowAbout'
                    D=1:64;D=(D'*D)/64;
                    uiwait(msgbox(sprintf(...
                        'Sector Analysis Toolbox\n\nDr. A. I. Hanna (2006)\naih@cmp.uea.ac.uk\nVersion %s', Data.version), 'About SectorAnalysisToolbox', 'custom', D, hot(64), 'modal'));
                case 'ChangeProject'
                    [Data.handles] = ChangeProject(Data.handles);
                case 'NewProject'
                    [Data.handles] = NewProject(Data.handles);
                case 'SegmentImages'
                    [Data.handles] = SegmentImages(Data.handles);
                case 'CalcSectorInformation'
                    fprintf('function disabled\n');
%                    [Data.handles] = CalcSectorInformation(Data.handles);
                case 'ExportData'
                    Export2FEMGrowthTool;
                    %Export2ObjFormat;
                case 'ExportSectorStats'
                    satlib_sectorStats2Excel;
                case 'ShowAlignedEdges'
                    show_aligned_edges;
                case 'SectorEditorTool'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    SectorEditorTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'FilteringTool'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    NoiseRemovalTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'ImageProcessingTool'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    ImageProcessingTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'SectorWarpingTool'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    SectorWarpingTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'GridEditorTool'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    GridEditorTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'StatViewer'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    StatViewerTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'ShowGrowth'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    ShowGrowthTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'UngrowingTool'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    UngrowingTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'AlignShapeTool'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    AlignShape;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'OptimiseGrid'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    OptimiseGridTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'FEMGrowth'
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'off');
                    FEMGrowthTool;
                    set(SectorAnalysisToolbox_figure_handle, 'Visible', 'on');
                case 'ExportGrowthToExcel'
                    satio_export_growth_data_to_excel;
                otherwise
            end
    end
    guidata(Data.handles.figMain, Data);
else
    clear global;
    remaining_globals = whos('global');
    if length(remaining_globals)>0
        fprintf('Warning!!! Some global variables have remained active\n');
    end
    closereq;
    return;
end
%%%%%%%%%%%%%%%%%%%%
%
% UpdateIcons
%
%%%%%%%%%%%%%%%%%%%%
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);
    %else
        %SectorAnalysisToolbox('Quit');
        %SectorAnalysisToolbox;
        %return;
    end
else
    %FILES = FindFilenames('JPG', handles.dat.StagedDirString);
    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
%%%%%%%%%%%%%%%%%%%%
%
% Initialize
%
%%%%%%%%%%%%%%%%%%%%
function Data=Initialise(arg,argoption)
if nargin<2
    argoption='';
end
p = which ('SectorAnalysisToolbox');
p = fileparts(fileparts(fileparts(p)));
% Open the GUI for display
fig = openfig(mfilename, 'reuse');
% Generate a structure of handles to pass to callbacks, and store
Data.handles = guihandles(fig);
Data.handles.dat.StagedDirString = 'Staged';
Data.handles.dat.OriginalsDirString = 'Original';
Data.handles.dat.ProcessedDirString = 'Processed';
Data.handles.segmentation_algs_dir = [p, filesep, 'SAT_Matlab_files_AIH\SectorAnalysisToolbox\SegmentationAlgorithms'] ;
set(fig, 'Color', get(Data.handles.DetailsPanel, 'BackgroundColor'));
Data.handles.figMain = fig;
movegui(fig, 'center')
set(fig, 'Visible', 'on');
enableButtons(pwd, Data.handles);
Data.handles = UpdateIcons(Data.handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Enable buttons based on path validity
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [] = enableButtons(d, handles)
if checkSATDir(d)
    set([handles.filtering_btn, handles.calc_sector_info_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.calc_sector_info_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;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   Change Project
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [handles] = ChangeProject(handles)
directoryname = uigetdir(pwd, 'Select Project Directory');
if directoryname==0
    disp('User pressed Cancel');
else
    [pathname, rootDir] = fileparts(directoryname);
    cd(directoryname);
    enableButtons(pwd, handles);
    handles = UpdateIcons(handles);
end

%%%%%%%%%%%%%%%%%%%%
%
% New Project
%
%%%%%%%%%%%%%%%%%%%%
function [handles] = NewProject(handles)
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, handles);
return;


%%%%%%%%%%%%%%%%%%%%%%%%
%
% CalcSectorInformation
%
%%%%%%%%%%%%%%%%%%%%%%%%
function [handles] = CalcSectorInformation(handles)
set(handles.figMain, 'visible', 'off');
StagedDirString = handles.dat.StagedDirString;
%FILES = FindFilenames('JPG', StagedDirString);
FILES = findfilesext('jpg', StagedDirString);

if isempty(FILES); set(handles.figMain, 'visible', 'on'); return; end;
[s,v] = listdlg('Name', 'Files To Get Information', 'PromptString','Select the files you wish to calculate:', 'SelectionMode','multiple', 'ListString',FILES, 'ListSize', [300, 200]);
if isempty(s)
    set(handles.figMain, 'visible', 'on');
    return;
end
FILES = FILES(s);
% Must choose ellipse fitting algorithm

ellipfitalg=questdlg('Choose Fitting Algorithm?', 'Ellipse Fitting Algorithm', 'AG', 'AIH','AIH');
w = waitbar(0, sprintf('%s', 'Calculating Sector Information'));
for i=1:length(FILES)
    name = FILES{i};
    parent_dir = get_parent_dir(name);
    [path, name, ext, versn] = fileparts(name);
    sectorsim = imread([path, filesep, name, '_sectors.tif']);
    organim = imread([path, filesep, name, '_organ.tif']);
    sectorsim = organim&sectorsim;
    imwrite(sectorsim, [path, filesep, name, '_sectors.tif']);
    [x, y] = find(sectorsim >0);
    sectors = [x(:), y(:)];
    save([path, filesep, 'sectors_xy.mat'], 'sectors');
    sector_info = sector_im2struct(sectorsim, ellipfitalg);
    save([path, filesep, 'sector_info.mat'], 'sector_info');
    waitbar(i/length(FILES), w);
end
close(w);
set(handles.figMain, 'visible', 'on');
return


%%%%%%%%%%%%%%%%%%%%
%
% Segment Images
%
%%%%%%%%%%%%%%%%%%%%
function [handles] = SegmentImages(handles)
set(handles.figMain, 'visible', 'off');
algorithm = get_project_segmentation_algorithm(handles.segmentation_algs_dir);
if isempty(algorithm)
    set(handles.figMain, 'visible', 'on');
    return;
end
StagedDirString = handles.dat.StagedDirString;
%FILES = [FindFilenames('JPG', StagedDirString), FindFilenames('jpg', StagedDirString)];
FILES = findfilesext('jpg', StagedDirString);

if isempty(FILES); set(handles.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]);
    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') 
        [w, orig, im, binim, sectors] = feval(algorithm, I, w);
        if sum(binim(:))>0
            E = binim2SortedEdge(binim);
            close(w);
            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');
        else
            fprintf('WARNING: Empty binary image %s\n', name);
        end
    end
end
set(handles.figMain, 'visible', 'on');
return
