close all; 

% rn = 'rootname' - a string that lets you label the saved file name
rn = 'DDSI';
% attempt = a number which allows the user to keep track of each attempt
attempt = 1;

%Calibration factors (slope of calibration curve or intensity of caldrop):
calibunt = 12.7;
calibtar = 1;

%Manual exposure time entry? (1=yes, 0=no)
manualexp = 1;

%Align targeted and untargeted images? (1=yes, 0=no)
alignimgs = 0;

%Plot targeted and untargeted images? (1=yes, 0=no)
plotimgs = 1;

%Background Correction? (1=yes, 0=no)
bckgrdcorrection = 0;

choice3=0;

Data.name = [rn,'_attempt_',num2str(attempt)];

% Load and plot untargeted image
uiwait(msgbox('Load untargeted channel image', 'modal'))
[file path] = uigetfile('*', 'select untargeted channel specimen image');
untargetedfile = [path file];
untimg = double(imread(untargetedfile));
%exptime=regexp(file,'(\d+)(m?)s','tokens');
%emptyCells = cellfun(@isempty,exptime);
%exptime(emptyCells) = [];
%untexptime=str2double(exptime{1}{1});
%if strcmp(exptime{1}{2}, 'm') == 1
 %   untexptime = untexptime*0.001;
%end

imgpath = path;
cd(imgpath);

if manualexp == 1
    prompt = {'Enter untargeted channel image exposure time (s):'};
    dlg_title = 'Exposure Time';
    num_lines = 1;
    defaultans = {'1'};
    answer = inputdlg(prompt,dlg_title,num_lines,defaultans);
    untexptime = str2num(answer{1});
end

Data.untexptime = untexptime;

% Load and plot targeted dye
uiwait(msgbox('Load targeted channel image', 'modal'))
[file path] = uigetfile('*.tif', 'select targeted channel specimen image');
targetedfile = [path file];
tarimg = double(imread(targetedfile));
%exptime=regexp(file,'(\d+)(m?)s','tokens');
%emptyCells = cellfun(@isempty,exptime);
%exptime(emptyCells) = [];
%tarexptime=str2double(exptime{1}{1});
%if strcmp(exptime{1}{2}, 'm') == 1
 %   tarexptime = tarexptime*0.001;
%end

if manualexp == 1
    prompt = {'Enter targeted channel image exposure time (s):'};
    dlg_title = 'Exposure Time';
    num_lines = 1;
    defaultans = {'1'};
    answer = inputdlg(prompt,dlg_title,num_lines,defaultans);
    tarexptime = str2num(answer{1});
end

Data.tarexptime = tarexptime;

if alignimgs == 1
    choice = 0;
    while choice ~= 1
    % Align untargeted and targeted images
    moving = imadjust(double(untimg/max(untimg(:))));
    fixed = imadjust(double(tarimg/max(tarimg(:))));
    uiwait(msgbox('Select points for image alignment and exit selection tool',...
        'modal'))
    [movingPoints, fixedPoints] = cpselect(moving, fixed, 'Wait', true);
    tform = fitgeotrans(movingPoints,fixedPoints,'nonreflectivesimilarity');
    Rfixed = imref2d(size(fixed));
    untimg = imwarp(untimg,tform,'OutputView',Rfixed);
    
    % Check if images are aligned
    warning('off', 'images:trueSize:ImageTooBigForScreen');
    figure; imshowpair(fixed, untimg, 'blend');
    daspect([1 1 1])
    truesize;
    title('Overlay image');
    
    choice = menu('Are the images aligned?','Yes','No');
    close
    untimg = imwarp(untimg,tform,'OutputView',Rfixed);
    end
end

%Select background region for background subtraction
if bckgrdcorrection == 1
    warning('off', 'Images:initSize:adjustingMag');
    figure; imagesc(untimg); title('Select background region'); daspect([1 1 1])
    truesize
    uiwait(msgbox('Select background region for both channels (showing untargeted)','modal'))
    backmask = roipoly(); close
    %Subtract background from images
    back = backmask.*double(untimg); Data.back = back;
    back = median(back(find(back~=0)));
    tmpunt = double(untimg);
    untimg = (untimg-back)/untexptime; Data.bkg_corrected_untimg = untimg;
    untimgraw = double(untimg);
    
    back = backmask.*double(tarimg);
    back = median(back(find(back~=0)));
    tarimg = (tarimg-back)/tarexptime; Data.bkg_corrected_tarimg = tarimg;
    tarimgraw = double(tarimg);
    
    if plotimgs == 1
        % Plot background corrected specimen images
        warning('off', 'images:trueSize:ImageTooBigForScreen');
        figure('Name', 'Background Corrected', 'NumberTitle', 'off')
        subplot(1, 2, 1);
        imagesc(untimg); title ('untargeted'); daspect([1 1 1]);
        subplot(1, 2, 2);
        imagesc(tarimg); title ('targeted'); daspect([1 1 1]);
        truesize;
        colorbar
    end
else
    tmpunt = double(untimg);
    untimgraw = double(untimg);
    tarimgraw = double(tarimg);
    
    if plotimgs == 1
        % Plot background corrected specimen images
        warning('off', 'images:trueSize:ImageTooBigForScreen');
        figure('Name', 'Raw Images', 'NumberTitle', 'off')
        subplot(1, 2, 1);
        imagesc(untimg); title ('untargeted'); daspect([1 1 1]);
        subplot(1, 2, 2);
        imagesc(tarimg); title ('targeted'); daspect([1 1 1]);
        truesize;
        colorbar
    end
end

% Normalize to the calibration drops
Data.calibunt = calibunt;
Data.calibtar = calibunt;
untimg = untimg/calibunt;
tarimg = tarimg/calibtar;
% Save final images
save('untargeted_img.mat', 'untimg');
save('targeted_img.mat', 'tarimg');

if plotimgs == 1
    %Plot normalized images
    warning('off', 'images:trueSize:ImageTooBigForScreen');
    figure('Name', 'Normalized to drop', 'NumberTitle', 'off');
    subplot(1, 2, 1);
    imagesc(untimg); title ('untargeted'); daspect([1 1 1])
    subplot(1, 2, 2);
    imagesc(tarimg); title ('targeted'); daspect([1 1 1])
    truesize;
    colorbar
    
    saveas(gcf, 'Norm_to_cal_final_images.fig')
end


% Calculate normalized difference ratio and apply mask for plotting
warning('off', 'IMAGES:initSize:adjustingMag');
diffnorm = (tarimg - untimg)./untimg;
diffnorm(~isfinite(diffnorm)) = 0; Data.diffnorm = diffnorm;

%diffnorm = mask.*diffnorm;

diffnorm(diffnorm==0)=min(min(diffnorm));

% Save diffnorm image
save('diffnorm.mat', 'diffnorm');
save('diffnorm.tif','diffnorm');
% Plot diffnorm image
figure; imagesc(diffnorm); ...
    title('Normalized to drops difference image');...
    daspect([1 1 1])
truesize;
colorbar

saveas(gcf, 'Diffnorm_image.fig')

%Save Data file
save(['Data_',rn,'_',num2str(attempt),'.mat'],'Data');

%Move saved images and data file to folder
mkdir(['DDSI_',rn,'_', num2str(attempt)]);
movefile('*.mat',...
    ['DDSI_',rn,'_', num2str(attempt)]);
movefile('*.fig',...
    ['DDSI_',rn,'_', num2str(attempt)]);

