function argout = tsedit(m)
%
%            Deirdre Byrne, L-DEO, 5 May 1997
%                 dbyrne@ldeo.columbia.edu
%
%
%  hack addition to staplot package.

global sections sta typevar nstn proj projlim lon_var lat_var
global F_HANDLES proplist figchars ifig B_HANDLES switchon TS_HANDLE
global the_fig GEO_HANDLE polon polat pr_var de_var pt_var sa_var
global te_var ts_edit ts_quit depths new
% 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]);
check = 0;
if ~isempty(de_var)
  if exist(de_var) == 1
    check = check + 1;
  else
    if ~isempty(pr_var)
      if exist(pr_var) == 1
	check = check + 1;
      end
    end
  end
else
  if ~isempty(pr_var)
    if exist(pr_var) == 1
      check = check + 1;
    end
  end
end

if ~isempty(te_var)
  if exist(te_var) == 1
    check = check + 1;
  else
    if ~isempty(pt_var)
      if exist(pt_var) == 1
	check = check + 1;
      end
    end
  end
else
  if ~isempty(pt_var)
    if exist(pt_var) == 1
      check = check + 1;
    end
  end
end

if ~isempty(sa_var)
  if exist(sa_var) == 1 
    check = check + 1;
  end
end

if check < 3
  disp('Cannot use TS edit.')
  return
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 STAPLOT plots in which to select stations')
      return
    elseif the_fig ~= TS_HANDLE
      disp('This is not your TS plot')
      return
    end
    if figchars(ifig,4) > 2 % it's a distance plot
      disp('Cannot station select in this plot')
      new = sta;
      return
    else
      % we're in business
      new = [];
      depths = [];
      % get rid of old TS edit window
      if ~isempty(ts_edit)
	if findobj(TS_HANDLE,'type','uicontrol','style','edit') == ts_edit
	  delete(ts_edit)
	end
      end
      if ~isempty(ts_quit)
	if findobj(TS_HANDLE,'type','uicontrol','style','pushbutton') == ts_quit
	  delete(ts_quit)
	end
      end
      set(gcf,'windowbuttondownfcn','tsedit(''down'')', ...
	  'windowbuttonupfcn','1;', ...
	  'windowbuttonmotionfcn','','buttondownfcn','', ...
	  'interruptible',switchon);
       ts_edit = uicontrol(TS_HANDLE, 'style','edit', ...
	   'max', 2, ...
	   'units','normalized', ...
	   'position', [0 0.952 0.243 0.048], ...
	   'visible','on', ...
	   'string','St.   PR or DE', ...
	   'foregroundcolor', [1 1 1], ...
	   'backgroundcolor', [0 0.5 0.5]);
       ts_quit = uicontrol(TS_HANDLE, 'style','push', ...
	   'units','normalized', ...
	   'position', [0.193 0.95 0.05 0.05], ...
	   'visible','on', ...
	   'string','X', ...
	   'callback', 'tsedit(''quit'')', ...
	   'foregroundcolor', [0 0.5 0.5], ...
	   'backgroundcolor', [0.702 0.702 0.702]);
      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, 'quit')
    set([ts_edit ts_quit],'visible','off')
    return
  elseif 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 Tsedit 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),:)))));
      eval(['x = size(' argx '); y = size(' argy ');'])
      typex = typevar(jjj(1)); typey = typevar(jjj(2));
      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
	end
      end
      % execute argument
      eval(arg)
      k = findnew(j);
      j = j(k);
      if length(i) > 0;
	% pick Pressure or Depth
	if exist(pr_var) == 1
	  argz = pr_var;
	else
	  argz = de_var;
	end
	% list of stations
	j = sta_picks(j);
	j = j(:);
	new = [new; j];
	new = new(findnew(new));
	k = [k; length(i)+1];
	for ii = 1:length(k)-1
	  depths = [depths; j(ii) minmax(PR(i(k(ii)):i(k(ii+1)-1), j(ii)))];
	end
	str = sprintf('%s\n','St.   PR or DE');
        s = sprintf('%i   %.1f - %.1f\n',depths');
	s = [str s];
	h = min([0.048*(size(depths,1)+1) 1]);
        set(ts_edit,'string', s, ...
	    'visible','on', ...
	    'units','normalized', ...
	    'position', [0 1-h 0.243 h])
	set(ts_quit,'visible','on')
      end
    end
  end
end
