%Hanna, 2005
function [value] = ImageProcessingTool(varargin)
if checkSATDir(pwd) == 0
    fprintf('You are not in a valid SectorAnalysisToolbox Project directory\n');
    return;
end
error(nargchk(0,inf,nargin));
% Open, move, and get the handles from the figure file.
fig = openfig(mfilename, 'reuse');
movegui(fig, 'center');
set(fig, 'Visible', 'on');
handles = guihandles(fig);
set(fig, 'Color', get(handles.uipanel2, 'BackgroundColor'));

% Set all the callback functions
set(handles.filenameList, 'callback', {@doSkipFile});
set(handles.nextBtn, 'callback', {@doNext});
set(handles.prevBtn, 'callback', {@doPrev});
set(handles.crop_btn, 'callback', {@doCrop});
set(handles.undo_btn, 'callback', {@doUndo});
set(handles.save_btn, 'callback', {@doSave});
set(handles.select_region_btn, 'callback', {@doSelectRegion});
set(handles.ChangeResolutionBtn, 'callback', {@ChangeRes});
set(handles.GlobalChangeResBtn, 'callback', {@GlobalChangeRes});
set(handles.red_channel_rad, 'callback', {@doSwithChannel});
set(handles.green_channel_rad, 'callback', {@doSwithChannel});
set(handles.blue_channel_rad, 'callback', {@doSwithChannel});
set(handles.all_channel_rad, 'callback', {@doSwithChannel});
set(handles.rotatebox, 'callback', {@doRotate});

% Initialize the application data structure
ad.StagedDirString = 'Staged';
ad.OriginalsDirString = 'Original';
ad.ProcessedDirString = 'Processed';
ad.projectpath = pwd;
ad.image_files = [FindFilenames('.JPG', ad.OriginalsDirString), FindFilenames('.jpg', ad.OriginalsDirString)];
ad.value = 0;
ad.currentChannel = 'all';
ad.handles = handles;
setappdata(0,'ImageProcessingToolData',ad);
init_gui(ad, handles);
try
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end
value = 0;
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GlobalChangeRes
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GlobalChangeRes(glbchange_res_btn, evd)
ad =getappdata(0, 'ImageProcessingToolData');
if isempty(ad.image_files); return; end;

files = ad.image_files;
res = str2num(get(ad.handles.resTxt, 'String'));
w = waitbar(0, 'Applying global resolution change, please wait...');
for f = 1:length(files)
    waitbar(f/length(files), w);
    I = imread(files{f});
    I = double(I);
    I = I./max(I(:));
    I = imresize(I, res, 'bilinear');
    imwrite(I, [files{f}]);
    fprintf('Size of image is now %dx%d\n', size(I,1), size(I,2));
    clear I;
end
close(w);
handles = Skip(ad.handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ChangeRes
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ChangeRes(change_res_btn, evd)
ad =getappdata(0, 'ImageProcessingToolData');
if isempty(ad.image_files); return; end;
res = str2num(get(ad.handles.resTxt, 'String'));
ad.currentImage = imresize(ad.currentImage, res, 'bilinear');
value = get(ad.handles.filenameList, 'value');
setappdata(0,'ImageProcessingToolData',ad);
displayImage(ad.handles.mainAxes);


function [] = init_gui(ad, handles)
if length(ad.image_files) == 0
    str = 'No sector files found';
    set(handles.filenameList, 'String', str);
    return;
end
str = ad.image_files;
set(handles.filenameList, 'String', str);
name = str{1};
loadImage(name);
displayImage(handles.mainAxes);
return;

function doSkipFile(sector_popup, evd)
ad =getappdata(0, 'ImageProcessingToolData');
if isempty(ad.image_files); return; end;
value = get(sector_popup, 'value');
fprintf('Skipped to file %s\n', ad.image_files{value});
loadImage(ad.image_files{value});
displayImage(ad.handles.mainAxes);
return;


function doSwithChannel(ch_rad, evd)
ad =getappdata(0, 'ImageProcessingToolData');
switch get(ch_rad, 'Tag')
    case 'red_channel_rad'
        ad.currentChannel = 'red';
    case 'green_channel_rad'
        ad.currentChannel = 'green';
    case 'blue_channel_rad'
        ad.currentChannel = 'blue';
    case 'all_channel_rad'
        ad.currentChannel = 'all';
    otherwise
        fprintf('Invalid value for channel\n');
end
setappdata(0, 'ImageProcessingToolData', ad);
displayImage(ad.handles.mainAxes);
return;

function doSave(save_btn, evd)
ad =getappdata(0, 'ImageProcessingToolData');
val = get(ad.handles.filenameList, 'Value');
str = get(ad.handles.filenameList, 'String');
if (val<1) | (val>length(str))
    return;
end
filename = str{val};
filename = ['Processed', filesep, filename(10:end)];
fprintf('Saving current image as %s\n', filename');
imwrite(ad.currentImage, filename);


function doSelectRegion(select_region_btn, evd)
ad =getappdata(0, 'ImageProcessingToolData');
[bw, x, y] = roipoly;
for i=1:size(ad.currentImage,3)
    temp(:,:,i) = double(bw).*double(ad.currentImage(:,:,i));
end
ad.currentImage = uint8(temp);
setappdata(0, 'ImageProcessingToolData', ad);
displayImage(ad.handles.mainAxes);


function doCrop(crop_btn, evd)
ad =getappdata(0, 'ImageProcessingToolData');
ad.currentImage = imcrop(ad.currentImage);
setappdata(0, 'ImageProcessingToolData', ad);
displayImage(ad.handles.mainAxes);

function doRotate(rotatebox, evd)
ad =getappdata(0, 'ImageProcessingToolData');
val = str2double(get(rotatebox, 'String')); 
ad.currentImage = imrotate(ad.currentImage, val, 'crop');
imshow(ad.currentImage);
setappdata(0,'ImageProcessingToolData',ad);


function doUndo(undo_btn, evd)
ad =getappdata(0, 'ImageProcessingToolData');
doSkipFile(ad.handles.filenameList);


function doNext(next_btn, evd)
ad =getappdata(0, 'ImageProcessingToolData');
if isempty(ad.image_files); return; end;

value = get(ad.handles.filenameList, 'value');
if value < length(ad.image_files)
    value = value + 1;
    set(ad.handles.filenameList, 'value', value);
    doSkipFile(ad.handles.filenameList);
end
return;
function doPrev(prev_btn, evd)
ad =getappdata(0, 'ImageProcessingToolData');
if isempty(ad.image_files); return; end;

value = get(ad.handles.filenameList, 'value');
if value > 1
    value = value - 1;
    set(ad.handles.filenameList, 'value', value);
    doSkipFile(ad.handles.filenameList);
end
return;

function loadImage(name)
ad =getappdata(0, 'ImageProcessingToolData');
full_im = imread([name]);
ad.currentImage = full_im;
setappdata(0,'ImageProcessingToolData',ad);

function displayImage(mainAxes)
ad =getappdata(0, 'ImageProcessingToolData');
cla(mainAxes);
if size(ad.currentImage, 3) == 1
imagesc(ad.currentImage, 'Parent', mainAxes);
else
    switch ad.currentChannel
        case 'all'
            imagesc(ad.currentImage, 'Parent', mainAxes);
        case 'red'
            imagesc(ad.currentImage(:,:,1), 'Parent', mainAxes);
        case 'green'
            imagesc(ad.currentImage(:,:,2), 'Parent', mainAxes);
        case 'blue'
            imagesc(ad.currentImage(:,:,3), 'Parent', mainAxes);
    end
end
axis(mainAxes, 'image', 'ij');
set(ad.handles.imwidthTxt, 'String', size(ad.currentImage,1));
set(ad.handles.imheightTxt, 'String', size(ad.currentImage,2));


% function [value] = ImageProcessingTool(varargin)
% if checkSATDir(pwd) == 0
%     fprintf('You are not in a valid SectorAnalysisToolbox Project directory\n');
%     return;
% end
% error(nargchk(0,inf,nargin));
% % Open, move, and get the handles from the figure file.
% fig = openfig(mfilename, 'reuse');
% movegui(fig, 'center');
% handles = guihandles(fig);
% % Set all the callback functions
% set(handles.filenameList, 'callback', {@doSkipFile});
% set(handles.nextBtn, 'callback', {@doNext});
% set(handles.prevBtn, 'callback', {@doPrev});
% set(handles.ChangeResolutionBtn, 'callback', {@ChangeRes});
% set(handles.GlobalChangeResBtn, 'callback', {@GlobalChangeRes});
% 
% 
% % Initialize the application data structure
% ad.StagedDirString = 'Staged';
% ad.OriginalsDirString = 'Originals';
% ad.ProcessedDirString = 'Processed';
% ad.projectpath = pwd;
% ad.image_files = FindFilenames('_sectors.tif', ad.StagedDirString);
% ad.value = 0;
% ad.handles = handles;
% setappdata(0,'ImageProcessingToolData',ad);
% init_gui(ad, handles);
% try
%     uiwait(fig);
% catch
%     if ishandle(fig)
%         delete(fig)
%     end
% end
% value = 0;
% return;
% 
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  Initialise
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [] = init_gui(ad, handles)
% if length(ad.image_files) == 0
%     set(handles.filenameList, 'String', 'No images');
%     set(handles.filenameList, 'value', 1);
%     handles.dat.currentIndex = 1;
%     return;
% end  
% str = ad.image_files;
% set(handles.filenameList, 'String', str);
% name = str{1};
% displayImage(name, handles.mainAxes);
% return;
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  Save
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [handles] = Save(handles)
% imwrite(handles.dat.CurrentImage, [handles.dat.CurrentImageDir, filesep, handles.dat.CurrentImageName]);
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  SelectRegion
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [handles] = SelectRegion(handles)
% BW = roipoly;
% handles.dat.CurrentImage(:,:,1) = handles.dat.CurrentImage(:,:,1).*BW;
% handles.dat.CurrentImage(:,:,2) = handles.dat.CurrentImage(:,:,2).*BW;
% handles.dat.CurrentImage(:,:,3) = handles.dat.CurrentImage(:,:,3).*BW;
% L = bwlabel(BW);
% S = regionprops(L, 'BoundingBox');
% R = S(1).BoundingBox;
% %handles.dat.CurrentImage = imcrop(handles.dat.CurrentImage,R);
% handles = UpdateImage(handles);
% return;

% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  Next
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [handles] = Next(handles)
% N = length(handles.dat.files);
% v = get(handles.filenameList, 'value');
% if (v < N)
%     v = v +1;
%     handles.dat.currentIndex =   handles.dat.currentIndex + 1;
% else
%     v = N;
% end
% set(handles.filenameList, 'value', v);
% handles = Skip(handles);
% 
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  Prev
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [handles] = Prev(handles)
% N = length(handles.dat.files);
% v = get(handles.filenameList, 'value');
% if (v > 1)
%     v = v -1;
%     handles.dat.currentIndex =   handles.dat.currentIndex + 1;
% else
%     v = 1;
% end
% set(handles.filenameList, 'value', v);
% handles = Skip(handles);
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  Select image directory
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [handles] = SelectDir(handles)
% handles.dat.directoryname = uigetdir(pwd);
% if handles.dat.directoryname~=0
% files = dir([handles.dat.directoryname, filesep, '*.JPG']);
% handles.dat.files = {files.name};
% fprintf('Directory, %s\n', handles.dat.directoryname); 
% for f = 1:length(handles.dat.files)
%    fprintf('Filename, %s\n', handles.dat.files{f}); 
% end
% if length(handles.dat.files)>0
%     set(handles.filenameList, 'String', handles.dat.files);
%     set(handles.filenameList, 'value', 1);
%     handles.dat.currentIndex = 1;
%     handles = Skip(handles);
%     handles = UpdateImage(handles);
% else
%     set(handles.filenameList, 'String', 'No images');
%     set(handles.filenameList, 'value', 1);
%     handles.dat.currentIndex = 1;
% end
% end
% return;
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  Skip
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [handles] = Skip(handles)
% handles.dat.currentIndex = get(handles.filenameList, 'value');
% I = imread([handles.dat.directoryname, filesep,handles.dat.files{handles.dat.currentIndex}]);
% I = double(I);
% handles.dat.CurrentImage = I./max(I(:));
% handles.dat.CurrentImageName = handles.dat.files{handles.dat.currentIndex};
% handles.dat.CurrentImageDir = handles.dat.directoryname;
% handles = UpdateImage(handles);
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  Update Image
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [handles] = displayImage(name, handles.mainAxes)
% 
% imagesc(handles.dat.CurrentImage, 'Parent', handles.mainAxes, 'HitTest', 'off');
% axis(handles.mainAxes, 'image');
% set(handles.imwidthTxt, 'String', num2str(size(handles.dat.CurrentImage,2)));
% set(handles.imheightTxt, 'String', num2str(size(handles.dat.CurrentImage,1)));
% 
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %  Process Image
% %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [handles] = Crop(handles)
% [x, y] = ginput(1);
% width = str2num(get(handles.widthTxt, 'String'));
% height = str2num(get(handles.heightTxt, 'String'));
% fprintf('Width, %d, Height, %d\n', width, height);
% 
% ys = round(x-width/2)
% yf = round(x+width/2)-1
% xs = round(y-height/2)
% xf = round(y+height/2)-1
% 
% if xs<1
%     xs = 1;
% end
% if xf>size(handles.dat.CurrentImage,1)
%     xf = size(handles.dat.CurrentImage,1);
% end
% if ys < 1
%     ys = 1;
% end
% if yf > size(handles.dat.CurrentImage,2)
%     yf = size(handles.dat.CurrentImage,2);
% end
% handles.dat.CurrentImage = handles.dat.CurrentImage(xs:xf, ys:yf,:);
% if size(handles.dat.CurrentImage,1)<height 
%     r= [handles.dat.CurrentImage(:,:,1); zeros(height - size(handles.dat.CurrentImage,1), size(handles.dat.CurrentImage, 2))];
%     g = [handles.dat.CurrentImage(:,:,2); zeros(height - size(handles.dat.CurrentImage,1), size(handles.dat.CurrentImage, 2))];
%     b = [handles.dat.CurrentImage(:,:,3); zeros(height - size(handles.dat.CurrentImage,1), size(handles.dat.CurrentImage, 2))];
% 
% handles.dat.CurrentImage = [];
% handles.dat.CurrentImage(:,:,1) = r;
% handles.dat.CurrentImage(:,:,2) = g;
% handles.dat.CurrentImage(:,:,3) = b;
% end
% if size(handles.dat.CurrentImage,2)<width
%     r = [handles.dat.CurrentImage(:,:,1), zeros(size(handles.dat.CurrentImage, 1), width - size(handles.dat.CurrentImage,2))];
%     g = [handles.dat.CurrentImage(:,:,2), zeros(size(handles.dat.CurrentImage, 1), width - size(handles.dat.CurrentImage,2))];
%     b = [handles.dat.CurrentImage(:,:,3), zeros(size(handles.dat.CurrentImage, 1), width - size(handles.dat.CurrentImage,2))];
%     handles.dat.CurrentImage = [];
%     handles.dat.CurrentImage(:,:,1) = r;
%     handles.dat.CurrentImage(:,:,2) = g;
%     handles.dat.CurrentImage(:,:,3) = b;
% end
% handles = UpdateImage(handles);
% return;