function [rseries,output_x,output_y] = select_curves(input_x,input_y,inc_res,plot_title,x_axis,y_axis,save_it)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% select_curves.m allows one to remove outlier data curves by
% clicking them on a plot.  It allows for multiple passes through
% the plot, if necessary.  Upon entering data two plots are
% produced- one that tracks the curves selected in a given
% iteration and one that displays the remaining curves. When one
% concludes a pass through the plot they are prompted to declare
% whether they want to remove the selected curves and finish.
% If so, the selected curves are removed and the remaining data set
% is returned.  If not, the user can either keep (i.e. in the case
% of errant clicking) or remove the curves selected in his/her last 
% iteration and continue until finished.  The indices of the
% removed curves and the remaining set are returned upon completion.
%
% Inputs:
% input_x    - input independent variables in either cell or array format;
%              if in array format, must be in in rows stacked vertically.
% input_y    - input dependent variables in either cell or array format;
%              if in array format, must be in in rows stacked vertically.
% inc_res    - (optional) factor by which to increase input resolution.
% plot_title - (optional) title for plots.
% x_axis     - (optional) xlabel for plots.
% y_axis     - (optional) ylabel for plots.
% save_it    - (optional) location to save plots, if desired.
%
% Outputs:
% rseries    - vector of removed rows.
% output_x   - input_x with outlier rows removed; input format preserved.
% output_y   - input_y with outlier rows removed; input format preserved.
%
% Example Usage:
% [rTA,xTA,yTA] = select_curves(input_x,n_aTA,10,'TA Act. Est.','Pct. GC','Act. Est.',1);
%
% Jared Markowitz
% Spring 2012
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Convert to cell if in array format:
if iscell(input_x) == 0
  cell_x = convert_to_cell(input_x);
  cell_y = convert_to_cell(input_y);
else
  cell_x = input_x;
  cell_y = input_y;
end;  

% Increase resolution if required (assuming uniform spacing):
if exist('inc_res') && inc_res > 1
  input_xi = {}; input_yi = {};
  for h = 1:length(cell_x)
    xi = cell_x{h}:(cell_x{h}(end)-cell_x{h}(1))/(length(cell_x{h})-1)/inc_res:cell_x{h}(end); 
    yi = interp1(cell_x{h},cell_y{h},xi,'spline'); 
    input_xi{h} = xi;
    input_yi{h} = yi;
  end;
else
  input_xi = cell_x; input_yi = cell_y;
end;  

clear cell_x cell_y;

% Produce initial plots:
f1 = figure;
for i = 1:length(input_xi)
  plot(input_xi{i},input_yi{i});
  hold on;
end;
grid on; axis tight;
if exist('plot_title') == 1
  cmd = ['title(''Selected ' plot_title ''',''fontsize'',12);'];
  eval(cmd);
else
  title ('Selected Curves', 'fontsize',12);
end;
if exist('x_axis') == 1
  cmd = ['xlabel(''' x_axis ''',''fontsize'',12);'];
  eval(cmd);
end;
if exist('y_axis') == 1
  cmd = ['ylabel(''' y_axis ''',''fontsize'',12);'];
  eval(cmd);
end;

f2 = figure;
for j=1:length(input_xi)
  cmd = ['h' num2str(j) '=plot(input_xi{j},input_yi{j});'];
  eval(cmd);
  hold on;
end;
grid on; axis tight;
if exist('plot_title') == 1
  cmd = ['title(''Remaining ' plot_title ''',''fontsize'',12);'];
  eval(cmd);
else
  title ('Remaining Curves', 'fontsize',12);
end;
if exist('x_axis') == 1
  cmd = ['xlabel(''' x_axis ''',''fontsize'',12);'];
  eval(cmd);
end;
if exist('y_axis') == 1
  cmd = ['ylabel(''' y_axis ''',''fontsize'',12);'];
  eval(cmd);
end;

% Click curves to remove:
colors = ['r';'g';'m';'c';'k';'y'];
done   = 0; cnum   = 0; ind    = [];

while done == 0;  
  cnum = mod(cnum,6)+1;
  figure(f2);
  fprintf('Click curves to remove (press enter when finished):\n');
  [x,y] = ginput;
  indt = [];
  for k=1:length(x)
    for l=1:length(input_xi)
      d1_vec(l) = find_min_dist(x(k),y(k),input_xi{l},input_yi{l});        
    end;
    [val,ind1] = min(d1_vec);
    indt = cat(1,indt,ind1);
    cmd = ['figure(f1); plot(input_xi{ind1},input_yi{ind1},''' colors(cnum) ''',''linewidth'',2);'];
    eval(cmd);
  end;
  check1 = 0;
  while check1 == 0
    resp1 = input('Remove selected curves and finish? (y/n):\n','s');
    if strcmp(resp1,'y') == 1 || strcmp(resp1,'Y') == 1
      ind = cat(1,ind,indt);
      for m = 1:length(indt);
        cmd = ['if exist(''h' num2str(indt(m)) '''); delete(h' num2str(indt(m)) '); clear h' num2str(indt(m)) '; end;'];
        eval(cmd);
      end;
      done = 1; check1 = 1;
    end;
    if strcmp(resp1,'n') == 1 || strcmp(resp1,'N') == 1
      check1 = 1; check2 = 0;
      while check2 == 0
        resp2 = input('Remove all curves selected since last prompt? (y/n):\n','s');
        if strcmp(resp2,'y') == 1 || strcmp(resp2,'Y') == 1
          ind = cat(1,ind,indt);
          for n = 1:length(indt)
            cmd = ['if exist(''h' num2str(indt(n)) '''); delete(h' num2str(indt(n)) '); clear h' num2str(indt(n)) '; end;'];
            eval(cmd);
          end;
          check2 = 1;  
        end;
        if strcmp(resp2,'n') == 1 || strcmp(resp2,'N') == 1
          fprintf('Curves selected since last prompt not removed.\n');
          check2 = 1; 
        end;
      end;
    end;
  end;  
end;  

% Remove errant GC:
rseries  = unique(ind);
output_x = input_x; 
output_y = input_y;

if iscell(input_x) == 1
  output_x(rseries) = [];
  output_y(rseries) = [];
else
  output_x(rseries,:) = [];
  output_y(rseries,:) = [];
end;

% Save remainder plot if desired:
if exist('save_it') == 1
  figure(f2);
  axis tight;
  cmd = ['title(''' plot_title ''',''fontsize'',12);'];
  eval(cmd);
  cmd = ['print -dpng ' save_it '.png'];
  eval(cmd);
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Function to convert input array to cell:
function output = convert_to_cell(input)
for p=1:size(input,1)
  output{p} = input(p,:);
end;  
  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  

% Function to find minimum Euclidean distance:
function d1 = find_min_dist(px,py,cx,cy)
dx = cx-px;
dy = cy-py;
delt = (dx.^2 + dy.^2).^.5;
d1 = min(delt);
  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    