%This is a chart reader. It reads charts.
%v 1.1 estimates mu hat and sigma hat along with post processing function
%to warn of bad values
%enjoy
function [stock_vals,stock_time] = creader()

clc
close all

disp('***********************************************');
disp('*     Chart Reader v1.1   23/07/2009          *');
disp('*                 Iain Blair                  *');
disp('***********************************************');   

%Change the chart location here
%get if from BIGCHARTS.COM
%%%%%%%%%%%%%%%%% CHART NAME HERE INPUT %%%%%%%%%%%%%%%
[fileName, pathName] = uigetfile('*.gif', 'Select .gif file...');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
chart_dir = fullfile(pathName,fileName);
disp(['Current Chart: ',chart_dir])
is_in_input_loop = true;


while(is_in_input_loop)

imshow(chart_dir);
hold on

disp(' ');
disp('Please select the TOP LEFT CORNER OF THE CHART...')
tl = ginput(1);
fprintf('Coord X: %g\n',tl(1));
fprintf('Coord Y: %g\n',tl(2));
plot(tl(1),tl(2),'*');
user_ok = input('This point ok? (ENTER = YES, 1 = NO)');
if user_ok == 1
    continue
end

disp(' ');
disp('Please select the BOTTOM RIGHT CORNER OF THE CHART...')
br = ginput(1);
fprintf('Coord X: %g\n',br(1));
fprintf('Coord Y: %g\n',br(2));
plot(br(1),br(2),'r*');
user_ok = input('This point ok? (ENTER = YES, 1 = NO)');
if user_ok == 1
    continue
end


%Error checking, think robustifying
if (tl(1) > br(1)) 
       disp('** Error with input, select TOP LEFT then BOTTOM RIGHT!! **');
       beep;
       continue

elseif  (tl(2) > br(2)) 
       disp('** Error with input, select TOP LEFT then BOTTOM RIGHT!! **');
       beep;
        continue
else
        disp(' ');
        disp('Coords Accepted...');
        tl = floor(tl);
        br = floor(br);
        is_in_input_loop = false;
end


%plot a box around the chart

disp('Displaying Chart Area...');
plot([tl(1) br(1)],[tl(2) tl(2)]);
plot([br(1) br(1)],[tl(2) br(2)]);
plot([tl(1) br(1)],[br(2) br(2)]);
plot([tl(1) tl(1)],[tl(2) br(2)]);

user_ok = input('Happy? (ENTER = YES, 1 = NO)');
if user_ok == 1
    is_in_input_loop = true;
    continue
end

disp(' ');
time_days = input('Please enter time frame that the chart covers (some unit?): ');
y_max = input('Please enter the max price of the chart scale: ');
y_min = input('Please enter the min price of the chart scale: ');

end

%ok now user is happy with input which is fantastic
%lets isolate the chart in a new window...

figure
[chart,map] = imread(chart_dir);
chart2 = chart';
chart2 = chart2(tl(1):br(1),tl(2):br(2));
chart2 = chart2';
imshow(chart2,map);

disp(' ');
disp('Calculating Scales...');
[sizey,sizex] = size(chart2);
fprintf('Selected Chart Height (pixels): %g\n',sizey);
fprintf('Selected Chart Width (pixels): %g\n',sizex);

pixely_per_price = sizey/(y_max-y_min);
pixelx_per_time = sizex/(time_days);

fprintf('Y Pixel Scale: %g pixels per dollar\n',pixely_per_price);
fprintf('X Pixel Scale: %g pixels per day\n',pixelx_per_time);

% now we are in a position to search for the elusive blacks!!!
% for each column in the image we will search vertically for the pixel

stock_vals = zeros(1,sizex);
found = 0;


%the crux of the program lies here
% for the "small and medium size charts, the price is given in 80. but for
% the large more accurate charts the price seems to be 15
disp(' ');
disp('Looping through selected chart area...');
hold on
for j = 1:sizex
    for i = 1:sizey
            
        if (chart2(i,j) == 80 || chart2(i,j) == 15)
            plot(j,i,'r')
            found(end) = i;
            found(end+1) = 0;
                
        end
        
    end
   if size(found > 1) 
   stock_vals(j) = sizey - sum(found(1:end-1))/(length(found)-1);
   else
       stock_vals(j) = sizey - found;
   end
    found = 0;
    if (mod(j,15)==0)
    fprintf('.');
    end
end

title('Chart Overlay');
legend('Read Price');

%%%%%%%%%%%%% THESE ARE THE OUPUT VECTORS %%%%%%%%%%%%%%%%%%%%
stock_vals = stock_vals/pixely_per_price + y_min;
stock_time = linspace(-sizex/pixelx_per_time,0,sizex);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

figure
plot(stock_time,stock_vals)
xlabel('Time (units ago)')
ylabel('Price ($)')
grid
title(['Chart Reader Vector Output: ',chart_dir])
axis([-time_days 0 y_min y_max]);

disp('Done.');
disp(' ');
disp('Post Processing Stock Values...');
nanny = 0;
for i = 1:length(stock_vals)
   if isnan(stock_vals(i))
       nanny = nanny + 1;
   end      
end
if nanny > 0
    disp('***********************************************');
    fprintf('\nWARNING: %g instances of "NaN" found in stock values...Consider redefining chart area...\n\n',nanny);
    disp('***********************************************');
    beep;
end
end


