clear;
close all
%% Importing Abnormal Images from Mammogram Database
fileID = fopen('Mammogram Info With Extra.txt');
C = textscan(fileID,'%3s %3d %s %4s %s %3d %3d %2d');
TextInfo = string([string(C{2}) C{3} C{4} C{5}]);
TextLocations = double([C{2} C{6} C{7} C{8}]);
fclose(fileID);
%% Getting Image Info 
close all
Dir = 'pwd';
GetDir = dir('/MATLAB Drive/Mammogram Database/*.pgm');
imageNum = nonzeros(TextLocations(:,1));
x = nonzeros(TextLocations(:,2));
y = nonzeros(TextLocations(:,3));
r = nonzeros(TextLocations(:,4));
numImages = length(imageNum);
%% Asking User to Input A file Number
i = input('Please input the file number you intend to analyze');
%% Accessing Image Specified by User from the Mammogram Database
currentImage = imageNum(i);
file = GetDir(currentImage).name;
X = imread(file);
% The image is flipped 
figure;
imshow(X)
title('Inverted Mammogram Image')
[l,w] = size(X);
axis on
%% Using Determined Thresholds to Identify Abnormalities
% loading analysis data from MammogramStats.m
% Contains appropriate thresholds for each tissue type
TissueType = input('Please Type in Tissue Type F,G, or (Fatty(F), FattyGlandular(G), or Dense(D)).','s');
load('MammogramStats.m','-mat')
% Setting k (threshold) to a diff threshold based on tissue type
% Each k is based on what threshold led to the most correct diagnoses
switch (TissueType)
    case 'F'
        k = statsF(3);
    case 'G'
        k = statsG(3);
    case 'D'
        k = statsD(3);
    otherwise
        return
end
%% Select Region of Interest
% Asking user to crop ROI using TestSandBox Function
% The image is cropped to only include the ROI
% The axis was switched to xy to apply the mass correctly.
ROI = GetRoi(X);
axis xy
figure;
imshow(ROI)
title('ROI')
axis on
%% Filtering Image for Better Contrast
% adapthisteq is used to improve contrast to 
% better visualize bright spots1

figure;
enhanced_contrast = adapthisteq(ROI);
imshow(enhanced_contrast);
title('Enhanced Contrast Image')
binaryimage = imbinarize(enhanced_contrast,k);
figure;
imshow(binaryimage)
title('binaryimage')
%% Using the Strel Function to remove noise
    SE = strel('disk',4);
    SE.Neighborhood
    % The imopen function removes any spots smaller
    % than a radius of 4 pixels. 
    % The function is applied to the negative of the filtered
    % image to remove black spots.
    open = imopen(~(binaryimage),SE);
    % The opened image is shown on figure 2
%% Using BW Label to find Abnormality
[Labeled, number_blobs] = bwlabel(~open,8);
% Use regionprops to find the centroid and boundary of the 
% abnormality
props = regionprops(~open);
% find the areas of the regions in props
areas = [props.Area];
[sortedAreas,indicies] = sort(areas,'descend');
% finding largest blob
% This is most likely the abnormality
% Includes coordinates of largest area (x,y), k (threshold), Area
Identified = ismember(Labeled, indicies(sortedAreas>500));
Spots = Identified>0;

%% Plotting Images of Varying Thresholds With Identified Masses
% The original mammogram image is shown.
% All identified masses are plotted in this image
figure(4);
title('Identified Masses')
imshow(X)
% The axis is reverted to normal so that 
% the spots are plotted correctly.
axis ij
hold on
% use region props to plot the location 
% of each identified mass
% plot the largest identified mass
Data = zeros();
limit = 500;
for idx = 1:length(areas)
    if areas(idx)>limit
    xcoordinate = props(idx).Centroid(1);
    ycoordinate = props(idx).Centroid(2);
    Data(idx,1) = xcoordinate;
    Data(idx,2) = ycoordinate;
    plot(xcoordinate,ycoordinate,'bx','DisplayName','Masses Identified by Classifier')
    end 
end
legend
%% Plotting actual region of abnormality
center = [x(i),1024-y(i)];
th = linspace(0,2*pi);
xcoord = center(1) + r(i)*cos(th);
ycoord = center(2) + r(i)*sin(th);
hold on
plot(xcoord,ycoord,'r','DisplayName','Diagnosed Mass')
legend