function [mask] = CalibrateMask(dicom, dimension)
% CalibrateMask Convert a 3D dicome matrix to a binary mask by user input
% threshold
% =========================================================================
% AUTHOR       Zachary Ip
% CONTACT      ipzach@uw.edu
% INSTITUTION  University of Washington
% DATE        25th November 2019
% 
% INPUTS dicom - 3D double, single, uint
%        dimension - int, the dimension to visualize data through
%   
% OUTPUTS mask - 3D logical - binary mask of converted DICOM file
% =========================================================================
% Ensure dimension is a valid value
valid = [1 2 3];
if ~ismember(dimension, valid)
    error('Please enter an integer between 1 and 3')
end

% Approximate threshold and initilize frame
threshold = floor(max(dicom(:))/10);
frame = 1;


disp('Calibrate binary threshold using (f)orward / (b)ackward and')
disp('(h)igher / (l)ower. Enter (y) when finished.')
% initialize user input 
ui = 'null';
% Display 2D frame of data to visualize threshold
figure
while ui ~= 'y'
    mask = dicom > threshold;
    switch dimension
        case 1
            pcolor(flipud(squeeze(mask(frame,:,:)))), shading flat, colormap(bone);title(num2str(frame))
        case 2
            pcolor(flipud(squeeze(mask(:,frame,:)))), shading flat, colormap(bone);title(num2str(frame))
        case 3
            pcolor(flipud(squeeze(mask(:,:,frame)))), shading flat, colormap(bone);title(num2str(frame))
    end % switch
    axis off
    ui = input(' ','s');
    % Controls for moving frames
    if ui == 'f'
        frame = frame+1;
    elseif ui == 'b'
        frame = frame-1;
    % Controls for changing threshold
    elseif ui == 'h'
        threshold = threshold +5;
    elseif ui == 'l'
        threshold = threshold -5;
    end % if
    disp(['Threshold: ',num2str(threshold)]);
end % while
end