function [ii]=gxytzoom(arg1,arg2,arg3,varargin)
% ii = gxytzoom(x,y,t);              % returns indices chosen
% ii = gxytzoom(x,y,t,ii);           % initializes with ii, can reset
% ii = gxytzoom(xytstruct);          % send in a structure with fields 
%                                    % x,y,.dday
%
% zoom on axes: x,y  
%               t,y  
%               x,t  
% or reset to original axes.
% returns the selected indices when you're done (accept).
%
% varargin consists of optional previously selected {ii} dataset
% "Numbers" button now available for precise selections

global GHH  %global handle  
  
if (nargin==0)
  disp('using synthetic data')
  arg1=[-2*pi:pi/64:2*pi]';
  arg2=sin(arg1);
  arg3=20*exp(-(arg1/10).^2);
elseif (nargin==1)
  %passing in a handle with a data structure
  if (~isstruct(arg1))
	help gxytzoom2
	error('one argument as assumed to be a data structure')
  else
	x=arg1.x;
	y=arg1.y;
	t=arg1.dday;
  end
end

%start things up  ----------

origunits = get(0,'Units');
set(0,'Units','pixels');

GHH.fig = figure(999);

call_init;  %make the stuff for the window

GHH.x=arg1(:);
GHH.y=arg2(:);
GHH.t=arg3(:);
if isempty(varargin)
   GHH.II=[1:length(arg1)];
else
   GHH.II=varargin{1};
end
GHH.outsidefig = 0;   % .outsidefig = in "Numbers" screen (y/n)

draw_plots

msg = sprintf('Activate axes with small corner buttons  \n\nZoom with the left mouse button');
disp(msg); 
GHH.newaxisselected=0;
GHH.reallyquit=0;
GHH.resetaxes=0;

keepgoing = 1;
while ( ~GHH.reallyquit ) & ...
	  ( keepgoing  | ...
	  ~strcmp( get(gcf,'selectiontype'), 'alt') | ...
	  ~strcmp( get(gcf,'selectiontype'), 'extend') | ...
     ~GHH.outsidefig )
  
  %left-click
  keepgoing = 0;
  GHH.newaxisselected=0;
  waitforbuttonpress %can select a new axis, can zoom  or can quit
 
     if (strcmp( get(gcf,'selectiontype'), 'normal'))
        if (~GHH.newaxisselected & ~GHH.outsidefig)  %i.e. we did not change axes, so we zoomed
           GHH.nuax=rbbox;
           resize_axes
        end
     else
        notice('Must use left button only')
     end
end  % while


% Terminate ---------
set(0,'defaultaxesxgrid','off')
set(0,'defaultaxesygrid','off')
if GHH.BOX_OFF
   set(0,'defaultaxesbox','off')
end
set(0,'Units',origunits);

ii=GHH.II;
if strcmp(get(GHH.fig,'Tag'),'abandon'), ii=[];end

close(GHH.fig);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                              functions                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function   call_init      

  global GHH

  set(0,'defaultaxesxgrid','on')
  set(0,'defaultaxesygrid','on')
  if strcmp('off',get(0,'defaultaxesbox'))
	set(0,'defaultaxesbox','on')
	GHH.BOX_OFF = 1;
  else
	GHH.BOX_OFF = 0;
  end
  
  scrn = get(0,'ScreenSize');
  pos1 = scrn(3)*0.45; pos2 = scrn(4)*0.40; pos3 = scrn(3)*0.5; pos4 = scrn(4)*0.55;
  set(GHH.fig,'Color',[0.8 0.8 0.8], ...
     'Position',[pos1 pos2 pos3 pos4], ...
     'Tag','Fig999', ...
     'NumberTitle','off', ...
     'Name','Select section in pale blue area', ...
     'MenuBar','none');
  %previously 'Position',[509 334 512 384], ... 
  %dangerous positioning, what if 800 x 600 screen res.?

  %make top right x/y  - this one starts as the active one
  GHH.axesXY = axes('Parent',GHH.fig,...
	  'Position',[.4 .4 .5 .44],'color',[.9 1 1],...
	  'xaxisloc','top','yaxisloc','right');
  xlabel('longitude')
  ylabel('latitude')
  GHH.cur_zm=GHH.axesXY;

  %make bottom right axis: xt
  GHH.axesXT = axes('Parent',GHH.fig,...
	  'Position',[.4 .1 .5 .3],'yaxisloc','right');
  xlabel('longitude')
  ylabel('time')
  
  %make the top left axes: ty
  GHH.axesTY = axes('Parent',GHH.fig,...
	  'Position',[.1 .4 .3 .44],'xaxisloc','top');
  xlabel('time')
  ylabel('latitude')
  

  GHH.axesall = axes('Parent',GHH.fig,...
	  'Position',[.1 .1 .3 .3],'color',[.8 .8 .8]);
  xlabel('longitude')
  ylabel('latitude')

  GHH.acceptbutton = uicontrol('Parent',GHH.fig, ...
	  'Units','normalized',...
	  'BackgroundColor',[0 1 0], ...
	  'Callback','call_accept',...
	  'Position',[.85 .94 .1 .055],...  % orig .9 .93 .1 .05
	  'fontsize',8,...
	  'String','ACCEPT');
  GHH.resetbutton = uicontrol('Parent',GHH.fig, ...
	  'Units','normalized', ...
	  'BackgroundColor',[0 0 1], ...
	  'ForegroundColor',[1 1 1], ...
	  'Callback','call_reset',...
	  'Position',[.65 .94 .15 .055],...
	  'fontsize',8,...
     	  'String','RESET AXES');
  GHH.endbutton = uicontrol('Parent',GHH.fig, ...
	  'Units','normalized',...
	  'BackgroundColor',[1 0 0], ...
	  'Callback','cancelled',...
	  'Position',[.5 .94 .1 .055],...
	  'fontsize',8,...
	  'String','CANCEL');
   GHH.numbersbutton = uicontrol('Parent',GHH.fig, ...
	  'Units','normalized',...
	  'BackgroundColor',[1 1 0], ...
	  'Callback','numbers',...
	  'Position',[.33 .94 .12 .055],...
	  'fontsize',8,...
	  'String','NUMBERS');
  
  pp=get(GHH.axesTY,'position');
  GHH.tybutton = uicontrol('Parent',GHH.fig, ...
          'Units','normalized', ...
          'Callback','call_ty',...
          'Position',[.01+pp(1) .01+pp(2) .05 .05],...
          'String','t/y');
  pp=get(GHH.axesXY,'position');
  GHH.xybutton = uicontrol('Parent',GHH.fig, ...
          'Units','normalized', ...
          'Callback','call_xy',...
          'Position',[.01+pp(1) .01+pp(2) .05 .05],...
          'String','x/y');
  pp=get(GHH.axesXT,'position');
  GHH.txbutton = uicontrol('Parent',GHH.fig, ...
          'Units','normalized', ...
          'Callback','call_xt',...
          'Position',[.01+pp(1) .01+pp(2) .05 .05],...
          'String','x/t');  

% ------------------------------
function   call_xy; 
  global GHH

  %choose a new axis, redraw at current scale
  set(GHH.fig,'currentaxes',GHH.axesXY);
  GHH.newaxisselected=1;
  set(GHH.cur_zm,'color',[1 1 1])
  GHH.cur_zm = gca;
  set(GHH.cur_zm,'color',[.9 1 1])
  disp('Zoom in on the XY axis using the left button');
  disp('Start in the light blue region!!');

% ------------------------------
function   call_xt;
  global GHH

  %choose a new axis, redraw at current scale
  set(GHH.fig,'currentaxes',GHH.axesXT);
  GHH.newaxisselected=1;
  set(GHH.cur_zm,'color',[1 1 1])
  GHH.cur_zm = gca;
  set(GHH.cur_zm,'color',[.9 1 1])
  disp('Zoom in on the XT axis using the left button');
  disp('Start in the light blue region!!');
  
% ------------------------------
function   call_ty;
  global GHH

  %choose a new axis, redraw at current scale
  set(GHH.fig,'currentaxes',GHH.axesTY);
  GHH.newaxisselected=1;
  set(GHH.cur_zm,'color',[1 1 1])
  GHH.cur_zm = gca;
  set(GHH.cur_zm,'color',[.9 1 1])
  disp('Zoom in on the TY axis using the left button');
  disp('Start in the light blue region!!');
  %msg = sprintf('Zoom in on the TY axis using the left button  \n\n(Start in the light blue region!!)');
  %notice(msg,2);
  
%------------------------------  
function   call_accept;
  global GHH
  
  GHH.reallyquit=1;

% ------------------------------
function   call_reset;
  global GHH

  disp('resetting to original axis limits')
  GHH.II = 1:length(GHH.x);
  draw_plots
  GHH.resetaxes=1;

%------------------------------
function   cancelled;
  global GHH
  
  GHH.reallyquit=1;
  set(GHH.fig, 'Tag','abandon');
  
  %------------------------------
function   numbers;
  global GHH

  GHH.outsidefig = 1;
  if isempty(GHH.II), GHH.II = 1:length(GHH.x); end;
  i1 = GHH.II(1);
  i2 = GHH.II(end);

  % call gxytnumbers and initialize
  gxytnumbers
  
  radlh = findobj(gcf,'tag','radiolat');
  set(radlh,'userdata','4'); % arbitrary default
  
  tblatc = findobj(gcf,'tag','tboxlatcurrent');
  st = sprintf('[ %.2f  %.2f ]', min(GHH.y(GHH.II)), max(GHH.y(GHH.II)));
  %st = sprintf('[ %.2f  %.2f ]', GHH.y(i1), GHH.y(i2));
  set(tblatc,'string', st);
  tblatp = findobj(gcf,'tag','tboxlatpossible');
  st = sprintf('[ %.2f  %.2f ]', min(GHH.y), max(GHH.y));
  %msg = 'minlat(S) maxlat(N) minlon(W) maxlon(E)';
  set(tblatp,'string', st);
  
  tblonc = findobj(gcf,'tag','tboxloncurrent');
  st = sprintf('[ %.2f  %.2f ]', min(GHH.x(GHH.II)), max(GHH.x(GHH.II)));
  %st = sprintf('[ %.2f  %.2f ]', GHH.x(i1), GHH.x(i2));
  set(tblonc,'string', st);
  tblonp = findobj(gcf,'tag','tboxlonpossible');
  st = sprintf('[ %.2f  %.2f ]', min(GHH.x), max(GHH.x));
  %st = sprintf('[ %.2f  %.2f  %.2f  %.2f ]', GHH.y(1), GHH.y(end), GHH.x(1), GHH.x(end));
  set(tblonp,'string', st);
  
  tbtimc = findobj(gcf,'tag','tboxtimecurrent');
  st = sprintf('[ %.2f  %.2f ]', GHH.t(i1), GHH.t(i2));
  set(tbtimc,'string', st);
  tbtimp = findobj(gcf,'tag','tboxtimepossible');
  st = sprintf('[ %.2f  %.2f ]', GHH.t(1), GHH.t(end));
  set(tbtimp,'string', st);
  
  tbfrac = findobj(gcf,'tag','tboxfractioncurrent');
  st = sprintf('[ %.2f  %.2f ]', GHH.II(1)/length(GHH.x), GHH.II(end)/length(GHH.x));
  set(tbfrac,'string', st);
  tbfrap = findobj(gcf,'tag','tboxfractionpossible');
  set(tbfrap,'string', '[ 0.00  1.00 ]');

  uiwait
  
  tbcb = findobj(gcf,'tag','tboxnewpair');
  st = get(tbcb,'string');
  [stval] = str2num(st);
  rbl = findobj(gcf,'tag','radiolat');
  n = get(rbl,'userdata');
  rblo = findobj(gcf,'tag','radiolon');
  cancel = get(rblo,'userdata');
  
  close
  GHH.outsidefig = 0;
  
  if isempty(cancel) % proceed, not cancelled
     switch(n)
     case '1'  % adj. lat
         yii = find(GHH.y >= stval(1) & GHH.y <= stval(2));
         GHH.II = yii;
     case '2'  % adj. lon.
         xii = find(GHH.x >= stval(1) & GHH.x <= stval(2));
         GHH.II = xii;
     case '3'  % adj. time (dd)
         tii = find(GHH.t >= stval(1) & GHH.t <= stval(2));
         GHH.II = tii;
     case '4'  % adj. fraction
        if stval(1) <= 0
           newll = 1;
        else
           newll = round(stval(1)*length(GHH.x));
        end
        if stval(2) >= 1
           newul = length(GHH.x);
        else
           newul = round(stval(2)*length(GHH.x));
        end
        GHH.II = newll:newul;
     case '5'  % adj. lat/long (also = case '1' & case '2' as lat/long combined)
         yii = find(GHH.y >= stval(1) & GHH.y <= stval(2));
         xii = find(GHH.x >= stval(3) & GHH.x <= stval(4));
         newmat = zeros(length(GHH.x),3);
         newmat(yii,1) = 1;
         newmat(xii,2) = 1;
         newmat(:,3) = newmat(:,1).*newmat(:,2);
         GHH.II = find(newmat(:,3));
     end
%   else
%      GHH.II = i1:12; % no change
  end

  draw_plots
  
%----------------------------------------------------------------------	
function resize_axes 
  global GHH
  
  XX=GHH.x;
  YY=GHH.y;
  TT=GHH.t;

  nuax=GHH.nuax;
  if (GHH.resetaxes==1)
	GHH.resetaxes=0;
  else
	% return if it's a mistake (small region and not a button)
	if (nuax(3)<10 | nuax(4)<10 ) & (GHH.newaxisselected | GHH.reallyquit)
	  return %do nothing
	elseif  (nuax(3)<10 | nuax(4)<10 ) %just too small
	  disp('not redrawing: zoom is too small to register')
	  return
	else
	end
	
	% determine the two corners of the selected box in pixels
	x1 = nuax(1);
	y1 = nuax(2);
	x2 = x1 + nuax(3);
	y2 = y1 + nuax(4);
	
	% translate pixels to relative coordinates
	
	t1 = get(gcf,'posit');
	x1 = x1/t1(3);
	x2 = x2/t1(3);
	y1 = y1/t1(4);
	y2 = y2/t1(4);
	
	% translate relative coordinates to axis coordinates
	
	t1 = get(GHH.cur_zm,'posit');
	
	x1 = x1 - t1(1);
	x2 = x2 - t1(1);
	y1 = y1 - t1(2);
	y2 = y2 - t1(2);
	
	xlm = get(GHH.cur_zm,'xlim');
	ylm = get(GHH.cur_zm,'ylim');
	
	x1 = x1/t1(3)*diff(xlm)+xlm(1);
	x2 = x2/t1(3)*diff(xlm)+xlm(1);
	y1 = y1/t1(4)*diff(ylm)+ylm(1);
	y2 = y2/t1(4)*diff(ylm)+ylm(1);
	
	t1 = min([x1 x2]);
	t2 = max([x1 x2]);
	t3 = min([y1 y2]);
	t4 = max([y1 y2]);
	if GHH.cur_zm==GHH.axesXY
	  t1 = find(XX(GHH.II)>t1 & XX(GHH.II)<t2 & YY(GHH.II)>t3 & YY(GHH.II)<t4);
	elseif GHH.cur_zm==GHH.axesXT
	  t1 = find(XX(GHH.II)>t1 & XX(GHH.II)<t2 & TT(GHH.II)>t3 & TT(GHH.II)<t4);
	else
	  t1 = find(TT(GHH.II)>t1 & TT(GHH.II)<t2 & YY(GHH.II)>t3 & YY(GHH.II)<t4);
	end
	GHH.II = GHH.II(t1);
	
	draw_plots
  end
	
%------------------------------
function draw_plots
  global GHH
  
  XX=GHH.x;
  YY=GHH.y;
  TT=GHH.t;

  axes(GHH.axesXY);
  delete( findobj(gca,'type','line') )
  line(XX(GHH.II),YY(GHH.II),'marker','.')
  set(GHH.axesXY,'xtickmode','auto')
  xts = get(GHH.axesXY,'xtick');
  set(GHH.axesXY,'xtick',xts(2:end));
  set(GHH.axesXY,'ytickmode','auto')
  yts = get(GHH.axesXY,'ytick');
  set(GHH.axesXY,'ytick',yts(2:end));

  axes(GHH.axesall)
  delete( findobj(gca,'type','line') )
  line(XX,YY,'marker','.','color','b')
  line(XX(GHH.II),YY(GHH.II),'marker','.','color','r')
  set(GHH.axesall,'xtickmode','auto')
  xts = get(GHH.axesall,'xtick');
  set(GHH.axesall,'xtick',xts(1:end-1));
  set(GHH.axesall,'ytickmode','auto')
  yts = get(GHH.axesall,'ytick');
  set(GHH.axesall,'ytick',yts(1:end-1));

  axes(GHH.axesXT)
  delete( findobj(gca,'type','line') )
  line(XX(GHH.II),TT(GHH.II),'marker','.')
  set(GHH.axesXT,'xtickmode','auto')
  xts = get(GHH.axesXT,'xtick');
  set(GHH.axesXT,'xtick',xts(1:end-1));
  set(GHH.axesXT,'ytickmode','auto')
  yts = get(GHH.axesXT,'ytick');
  set(GHH.axesXT,'ytick',yts(2:end));

  axes(GHH.axesTY)
  delete( findobj(gca,'type','line') )
  line(TT(GHH.II),YY(GHH.II),'marker','.')
  set(GHH.axesTY,'xtickmode','auto')
  xts = get(GHH.axesTY,'xtick');
  set(GHH.axesTY,'xtick',xts(2:end));
  set(GHH.axesTY,'ytickmode','auto')
  yts = get(GHH.axesTY,'ytick');
  set(GHH.axesTY,'ytick',yts(1:end-1));

  %end of function draw_plots

  


  