function argout = stasel(m)
%
%            Deirdre Byrne, L-DEO, 1 Dec 1995
%                 dbyrne@ldeo.columbia.edu
%
%
%  part of staplot package.

global sections sta typevar nstn proj projlim lon_var lat_var
global F_HANDLES proplist figchars ifig B_HANDLES
global new the_fig GEO_HANDLE polon polat
% note: global vars must be re-initialized *every* time a function is called
s = size(proplist); str = []; for i = 1:s(1); str = [str ' ']; end
str = sprintf('%s',[proplist str']');
eval(['global ' str]);
sta = sta(:);
VERSION = version; VERSION = str2num(VERSION(1));
if VERSION < 5
  affirm = 'yes';
  deny = 'no';
else
  affirm = 'on';
  deny = 'off';
end

if ~isstr(m)
  if m == 1
    pix = get(0,'children'); 		% check for live staplot figs
    kids = [];
    for i = 1:length(pix)
      if isstrcmp(get(pix(i),'userdata'),'staplot')
	kids = [kids pix(i)];
      end
    end
    for i = 1:length(kids) % find most recent plot that's a staplot plot
      if any(kids(i) == F_HANDLES)
	figure(kids(i));
	break
      end
    end
    ifig = min(find(F_HANDLES == gcf)); % get newest one
    the_fig = gcf;
    if isempty(ifig)
      disp('No plots in which to select stations')
      new = sta;
      return
    end
    if figchars(ifig,4) > 2 % it's a distance plot
      disp('Cannot station select in this plot')
      new = sta;
      return
    else
      new = [];
      set(gcf,'windowbuttondownfcn','stasel(''down'')', ...
	  'windowbuttonupfcn','1;', ...
	  'windowbuttonmotionfcn','','buttondownfcn','', ...
	  'interruptible',affirm);
      return
    end
  else	% m == 0
    set(the_fig,'windowbuttondownfcn','','windowbuttonupfcn','',...
	'windowbuttonmotionfcn','','buttondownfcn','');
    sta = new; new = [];
    hydroplt('gsetsta');
    return
  end
else  % we are choosing stations  
  m = lower(m); 
  if strcmp(m,'down'),
    ax = get(gcf,'Children'); % look for figure axes
    valid = 0;
    for i=1:length(ax),
      if strcmp(get(ax(i),'Type'),'axes'),
	pt1 = get(ax(i),'CurrentPoint');
	xlim = get(ax(i),'XLim');
	ylim = get(ax(i),'YLim');
	if (xlim(1) <= pt1(1,1) & pt1(1,1) <= xlim(2) & ...
	      ylim(1) <= pt1(1,2) & pt1(1,2) <= ylim(2))
	  valid = 1;
	  % cleverly change to axis in which pointer is found,
	  % allowing Stasel for multiple plots on one fig
	  set(gcf,'CurrentAxes',ax(i)); 
	  break
	end
      end
    end
    
    if ~valid; return; end
    pt1 = get(gca,'currentpoint');
    pt2 = pt1;
    c = computer;
    if strcmp(c(1:2),'MA')
      rb0 = get(gcf,'currentpoint');
      rbbox([rb0 0 0],get(gcf,'currentpoint'))
      w = 1;
      while w
        w = waitforbuttonpress;
        rbbox([rb0 0 0],get(gcf,'currentpoint'))
      end
    else
      % this is the key little line:
      rbbox([get(gcf,'currentpoint') 0 0],get(gcf,'currentpoint'))
    end
    pt2 = get(gca,'currentpoint');
    pt1 = pt1(1,1:2);
    pt2 = pt2(1,1:2);
    xmin = min([pt1(1,1) pt2(1,1)]); ymin = min([pt1(1,2) pt2(1,2)]);
    xmax = max([pt1(1,1) pt2(1,1)]); ymax = max([pt1(1,2) pt2(1,2)]);
    sta_picks = get(gca,'Userdata');
    if length(sta_picks) > 0
      sta_picks = sta_picks(findnew(sta_picks)');
      jjj = figchars(ifig,:);
      argx = fliplr(deblank(fliplr(deblank(proplist(jjj(1),:)))));
      argy = fliplr(deblank(fliplr(deblank(proplist(jjj(2),:)))));
      % the one special-est case :-(
      if strcmp(argx,lon_var) & strcmp(argy,lat_var) & (gcf == GEO_HANDLE)
	if strcmp(proj,'north') | strcmp(proj,'south')
	  argx = 'polon'; argy = 'polat';
	end
      end
      eval(['x = size(' argx '); y = size(' argy ');'])
      typex = typevar(jjj(1)); typey = typevar(jjj(2));
      if (any(x <= 1) & typex == 3) | (min(x) ~= 1 & (typex == 1 | typex == 2))
	disp('Check and reset variable types with ''showttype'' and ''settype''.')
	return
      end
      if (any(y <= 1) & typey == 3) | (min(y) ~= 1 & (typey == 1 | typey == 2))
	disp('Check and reset variable types with ''showttype'' and ''settype''.')
	return
      end
      i = []; j = []; k = []; l = length(sta_picks);
      if typex == typey
	if typex == 3
	  if x(2) == nstn & y(2) == nstn
	    xarg = ['(' argx '(:,sta_picks) >= xmin) & ', ...   
		    '(' argx '(:,sta_picks) <= xmax)'];
	    yarg = ['(' argy '(:,sta_picks) >= ymin) & (' argy, ...
		    '(:,sta_picks) <= ymax)'];
	    arg = ['[i j] = find(' xarg ' & ' yarg ');'];
	  else
	    disp('No can do')
	    new = sta;
	    return
	  end
	elseif typex == 1
	  if max(x) == nstn & max(y) == nstn
	    % fixed bug 97/5/19
	    eval(['tempx = ' argx '(:)'';']);
	    eval(['tempy = ' argy '(:)'';']);
	    xarg = '(tempx(sta_picks) >= xmin) & (tempx(sta_picks) <= xmax)';
	    yarg = '(tempy(sta_picks) >= ymin) & (tempy(sta_picks) <= ymax)';
	    arg = ['j = find(' xarg ' & ' yarg ');'];
	  else
	    disp('No can do')
	    new = sta;
	    return
	  end
	else
	  disp('No can do')
	  new = sta;
	  return
	end
      else % not the same type
	% get nrow
	if typex == 3, nrow = x(1);
	elseif typey == 3, nrow = y(1);
	elseif typex == 2, nrow = max(x);
	else, nrow = max(y);
	end
	
	% set up matrix args
	if typex == 1
	  if max(x) == nstn;
	    % fixed bug 97/05/05
	    eval(['tempx = ' argx '(:)'';']);
	    xarg = ['(ones(nrow,1)*tempx(sta_picks) >= xmin) & ', ...
		    '(ones(nrow,1)*tempx(sta_picks) <= xmax)' ];
	  else
	    disp('No can do')
	    new = sta;
	    return
	  end
	elseif typex == 2;
	  x = eval(argx);
	  xarg = '((x(:)*ones(1,l)) >= xmin) & ((x(:)*ones(1,l)) <= xmax)';
	else 				% x-arg is type 3
	  if x(2) == nstn;
	    xarg = ['(' argx '(:,sta_picks) >= xmin) & ', ...   
		    '(' argx '(:,sta_picks) <= xmax)'];
	  else
	    disp('No can do.')
	    new = sta;
	    return
	  end
	end
	if typey == 1
	  % fixed bug 97/05/05
	  eval(['tempy = ' argy '(:)'';']);
	  if max(y) == nstn;
	    yarg = ['(ones(nrow,1)*tempy(sta_picks) >= ymin) & ', ...
		    '(ones(nrow,1)*tempy(sta_picks) <= ymax)' ];
	  else
	    disp('No can do.')
	    new = sta;
	    return
	  end
	elseif typey == 2;
	  y = eval(argy);
	  yarg = '((y(:)*ones(1,l)) >= ymin) & ((y(:)*ones(1,l)) <= ymax)';
	else 				% y-arg is type 3
	  if y(2) == nstn;
	    yarg = ['(' argy '(:,sta_picks) >= ymin) & (' argy, ...
		    '(:,sta_picks) <= ymax)'];
	  else
	    disp('No can do.')
	    new = sta;
	    return
	  end
	end
	arg = ['[i j] = find(' xarg ' & ' yarg ');'];
      end
      
      % execute argument
      eval(arg)
      j = j(findnew(j));
      if length(j) > 0;
	j = sta_picks(j);
	new = [new; j(:)];
	new = new(findnew(new));
      end
    end
  end
end
