%First load the file path
[file_name,path] = uigetfile('*.tif','Select the file');
file = fullfile(path,file_name);
% Next the image is loaded into the matlab environment
original_img = imread(file);
% Apply the rotation function
n_rotations = 450;
gradient_loc = 'lower';
sensitivity = 0.001;
operation = 'mean';

%Create a list of rotations
rotations = linspace(0,360,n_rotations);
%Create a blank list of zeros that will report the top-bottom ratio
report = zeros(n_rotations,1);

%If the picture is 3 dimensions (X, Y, Colordepth), this collapses it into
%one dimension
if length(size(original_img)) == 3
    img = original_img(:,:,1) + original_img(:,:,2) + original_img(:,:,3);
else 
    img = original_img;
end

%This applies a background correction for non-black backgrounds
background = img(1,1);
img(img == background) = 0;

for i = 1:n_rotations
    disp(i)
    targ_rot = rotations(i);
    B = imrotate(img, targ_rot, 'crop');
    m =size(img,1)/2;
    if strcmp(operation, 'mean')
        upper_inten = mean(mean(B(1:m, :, :)));
        lower_inten = mean(mean(B(m:end, :, :)));
    elseif strcmp(operation, 'sum')
        upper_inten = sum(sum(B(1:m, :, :)));
        lower_inten = sum(sum(B(m:end, :, :)));
    else
        upper_inten = NaN;
        lower_inten = NaN;
    end
    report(i) = upper_inten/lower_inten;
end

if strcmp(gradient_loc, 'upper')
    [val,id] = max(report);
elseif strcmp(gradient_loc, 'lower')
    [val,id] = min(report);
end

candid = find(report <= (val + sensitivity));
if length(candid) > 1
    top = candid(1);
    bottom = candid(end);
    best_rot = (rotations(top) + rotations(bottom))/2;
else
    best_rot = rotations(1,id);
end

if best_rot ~= 180
    rot_img = imrotate(original_img, best_rot, 'crop');
else
    rot_img = original_img;
end

new_filename = strcat(file_name(1:end-4) , '_rotated.tif');

imwrite(rot_img, fullfile(path, new_filename));

imshow([original_img, rot_img]);


