%Hanna, 2005
function NoiseRemovalTool(varargin)
if checkSATDir(pwd) == 0
    fprintf('You are not in a valid SectorAnalysisToolbox Project directory\n');
    return;
end
error(nargchk(0,inf,nargin));
ad.value = 0;
% Open, move, and get the handles from the figure file.
fig = openfig(mfilename, 'reuse');
% Move the gui and then show it, rather than have it jump all over the
% place.
movegui(fig, 'center');
set(fig, 'visible', 'on');
handles = guihandles(fig);
%set(fig, 'Color', get(handles.uipanel1, 'BackgroundColor'));

% Set all the callback functions
set(handles.select_stage_btn, 'callback', {@doSelectStage});
set(handles.orig_sector_axis, 'ButtonDownFcn', {@doSelectThreshold});
set(handles.save_btn, 'callback', {@doSave});


% Initialize the application data structure
ad.figMain = fig;
ad.StagedDirString = 'Staged';
ad.OriginalsDirString = 'Originals';
ad.ProcessedDirString = 'Processed';
ad.DataDir = [ad.StagedDirString, filesep, 'Data'];
ad.GridDir = [ad.DataDir, filesep, 'Grids'];
ad.UngrowingDataDir = [ad.DataDir, filesep, 'UngrowthData'];
ad.handles = handles;
ad = InitGui(ad);
setappdata(0,'NoiseRemovalToolData',ad);
try
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end
if isappdata(0,'NoiseRemovalToolData')
    ad = getappdata(0,'NoiseRemovalToolData');
    rmappdata(0,'NoiseRemovalToolData')
end
return;
%%%%%%
%
%
%%%%%%
function ad = InitGui(ad)
ad.stagedir = [];
ad.stagefilenames = {};
ad.hist = [];
ad.info = [];
ad.selectedind = [];
if exist([ad.DataDir, filesep, 'mean_shape.mat'], 'file')
    ad.mean_shape_dir = ad.DataDir;
else
    ad.mean_shape_dir = [];
end
return;
%%%%%%
%
%
%%%%%%
function doSave(savebtn, evd)
ad =getappdata(0, 'NoiseRemovalToolData');

if isempty(ad.selectedind)
    return;
end
ellipthr = ad.info(ad.selectedind);
files = findfiles('warped_sector_info.mat', ad.stagedir);
wh = waitbar(0, 'Saving sector info...');
for i=1:length(files)
    waitbar(i/length(files), wh);
    file = files{i};
    if exist(file, 'file')
        [pathname, filename, ext, vers] = fileparts(file);
        origwarpedfilename = [pathname, filesep, filename, '_orig', ext];
        if ~exist([pathname, filesep, filename, '_orig', ext], 'file')
            [SUCCESS,MESSAGE,MESSAGEID] = copyfile(file, origwarpedfilename);
        end
        warped_sector_info = load(origwarpedfilename);
        warped_sector_info = warped_sector_info.warped_sector_info;
        a = [warped_sector_info.Area];
        warped_sector_info(a<=ellipthr.Area) = [];
        save(file, 'warped_sector_info');
    else
        fprintf('Could not save file %s\n', file);
    end
end
close(wh);
return;
%%%%%%
%
%
%%%%%%
function doSelectThreshold(selectthrbtn, evd)
ad =getappdata(0, 'NoiseRemovalToolData');
p = get(ad.handles.orig_sector_axis, 'CurrentPoint');
ad.currentPoint = p(1,1:2);
ad = findSelectedEllipse(ad);
ad = filterSectors(ad);
ad = plotFilteredSectors(ad);
ad = plotFilteredHistogram(ad);

disp('Selecting threshold');
setappdata(0, 'NoiseRemovalToolData', ad);
%delete(gcbf);
%%%%%%
%
%
%%%%%%
function ad = filterSectors(ad)
if isempty(ad.selectedind)
    return;
end
ellipthr = ad.info(ad.selectedind);
a = [ad.info.Area];
ad.filtinfo = ad.info(a>ellipthr.Area);
return
%%%%%%
%
%
%%%%%%
function ad = findSelectedEllipse(ad)
ad.selectedind = [];
p = ad.currentPoint;
C = [ad.info.Centroid];
C = reshape(C, 2,length(C)/2)';
d = sqrt(sum((C - ones(size(C,1),1)*p).^2,2));
[val, ind] = min(d);
ad.selectedind = ind(1);
%%%%%%
%
%
%%%%%%
function doSelectStage(selectstagebtn, evd)
ad =getappdata(0, 'NoiseRemovalToolData');
ad.stagedir = chooseStage;
if isempty(ad.stagedir)
    return;
end
set(ad.handles.stage_txt, 'String', ad.stagedir);
ad.stagefilenames = getstagefilenames(ad.stagedir);
ad = loadSectorInfo(ad);
ad = plotOriginalHistogram(ad);
ad = plotOriginalSectors(ad);
ad = plotFilteredHistogram(ad);
ad = plotFilteredSectors(ad);
setappdata(0, 'NoiseRemovalToolData', ad);
%%%%%%
%
%
%%%%%%
function ad = loadSectorInfo(ad)
ad.sector_info = [];
ad.info = [];
ad.filtinfo = [];
files = findfiles('warped_sector_info.mat', ad.stagedir);
wh = waitbar(0, 'Loading sector info...');
for i=1:length(files)
    waitbar(i/length(files), wh);
    file = files{i};
    if exist(file, 'file')
        [pathname, filename, ext, vers] = fileparts(file);
        origwarpedfilename = [pathname, filesep, filename, '_orig', ext];
        if ~exist([pathname, filesep, filename, '_orig', ext], 'file')
            [SUCCESS,MESSAGE,MESSAGEID] = copyfile(file, origwarpedfilename);

        end
        info = load(origwarpedfilename);
        info = info.warped_sector_info;
        ad.info = [ad.info, info];
        filtinfo = load(file);
        filtinfo = filtinfo.warped_sector_info;
        ad.filtinfo = [ad.filtinfo, filtinfo];
        
    else
        fprintf('Could not load file %s\n', file);
    end
end
close(wh);
ad.filtinfo = ad.info;
return;
%%%%%%
%
%
%%%%%%
function ad = plotOriginalHistogram(ad)
if isempty(ad.stagedir)
    return;
end
if isempty(ad.info)
    return;
end
ppc = get_pixel_per_cell_value;
[ad.hist.n, ad.hist.x] = calc_hist_data(ad.info, ppc);
map = cool(length(ad.hist.x));
cbar(ad.hist.n, ad.hist.x, map, ad.handles.orig_hist_axis);
%%%%%%
%
%
%%%%%%
function ad = plotOriginalSectors(ad)
if isempty(ad.info)
    return;
end
cla(ad.handles.orig_sector_axis);

plot_ellipse_axis(ad.handles.orig_sector_axis, ad.info, [0 0 0]);
axis(ad.handles.orig_sector_axis, 'image');

%%%%%%
%
%
%%%%%%
function ad = plotFilteredHistogram(ad)
if isempty(ad.stagedir)
    return;
end
ppc = get_pixel_per_cell_value;

[ad.hist.n, ad.hist.x] = calc_hist_data(ad.filtinfo, ppc);
map = cool(length(ad.hist.x));
cbar(ad.hist.n, ad.hist.x, map, ad.handles.filt_hist_axis);

%%%%%%
%
%
%%%%%%
function [n, x] = calc_hist_data(info, number_of_pixels_per_cell)
if isempty(info)
    return;
end
area = [info.Area];
area = area/number_of_pixels_per_cell;
area(area<=0) = [];
[x, n] = hist(log2(area), 10);
%%%%%%
%
%
%%%%%%
function ad = plotFilteredSectors(ad)
if isempty(ad.filtinfo)
    return;
end
cla(ad.handles.filt_sector_axis);
plot_ellipse_axis(ad.handles.filt_sector_axis, ad.filtinfo, [0 0 0]);
axis(ad.handles.filt_sector_axis, 'image');
