%% Stores x-y data from clicking on data in an image with a scatter plot
% Ted Present, 30 March 2014

clc;
clear;
close all;
imtool close all;

%% Read in image
folder = 'C:\Users\Ted\Desktop';
baseFileName = 'screenshot_of_figure.png';
set(0,'DefaultFigureWindowStyle','normal');
fullFileName = fullfile(folder, baseFileName);
img = imread(fullFileName);
[rows,columns,numberOfColorBands] = size(img);
imshow(img, []);
hold on;

%set(gcf, 'Position', get(0,'Screensize'));
set(gcf,'name',baseFileName,'numbertitle','off')
%screen_size = get(0,'ScreenSize');
%set(gcf,'Position',[0 0 screen_size(3) screen_size(4)]);

%% Get axis values
X_name = inputdlg('What is the name of the X-axis?');
Xmin_input = inputdlg('Enter min value of X-axis, and click its position');
Xmin = str2double(Xmin_input{:});
[Xmin_x, Xmin_y] = ginput(1);
plot(Xmin_x,Xmin_y,'x');

Xmax_input = inputdlg('Enter max value of X-axis, and click its position');
Xmax = str2double(Xmax_input{:});
[Xmax_x, Xmax_y] = ginput(1);
plot(Xmax_x,Xmax_y,'x');

Y_name = inputdlg('What is the name of the Y-axis?');
Ymin_input = inputdlg('Enter min value of Y-axis, and click its position');
Ymin = str2double(Ymin_input{:});
[Ymin_x, Ymin_y] = ginput(1);
plot(Ymin_x,Ymin_y,'x');

Ymax_input = inputdlg('Enter max value of Y-axis, and click its position');
Ymax = str2double(Ymax_input{:});
[Ymax_x, Ymax_y] = ginput(1);
plot(Ymax_x,Ymax_y,'x');

%% Get data series
uiwait(msgbox('Click each point in data series. RIGHT CLICK on the last point'));
b=1;
x = NaN; y = NaN;
while b==1
    [xclick,yclick,b] = ginput(1);
    x(end+1)=xclick; %#ok<*SAGROW>
    y(end+1)=yclick;
    plot(xclick,yclick,'o');
end
x = x(2:end)';
y = y(2:end)';
hold off;

%% Interpolate data
x_data = (x-Xmin_x)/(Xmax_x-Xmin_x).*(Xmax-Xmin)+Xmin;
y_data = (y-Ymin_y)/(Ymax_y-Ymin_y).*(Ymax-Ymin)+Ymin;

figure;
plot(x_data,y_data, 'o');

%% Save to text file
data_for_output = [x_data y_data]';
outputFileID = fopen(strcat(baseFileName,'_XYoutput.txt'),'w');
fprintf(outputFileID,'%s %s\r\n',X_name{1},Y_name{1});
fprintf(outputFileID,'%f %f\r\n',data_for_output);
fclose(outputFileID);