function [DATA,Vx]=view5(DATA,vdims,iich,iinewfig,tsize,instr,iifig_size)
% Call [DATA,Vx]=view5(DATA,vdims,iich,iinewfig,tsize,instr,iifig_size)
%
% Generalization of view3 for 5-dimensional data;
% User inputs two dimensions over which to image, one dimension over which to step;
%
%
% If errors occur for no apparent reason, reset viewing options by executing "view_global_set".
%
% DATA		= structure containing fields .x,.y,.z,.data,.xlab,.ylab,.zlab, OR
%		  	  root of HDF file that contains 2- or 3-D data, OR
%		  	  root of .mat file that contains a structure with same fields as above;
% vdims		= [y_dim,x_dim,fix_dim] dimensions to image and dimension to step through;
% iich 		= 1 to change values, 0 to leave as specified in V;
% iinewfig	= 1 to create new figure, 0 to plot on current figure;
% tsize		= image size (default is that in V.size);
% instr     = 1 to print out instructions on key strokes;
%
% V.ii_img: 	0=line plot; 1=image; 2=contour; 3=grid of images;
% V.iilog(1:6): 0=linear axis, 1=log axis [choose for each of six axes: y,x,z,z2,z3,data];
% V.iibar: 		0=no colorbar, 1=add colorbar (for images only);
% V.clim = 		min, max value for imaging, plotting, or contouring ([]=use data);
% V.unit,V.size,V.ptsize = 		values for size of plot and lines;
%
% view5 help
%  
% Place crosshairs over figure and enter one of the keystroke commands below.;
% Some commands take effect immediately;
%   e.g., ''L'' immediately switches from image to line plot;  ''I'' from line to image.
% Other comands require further input from command line;
%   e.g., ''c'' changes the color scale.  After entering ''c'', go to the command line
%     and enter new color scale limits.
%  
% Basic Commands
%   carriage return = exit view5
%   c = change Color scale
%   s = change image Size
%   m = change color Map
%   L = Line plot, horizontal
%   +/- = change line plot index; e.g., move line plot in time
%   P = multiple line Plots (each row of image becomes a different color line)
%   V = Vertical line plot
%   I = Image plot (switch back from line plot)
%   left click mouse = zoom (must click twice to define rectangle)
%     right click mouse = restore full image
%   l = Label & mark peaks (finds local maximum near crosshairs)
%   F = spawn new Figure window (i.e., to save current view in old window)
%   down-arrow or keypad 2 = choose dimensions to image
%  
% Manipulate Current Image
%   i = toggle axis ij/xy (flip vertical axis)
%   / = switch x-y axes
%   ? = switch x-y & hor/ver (rotate image)
%   b = toggle colorBar on/off
%   g = toggle Grid lines on/off
%   x = change X-axis limits
%   y = change Y-axis limits
%   t to toggle Time axis between time and sequence number
%   C = contours
%  
% Line Plot Commands
%   =/_ to set line plot index(es)/value(s)
%   h = set line colors and styles
%   H = change symbols and symbol sizes
%   Y = symbols & no lines
%   w = change line Width
%   [ = set axis(''tight' automatically for each line plot
%  
% Text Commands
%   B = toggle Bold
%   p = change font Point size
%  
% Manipulating Multi-Dimensional (> 2) Data Sets
%   G = Grid of images
%   M = Movie
%   left/right arrows or keypad 4/6 = vary index of first fixed dimension
%   keypad 7/9 = vary index of second fixed dimension
%   keypad 1/3 = vary index of third fixed dimension
%   up-arrow or keypad 8 = cycle through dimensions
%     * = cycle opposite way
%   5 = cycle through fixed dim
%   z/Z = set fixed dimension by index/value
%  
% Special Purpose Commands
%   A = toggle scales/scales2
%   d = convert to dB (10*log10)
%   D = convert to dB (20*log10)
%   a = toggle dB/(angle/pi)
%   u = unwrap phase
%   T = threshold
%
% COPYRIGHT (c) 2008
% 
% Applied Research Laboratories, The University of Texas at Austin
% (ARL:UT)
% All rights reserved.
% 
% This material may be reproduced by or for the U.S. Government
% only. This notice must appear in all copies of this file and its
% derivatives. Further distribution outside the U.S. Government is
% prohibited without the explicit written authorization from the
% Director of the Environmental Sciences Laboratory, ARL:UT.
% 
% THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
% EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE
% IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
% PURPOSE, OR NONINFRINGEMENT.
% 
% IN NO EVENT WILL ARL:UT BE LIABLE FOR ANY DAMAGES WHATSOEVER ARISING
% OUT OF THE USE OR INABILITY TO USE THIS SOFTWARE, EVEN IF ARL:UT HAS
% BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

view_global
%
if nargin<1, DATA=[]; end
if nargin<2, vdims=[]; end
if nargin<3, iich=1; end
if nargin<4, iinewfig=1; end
if nargin<5, tsize=[]; end
if nargin<6, instr=1; end
if nargin<7, iifig_size=[]; end
%
if isempty(V), view_global_set; end
if isempty(iinewfig), iinewfig=1; end
if ~isempty(tsize), V.size=tsize; end
%
if ~isfield(V,'col'), V.col={'r','b','g','m','c','k'}; end
if ~isfield(V,'sty'), V.sty={'-'}; end
%
if isfield(DATA,'vdims'), vdims=DATA.vdims; elseif isfield(V,'vdims'), vdims=V.vdims; end
if isfield(DATA,'ii_img'), V.ii_img=DATA.ii_img; end
if isfield(DATA,'iiq'), V.iiq=DATA.iiq; end
if isfield(DATA,'size'), V.size=DATA.size; end
if isfield(DATA,'iisc2'), V.iisc2=DATA.iisc2; end
if isfield(DATA,'iigrid'), V.iigrid=DATA.iigrid; end
% For line colors and styles, don't update V.col and V.sty since it's hard for the user to
% go back to the defaults:
if isfield(DATA,'col'), COL=DATA.col; else, COL=V.col; end
if isfield(DATA,'sty') & ~isempty(DATA.sty), STY=DATA.sty; else, STY=V.sty; end
if isfield(DATA,'sym'), SYM=DATA.sym; else, SYM=V.sym; end
if isfield(DATA,'dot'), DOT=DATA.dot; elseif isfield(V,'dot'), DOT=V.dot; else, DOT={5}; end
if isfield(DATA,'ii_tight') ii_tight=DATA.ii_tight; else, ii_tight=0; end
%
if ~isfield(V,'iilog') | iscell(V.iilog), V.iilog=zeros(1,6); end
if length(V.iilog)<6, V.iilog=zeros(1,6); end
if ~isfield(V,'ii_img'), V.ii_img=1; end
if ~isfield(V,'iibar'), V.iibar=1; end
if ~isfield(V,'ident'), V.ident=1; end
if ~isfield(V,'lwidth'), V.lwidth=1.5; end
if ~isfield(V,'iibold'), V.iibold=1; end
if ~isfield(V,'unit'), V.unit='in'; end
if ~isfield(V,'size'), V.size=[5,3.5]; end
if ~isfield(V,'ptsize'), V.ptsize=14; end
if ~isfield(V,'cmap'), V.cmap=jet; end
if ~isfield(V,'sym'), V.sym={'o'}; end
if ~isfield(V,'fname'), V.fname='Arial'; end
if ~isfield(V,'iivg'), V.iivg=1; end
if ~isfield(V,'iiq'), V.iiq=1; end
if ~isfield(V,'iisc2'), V.iisc2=0; end
if ~isfield(V,'iiz'), V.iiz=[1]; end
if ~isfield(V,'grid_dims'), V.grid_dims=[1 1]; end
if ~isfield(V,'ii_row_major'), V.ii_row_major=1; end
if ~isfield(V,'iigrid'), V.iigrid=0; end
MG=[];
%
ii_sym=0;
%
iihdf=0;
if isempty(DATA),
	disp('No data input to view: choose .mat file or cancel to choose HDF file');
	[f_file,DATA,iif,path_back]=check_for_file([],'hdf','HDF');
	DATA=DATA(1:end-1);
	if ~iif,
		[f_file,DATA,iif,path_back]=check_for_file([],'.mat','.mat'),
		if ~iif; disp('No files chosen.  Returning from view5'); return; end
	end
end
%
iihdf_fmt=0;
if ischar(DATA),
    if any(DATA=='*'),
	    disp('Choose desired data file or cancel to exit: ');
	    [DATA,f_root,iif,path_back]=check_for_file([],DATA,[]),
        ii=findstr(DATA,'.');
        if ~isempty(ii), DATA=DATA(1:ii(end)-1), end
    end   
	disp('Checking for HDF or .mat files ...')
	file_root=DATA; clear DATA;
    iihdf1=exist([file_root,'.hdf'],'file')==2;
    iihdf2=exist(file_root,'file')==2 & strcmp(file_root(max(1,end)-3:end),'.hdf');
	if iihdf1 | iihdf2,
        if iihdf2, file_root=file_root(1:end-4); end
		[SD,status]=hdfsd_open([file_root,'.hdf']);
        if status~=0, error(['Error opening HDF file: ',file_root,'.hdf']); end
		if SD.nset>1, 
			disp(['HDF file contains ',int2str(SD.nset),' datasets named: ']);
			disp(SD.data_name)
			jset=input('Enter data number: ');
		else
			jset=1;
		end
		[DATA,status]=hdfsd_read(SD,[],jset);
        if status<0, display('hdfsd_read not successful'); display(status); return; end
        iihdf_fmt=1; DATA.labels{DATA.ndim}
        if strcmp(DATA.labels{DATA.ndim},'Re/Im'),
            disp('forming complex values ...');
            DATA.ndim=DATA.ndim-1;
            npt_tot=prod(DATA.dims(1:DATA.ndim-1)); 
            DATA.data=DATA.data(1:npt_tot) + i*DATA.data(npt_tot+1:2*npt_tot);
            DATA.dims=DATA.dims(1:DATA.ndim);
            DATA.data=reshape(DATA.data,DATA.dims);
            DATA.labels=DATA.labels(1:DATA.ndim);
            DATA.scales=DATA.scales(1:DATA.ndim);
            DATA.iidB=-1;
        end
	elseif exist([file_root,'.mat'],'file')==2,
%		str=['S = load(''',file_root,'.mat''');'], eval(str);
		S=load([file_root,'.mat']);
		if ~isstruct(S), disp('.mat file did not contain structure'); return; end
		fields=fieldnames(S); nfield=length(fields);
		if nfield>1,
			disp(fields);
			jfield=input('Enter data structure number to view: ');
		else,
			jfield=1;
		end
		str=['DATA=S.',fields{jfield},';']; disp(str); eval(str);
		if isempty(DATA), disp('Data found to be empty'); return; end
        nset=length(DATA);
        if nset>1, 
            jset=input([int2str(nset),' data structures in .mat file: Enter desired one: ']);
            DATA=DATA{jset}; iihdf_fmt, DATA, 
        end
	else
		disp('Input found to be a string, but no HDF or .mat file found locally')
		return
	end
end
%
%[ny,nx,nz,nz2,nz3,nz4,nz5]=size(DATA(1).data);
%if any([ny,nx,nz,nz2,nz3,nz4,nz5]==0), disp(DATA); error('DATA is empty'); end
% Check that first argument is a structure containing data, axes, and labels:
if ~isstruct(DATA),
	disp('view5 requires DATA structure or HDF/.mat file root');
	return
end
if ~isfield(DATA,'dims'), error('DATA structure must have fields "ndim", "dims", "labels", etc'); end
nset=length(DATA);
if nset>1,
    disp('Choose which dataset to plot or image: ');
    for jset=1:nset,
        disp(['Set number ',int2str(jset),' = ',DATA(jset).dlab]);
    end
    jset=input('Enter set number: ');
    DATA=DATA(jset);
end
% Allow DATA to be structure output from hdfsd_read:
%data=DATA.data; ndim_max=7;
%vars={'y','x','z','z2','z3','z4','z5'};
%for jdim=1:DATA.ndim,
%	str=[vars{jdim},'=DATA.scales{jdim};']; eval(str);
%	str=['V.',vars{jdim},'lab=DATA.labels{jdim};']; eval(str);
%end
%for jdim=DATA.ndim+1:ndim_max,
%	str=[vars{jdim},'=0;']; eval(str);
%	str=['V.',vars{jdim},'lab='' '';']; eval(str);
%end
dlab=DATA.dlab; dlabs=DATA.dlab; jdim_dlab=0;
if iscell(dlab),
    for jdim=1:DATA.ndim,
        if all(strcmp(DATA.dlab,DATA.labels{jdim})), jdim_dlab=jdim; end
    end
end
    %else	
%	if isfield(DATA,'y'), y=DATA.y; else, y=1:ny; end
%	if isfield(DATA,'x'), x=DATA.x; else, x=1:nx; end
%	if isfield(DATA,'z'), z=DATA.z; else, z=1:nz; end
%	if isfield(DATA,'z2'), z2=DATA.z2; else, z2=1:nz2; end
%	if isfield(DATA,'z3'), z3=DATA.z3; else, z3=1:nz3; end
%	if isfield(DATA,'z4'), z4=DATA.z4; else, z4=1:nz4; end
%	if isfield(DATA,'z5'), z5=DATA.z5; else, z5=1:nz5; end
%	if isfield(DATA,'data'), data=DATA.data; end
%	if isfield(DATA,'ylab'), V.ylab=DATA.ylab; else, V.ylab='y-axis'; end
%	if isfield(DATA,'xlab'), V.xlab=DATA.xlab; else, V.xlab='x-axis'; end
%	if isfield(DATA,'zlab'), V.zlab=DATA.zlab; else, V.zlab='z-axis'; end
%	if isfield(DATA,'z2lab'), V.z2lab=DATA.z2lab; else, V.z2lab='z2-axis'; end
%	if isfield(DATA,'z3lab'), V.z3lab=DATA.z3lab; else, V.z3lab='z3-axis'; end
%	if isfield(DATA,'z4lab'), V.z4lab=DATA.z4lab; else, V.z4lab='z4-axis'; end
%	if isfield(DATA,'z5lab'), V.z5lab=DATA.z5lab; else, V.z5lab='z5-axis'; end
%	if isfield(DATA,'dlab'), dlab=DATA.dlab; else, dlab='Data'; end
%end
if isfield(DATA,'clim'), V.clim=DATA.clim; end
if isfield(DATA,'cmap'), V.cmap=DATA.cmap; end
if isfield(DATA,'title'), ident=DATA.title; else, ident=' '; end
if isempty(ident), ident=' '; end
ident=strrep(ident,'\','/'); ident=strrep(ident,'_','\_');
if isfield(DATA,'size'), V.size=DATA.size; end
%
if prod(size(V.size))~=2 | any(V.size==0), V.size=[5,3.5]; disp('Bad plot size fixed'); end
%
data=DATA.data;
if any(~isreal(data(:))), 
	data=dB(data); 'dB done',
end
%
if isfield(DATA,'scales2') & isfield(DATA,'labels2') & V.iisc2,
	axvals=DATA.scales2; axlabs=DATA.labels2;
else
	axvals=DATA.scales; axlabs=DATA.labels;
end
%%ny,nx,nz,nz2,nz3,length(y),length(x),length(z),length(z2),length(z3),
%%DATA, keyboard
%x,y,z,z2,z3,nx,ny,nz,nz2,nz3,keyboard,
%axlims0={[y(1) y(ny)]; [x(1) x(nx)]; [z(1) z(nz)]; [z2(1) z2(nz2)]; [z3(1) z3(nz3)]; ...
%        [z4(1) z4(nz4)]; [z5(1) z5(nz5)]};
%axlims=axlims0;
%
axind=cell(1,DATA.ndim); axlims0=axind;
for jdim=1:DATA.ndim, 
    axind{jdim}=[1:DATA.dims(jdim)]; 
%     axlims0{jdim}=reshape(axvals{jdim}([1,end]),[1,2]); disp(axlims0{jdim}),
    axlims0{jdim}=[min(axvals{jdim}), max(axvals{jdim})]; %%disp(axlims0{jdim}),
end
axlims=axlims0;
%
[nrow,ncol,nlay,nlay2,nlay3,nlay4,nlay5]=size(data);
dmin=min(data(:)); dmax=max(data(:));
if isempty(V.clim), V.clim=[dmin,dmax]; end
if length(V.clim(:))==1, V.clim=[dmax-abs(V.clim(1)),dmax]; end
if dmin>V.clim(2) | dmax<V.clim(1),
	V.clim=[dmin,dmax]; 
end
%
dims=[nrow,ncol,nlay,nlay2,nlay3,nlay4,nlay5]; ndim=length(dims);%% disp(dims);
if prod(dims)==1,
	disp(['Single number in data set: ',num2str(data(1))]);
	return
end
iiok=find(dims>1); dims_ok=dims(iiok); ndim_ok=length(iiok);
if ndim_ok<3 & V.ii_img==3, V.ii_img=1; end
ii1v=find(dims==1); 
[dims_sort,ii_sort]=sort(dims_ok);
%
% Find time dimension
time_dim=find(strncmp(axlabs,'Time -',6) | strncmp(axlabs,'time -',6));
if length(time_dim)>1, time_dim=time_dim(end); end
time_unit=0;
iithresh=0;
if ~isempty(time_dim) & dims(time_dim)>1,
	iihr1=findstr(axlabs{time_dim},'hour'); iihr2=findstr(axlabs{time_dim},'Hour');
	iimin1=findstr(axlabs{time_dim},'min'); iimin2=findstr(axlabs{time_dim},'Min');
	iisec=findstr(axlabs{time_dim},'- s');
	time_lab{1}='Time - hour'; time_lab{2}='Time - min'; time_lab{3}='Time - s';
	if ~isempty(iihr1) | ~isempty(iihr2),
		time_unit=1;
		time_ax{1}=axvals{time_dim};
		time_ax{2}=60*(time_ax{1} - time_ax{1}(1));
		time_ax{3}=3600*(time_ax{1} - time_ax{1}(1));
		time_lab{1}=axlabs{time_dim};
		hour0=sprintf('%1.3f',time_ax{1}(1));
		time_lab{2}=[time_lab{2},' re ',axlabs{time_dim}(end-2:end),'/',hour0];
		time_lab{3}=[time_lab{3},' re ',axlabs{time_dim}(end-2:end),'/',hour0];
	elseif ~isempty(iimin1) | ~isempty(iimin2),
		time_unit=2; 
		time_ax{2}=axvals{time_dim};
		time_ax{3}=60*(time_ax{2} - time_ax{2}(1));
		time_ax{1}=(1/60)*(time_ax{2} - time_ax{2}(1));
	elseif ~isempty(iisec),
		time_unit=3;
		time_ax{3}=axvals{time_dim};
% 		time_ax{2}=(1/60)*(time_ax{3} - time_ax{3}(1));
% 		time_ax{1}=(1/3600)*(time_ax{3} - time_ax{3}(1));
		time_ax{2}=(1/60)*time_ax{3};
		time_ax{1}=(1/3600)*time_ax{3};
	end
	if time_unit==0,
		disp('Unable to determine if time axis is in minutes or hours');
	end
else
	time_dim=iiok(1);
end
V.iiij=set_iiij(axlabs,dlab);        % Set iiij flags for each dimension;
%
% if length(vdims)>DATA.ndim, vdims=vdims(1:DATA.ndim); end
if any(vdims>DATA.ndim), vdims=[]; end 
if length(unique(vdims))<length(vdims), vdims=[1:max(2,DATA.ndim)]; end
if isempty(vdims),
	ii_nt=find(iiok~=time_dim);
%    ndim_ok, iiok,time_dim,
	if ndim_ok==1,
		vdims=[ii1v(1) iiok(1) ii1v(2)];
	elseif ndim_ok==2,
        ii_td=find(time_dim==iiok);
        if isempty(ii_td), 
            vdims=[iiok,time_dim]; 
        else,
            if V.ii_img>0,
                vdims=[time_dim,iiok(ii_nt),ii1v(1)];
            else
                vdims=[iiok(ii_nt),time_dim,ii1v(1)];
            end
        end
%		vdims=[time_dim iiok(ii_nt(1)) ii1v(1)];
	elseif ndim_ok>=3,
%		vdims=[time_dim iiok(ii_nt(1:end))];
		if V.ii_img>0,
            vdims=[time_dim,iiok(ii_nt(1:end))];
		else
            vdims=[iiok(ii_nt(1)),time_dim,iiok(ii_nt(2:end))];
		end
	end
%	vdims,	keyboard
elseif length(vdims)<3,
%%	disp('USER ERROR: input vdims must have length 3'); return;
end
%
if any(V.ii_img==[-1,0]), 
%    jdim_ax=1 - V.ii_img; 
    jdim_ax=vdims(V.ii_img + 2);
    if V.iiq(1)==0, V.iiq=[1:dims(jdim_ax)]; end
    axind{jdim_ax}=unique(mod(V.iiq-1,dims(jdim_ax))+1);
end
iiok_not_used=[];
for jdim=1:DATA.ndim,
    if ~any(jdim==vdims) & DATA.dims(jdim)>1, iiok_not_used=[iiok_not_used, jdim]; end 
end
nok_not_used=length(iiok_not_used);
for jdim=1:length(vdims),
	if ~any(vdims(jdim)==iiok) & nok_not_used>0,
        vdim_old=vdims(jdim);
        vdims(jdim)=iiok_not_used(1);
        iiok_not_used=iiok(find(iiok~=vdims(1) & iiok~=vdims(2))); nok_not_used=length(iiok_not_used);
        for jdim2=jdim+1:length(vdims),
            if vdims(jdim2)==vdims(jdim), vdims(jdim2)=vdim_old; end
        end
	end    
end
% Increase length of vdims if more non-singletary dimensions available:
for jok=1:length(iiok),
    if ~any(iiok(jok)==vdims), vdims=[vdims, iiok(jok)]; end
end
nvdims=dims(vdims);
%
if prod(nvdims(1:2))<=10, V.ii_img=-1; end		% Make a line plot if 2 dims are ~1;
if nvdims(1)>100 & V.ii_img==-1, V.ii_img=1; disp('Set to image since too many line plots'); end
if nvdims(2)>100 & V.ii_img==0, V.ii_img=1; disp('Set to image since too many line plots'); end
%if V.ii_img<=0 & nvdims(2)<nvdims(1),
%	vdims=vdims([2 1 3]);
%end
%
if iinewfig, figure; end
%
if iich & instr,
	disp(['Place cursor over figure and enter key codes (space bar to type out key codes): ']);
end
%
ii_sc2=0;
iiclip=-1; iiv=[];
%
jfix=1; KV={1 1 1 1 1 1 1};	
button=-999; climx=[]; ii_ang=0;
iidB=-1;
if isfield(DATA,'iidB'), iidB=DATA.iidB; end
while ~isempty(button),
%%  disp(button),
	switch button,
    case {32},          % " " to type out instructions
        disp_instructions;
	case {28,52},       % Left-arrow or "4" to decrease jfix;
        if V.ii_img==3,
            jfix=jfix - prod(V.grid_dims);
        else
    		jfix=jfix - 1;
        end
	case {29,54},       % Right-arrow or "6" to increase jfix;
        if V.ii_img==3,
            jfix=jfix + prod(V.grid_dims);
        else
    		jfix=jfix + 1;
        end
	case {55,57},       % "7" or "9" to decrease or increase 2nd fixed dimension;
        if length(vdims)>=4,
            KV{vdims(4)}=KV{vdims(4)} + button-56;
        else
            disp(['Not enough dimensions to flip through 2nd fixed dim.']);
        end
	case {49,51},       % "1" or "3" to decrease or increase 3rd fixed dimension;
        if length(vdims)>=5,
            KV{vdims(5)}=KV{vdims(5)} + button-50;
        else
            disp(['Not enough dimensions to flip through 3rd fixed dim.']);
        end
	case {31,50},       % Down-arrow or "2" to enter vdims by hand;
		disp(axlabs);
		str=sprintf('%i,',dims);
		disp(['Dimensions = [',str(1:length(str)-1),']']);
		cmm=input(['Enter new y_dim,x_dim,fix_dim (current = [',int2str(vdims(1:3)),']): '],'s'); 
		cmm=str2num(cmm);
		if isempty(cmm), cmm=vdims; end
		if length(cmm)~=3 | any(cmm>7) | any(cmm<1) | any(round(cmm)~=cmm), 
			disp('Invalid dims');
			keyboard
		else
			vdims=cmm;
            if length(cmm)<ndim_ok,
                for jdim=1:ndim_ok
                    if ~any(vdims==iiok(jdim)), vdims=[vdims iiok(jdim)]; end
                end
            end
            jdim=vdims(1); axind{jdim}=[1:length(axvals{jdim})];
            jdim=vdims(2); axind{jdim}=[1:length(axvals{jdim})];
		end
	case {30,56},       % "8" or up-arrow to shift through dimensions;
		if ndim_ok<3, 
			disp('Fewer than three dimensions > 1.  Use / to switch hor/ver');
		else
            vdims=vdims([2:end,1]); disp(['vdims = ',int2str(vdims)]);	
            jdim=vdims(1); axind{jdim}=[1:length(axvals{jdim})];
            jdim=vdims(2); axind{jdim}=[1:length(axvals{jdim})];
		end
	case {42},       % "*" to shift through dimensions in opposite order;
		if ndim_ok<3, 
			disp('Fewer than three dimensions > 1.  Use / to switch hor/ver');
		else
            vdims=vdims([end,1:end-1]); disp(['vdims = ',int2str(vdims)]);	
            jdim=vdims(1); axind{jdim}=[1:length(axvals{jdim})];
            jdim=vdims(2); axind{jdim}=[1:length(axvals{jdim})];
		end
	case 53, % "5" to cycle through fixed dim.
		if ndim_ok<3, 
			disp('Fewer than three dimensions > 1.  Use / to switch hor/ver');
		else
            vdims(3:end)=vdims([4:length(vdims),3]);
			disp(['vdims = ',int2str(vdims)]);	
		end
	case 47, % "/" to switch x,y axes.
		vdims=vdims([2 1 3:end]);
    case 63,    % "?" to switch x,y axes and horizontal,vertical sizes;
		vdims=vdims([2 1 3:end]);
        V.size=V.size([2,1]);
	case 43, % "+" to increment forward on single line plot 
        jdim_ax=2 + V.ii_img;  if jdim_ax>=6, jdim_ax=jdim_ax-5; end
        if jdim_ax<1 | jdim_ax>2,
            disp('Line plot values not appropriate for images.  Select hor (L) or vert (V) line plot first ');
        else
            jdim=vdims(jdim_ax); nvals=length(axvals{jdim});
			axind{jdim}=mod(axind{jdim},nvals) + 1;
        end
	case 45, % "-" to increment backward on single line plot 
        jdim_ax=2 + V.ii_img;  if jdim_ax>=6, jdim_ax=jdim_ax-5; end
        if jdim_ax<1 | jdim_ax>2,
            disp('Line plot values not appropriate for images.  Select hor (L) or vert (V) line plot first ');
        else
            jdim=vdims(jdim_ax); nvals=length(axvals{jdim});
			axind{jdim}=mod(axind{jdim}-2,nvals) + 1;
        end
	case 61, % "=" to set single line plot indices
%		V.iiq=input('Enter index(es) for line plots ([] for all): ','s'); V.iiq=str2num(V.iiq);
        jdim_ax=2 + V.ii_img;  if jdim_ax>=6, jdim_ax=jdim_ax-5; end
        if jdim_ax<1 | jdim_ax>2,
            disp('Line plot values not appropriate for images.  Select hor (L) or vert (V) line plot first ');
        else
            axind=get_axis_indices(axlabs,axvals,axind,vdims,jdim_ax,1); 
        end
	case 95, % "_" to set single line plot index by its value
        jdim_ax=2 + V.ii_img;  if jdim_ax>=6, jdim_ax=jdim_ax-5; end
        if jdim_ax<1 | jdim_ax>2,
            disp('Line plot values not appropriate for images.  Select hor (L) or vert (V) line plot first ');
        else
            axind=get_axis_indices(axlabs,axvals,axind,vdims,jdim_ax,0); 
        end
%		iiv=input('Enter axis value(s) for line plots ([] for all):','s'); iiv=str2num(iiv);
%        if isempty(iiv), V.iiq=[]; end
	case 122, % "z" to set fixed dimension index by index
        disp(['Fixed dim = ',int2str(vdims(3)),'; Dim Label = ',axlabs{vdims(3)}, ...
                '; Limits = ',num2str(axvals{vdims(3)}([1,end])),' # vals = ',int2str(dims(vdims(3)))]);
		jfix=input('Enter dimension index to image ([] for all): ','s'); jfix=str2num(jfix);
	case 90, % "Z" to set fixed dimension index by value;
        disp(['Fixed dim = ',int2str(vdims(3)),'; Dim Label = ',axlabs{vdims(3)}, ...
                '; Limits = ',num2str(axvals{vdims(3)}([1,end])),' # vals = ',int2str(dims(vdims(3)))]);
		zval=str2num(input('Enter dimension value to image ([] for all): ','s')); 
        [dum,jfix]=min(abs(axvals{vdims(3)} - zval));
	case 99, % "c" for clim
		disp(['Min, max of entire data set = ',num2str([dmin,dmax])]);
      	cmm=input(['Enter [cmin,cmax] (or cmax-cmin) (currently: ',num2str(V.clim),'): '],'s');
      	cmm=str2num(cmm);
        if length(cmm)==1, 
            if cmm>0, 
                cmm=[dmax-cmm,dmax];    % Single pos # mean dynamic range from dmax;
            else
                cmm=[dmin,dmin-cmm];       % Single negative number means to add up from dmin;
            end
        end
		if isempty(cmm), cmm=[dmin,dmax]; end
		if length(cmm)~=2 | cmm(1)>=cmm(2), disp('Invalid clims.'); else V.clim=cmm; end
	case 115, % "s" for size
        disp(['Current plot size = ',num2str(V.size)]);
		cmm=input('Enter plot size [width,height] in inches: ','s'); cmm=str2num(cmm);
        if isempty(cmm), cmm=V.size; end
        if length(cmm)~=2, 
            disp('Illegal plot size: should be [w,h]. ');
        else
    		V.size=cmm; V.unit='in'; 
        end
	case 109, % "m" for map
		V.cmap=input('Enter color map (no quotes) (jet,1-gray,etc): ');
		if ~isempty(V.cmap), colormap(V.cmap); end
	case 98, % "b" to toggle colorbar
		V.iibar=1-V.iibar;
%	case 108, % "l" to change axis labels
%		cmm=input('Enter row (y) axis label (<cr> to keep same): ','s');
%		if ~isempty(cmm), V.ylab=cmm; end
%		cmm=input('Enter col (x) axis label (<cr> to keep same): ','s');
%		if ~isempty(cmm), V.xlab=cmm; end
%		cmm=input('Enter data axis label (<cr> to keep same): ','s');
%		if ~isempty(cmm), dlab=cmm; end
	case 104, % "h" to set line colors and styles
        disp('Current line colors: '); disp(COL);
		cmm=input(['Enter line colors (no quotes): (<cr> to keep same): '],'s');
		if ~isempty(cmm),
            COL=cell(1,length(cmm));
            for j=1:length(cmm), COL{j}=cmm(j); end;
        end
        disp('Current line styles: '); disp(STY);
		cmm=input(['Enter line styles (no quotes): (_ or d for dash, <cr> to keep same): ']);
		if ~isempty(cmm),
%            if ~iscell(cmm), cmm=cellstr(cmm); end; 
            STY=cmm; 
        end
	case 72, % to set line symbols, symbol sizes, and line styles:
%         for j=1:length(cmm), COL{j}=cmm(j); end
        disp('Current symbols: '); disp(SYM);
		cmm=input(['Enter symbols (AS CELL ARRAY: {''o''} or {''none''}, e.g.): (<cr> to keep same): ']);
		if ~isempty(cmm), if ~iscell(cmm), SYM=cellstr(cmm); end; SYM=cmm; end
        disp('Current dot sizes: '); disp(DOT);
		cmm=input(['Enter dot sizes (AS CELL ARRAY: {5} or {5,8}, e.g.): (<cr> to keep same): ']);
		if ~isempty(cmm), if ~iscell(cmm), cmm=cellstr(cmm); end; DOT=cmm; end
    case 89, %"Y" to toggle between symbols, symbols&lines, and lines:
        ii_sym=rem(ii_sym+1,5);
        switch ii_sym
            case 0, SYM={'none'}; STY={'-'};
            case 1, SYM={'o'}; STY={'none'}; DOT={5};
            case 2, SYM={'o'}; STY={'-'}; DOT={5};
            case 3, SYM={'o'}; STY={'none'}; DOT={8};
            case 4, SYM={'o'}; STY={'-'}; DOT={8};
        end
	case 105, % "i" to toggle axis ij/xy
        if any(V.ii_img==[-1,0]),
		    V.iiij{8}=1-V.iiij{8};
        else
		    V.iiij{vdims(1)}=1-V.iiij{vdims(1)};
        end
	case 112, % "p" to change point size
		V.ptsize=input('Enter point size: ');
	case 103, % "g" to toggle grid on and off
		if V.iigrid==0, V.iigrid=1; else, V.iigrid=-V.iigrid; end
	case 76, % "L" for single line plot
        if any(V.ii_img==[-1,0]), 
            disp('Already a line plot: choose image first, position cursor, then hit "L"');
        else
			V.ii_img=-1; %iiv=ypt;
            jdim_ax=vdims(1);
            [dum,axind{jdim_ax}]=min(abs(ypt-axvals{jdim_ax}(axind{jdim_ax})));
        end
	case 86, % "V" for single line plot
        if any(V.ii_img==[-1,0]), 
            disp('Already a line plot: choose image first, position cursor, then hit "V"');
        else
			V.ii_img=0; %iiv=xpt;
            jdim_ax=vdims(2);
            [dum,axind{jdim_ax}]=min(abs(xpt-axvals{jdim_ax}(axind{jdim_ax})));            
        end
	case {73,67,71}, % "I" for image plot, "C" for contour plot, "G" for grid of images;
        jdim_ax=2 + V.ii_img;
        if jdim_ax==1 | jdim_ax==2, 
            jdim=vdims(jdim_ax); axind{jdim}=[1:length(axvals{jdim})];
        end
        clf;
        switch button
        case 73, V.ii_img=1;
        case 67, V.ii_img=2;
        case 71,        % "G" to plot a grid of images, change [nrow,ncol] of grid, or change ii_row_major;
            if V.ii_img==3 | isempty(MG),
			    cmm=input(['Enter nrow,ncol if image grid, 0 to toggle ii_row_major, 1 for auto, ', ...
                    'or <CR> to abort: '],'s'); 
                cmm=str2num(cmm); 
                if length(cmm)==1,
                    switch cmm
                    case 0,
                        V.ii_row_major=1 - V.ii_row_major;
                    case 1,
                        ngrid=dims(vdims(3)); xfac1=sqrt(ngrid);
                        V.grid_dims=[ceil(xfac1),floor(xfac1)];
                        if prod(V.grid_dims)<ngrid, V.grid_dims(2)=V.grid_dims(2)+1; end
                        disp(['V.grid_dims set to ',int2str(V.grid_dims)]);
                        V.size=[8,6];
                    end
                elseif length(cmm)~=2, 
                    disp('Must enter 2 numbers for nrow,ncol'); 
                elseif prod(cmm)<1 | prod(cmm)>75G | ~all(round(cmm)==cmm),
                    disp('# images too small, too large (edit view5 to allow > 50 images), or not integers');
                else
                    V.grid_dims=cmm;
                end
            end
            V.ii_img=3;
        end
        V.iigrid=0;     % Auto set to no grid when image first chosen;
%	case 83, % "S" for shaded line plot
%		V.ii_img=3;
%	case 80, % "P" to pause so that figure may be copied
%		disp('Pausing so that figure may be copied (only needed on Mac).  Press return to continue.');
%		pause;
    case 80,
        V.ii_img=4;
    case 81,
        V.ii_img=5;
%	case 101, % "e" to toggle cliplines call (makes copied plot's lines clipped)
%		iiclip=-iiclip,
	case 66, % "B" to toggle bold lettering 
		V.iibold=1-V.iibold;
	case 119, % "s" for size
		cmm=input(['Enter line width in points: (current value = ', ...
			num2str(V.lwidth),'): ']);
		if isempty(cmm), cmm=1.5; end
		V.lwidth=cmm;
    case 1,     % Left mouse button to zoom in on section of image
        disp('Click on opposite corner of region to zoom in on (<CR> to abort):');
        [xpt2,ypt2,button2]=ginput(1);
        if isempty(button2), disp('Aborting image zoom-in'); return; end;
        axlims{vdims(1)}=[min(ypt,ypt2),max(ypt,ypt2)];
        axlims{vdims(2)}=[min(xpt,xpt2),max(xpt,xpt2)];
		axind{vdims(2)}=find(axvals{vdims(2)}>=axlims{vdims(2)}(1) & axvals{vdims(2)}<=axlims{vdims(2)}(2));
		axind{vdims(1)}=find(axvals{vdims(1)}>=axlims{vdims(1)}(1) & axvals{vdims(1)}<=axlims{vdims(1)}(2));
    case 3,     % Right mouse button to zoom out
% Don't line-plot all dimensions (horizontal or vertical):
        if V.ii_img ~= -1, axlims{vdims(1)}=axlims0{vdims(1)}; axind{vdims(1)}=[1:dims(vdims(1))]; end
        if V.ii_img ~= 0, axlims{vdims(2)}=axlims0{vdims(2)}; axind{vdims(2)}=[1:dims(vdims(2))]; end
    case 120, % "x" to change x-axis limits
		xlims0=axlims0{vdims(2)}; xlims=axlims{vdims(2)};
		disp(['Data horizontal axis values   : ',num2str(xlims0)]);
		disp(['Current horizontal axis values: ',num2str(xlims)]);
		cmm=input('Enter new horizontal axis limits xmin,xmax (<CR>=keep same;0=min,max): ','s');
		cmm=str2num(cmm);
		if length(cmm)==2,
			axlims{vdims(2)}=cmm;
        elseif length(cmm)==1,
            axlims{vdims(2)}=xlims0;
        else
            disp(['Keeping same']);
		end
		xvals=axvals{vdims(2)};
		axind{vdims(2)}=find(xvals>=axlims{vdims(2)}(1) & xvals<=axlims{vdims(2)}(2));
	case 121, % "y" to change y-axis limits
		ylims0=axlims0{vdims(1)}; ylims=axlims{vdims(1)}; 
		disp(['Data vertical axis values   : ',num2str(ylims0)]);
		disp(['Current vertical axis values: ',num2str(ylims)]);
		cmm=input('Enter new vertical axis limits ymin,ymax: (<CR>=keep same;0=min,max):','s'); 
        cmm=str2num(cmm);
		if length(cmm)==2,
			axlims{vdims(1)}=cmm;
        elseif length(cmm)==1,
            axlims{vdims(1)}=ylims0;
        else
            disp('Keeping same'); 
		end
		yvals=axvals{vdims(1)};
		axind{vdims(1)}=find(yvals>=axlims{vdims(1)}(1) & yvals<=axlims{vdims(1)}(2));
	case 116,
		if time_unit==0, 
			disp('No Time label found in data or unable to figure out h/m/s'); axlabs; return; 
		end
		time_unit=mod(time_unit,3) + 1;
		axlabs{time_dim}=time_lab{time_unit}; axvals{time_dim}=time_ax{time_unit};
	case 86,
		V.iivg=1-V.iivg;
		if V.iivg,
			V.fname='Arial'; V.ptsize=14; V.iibold=1;
		else
			V.fname='Times'; V.ptsize=11; V.iibold=0;
		end
	case 70,	% "F" to spawn new figure;
		zoom on; figure; zoom on;
	case {100,68}	% Lower/upper case d to convert to dB using 10*log10 or 20*log10:
		if button==100, fac=10; else, fac=20; end
		if iidB==0,
			data=fac*log10(abs(data));
			iidB=1; dmin=fac*log10(abs(dmin)); dmax=fac*log10(abs(dmax));
            dlab=dlab_check(1,dlab);
			V.clim=fac*log10(max(V.clim,1e-30));
		else
			data=10.^(data/fac);
			iidB=0; dmin=10.^(dmin/fac); dmax=10.^(dmax/fac); dlab=dlab_check(2,dlab); 
			V.clim=10.^(V.clim/fac);
        end
    case {97}
        if DATA.iidB~=-1, 
            disp('DATA.iidB must be -1, indicating complex numbers, to toggle between dB/angle.')    
        elseif ii_ang==1,
            data=dB(DATA.data); ii_ang=0; if ~isempty(climx), V.clim=climx; end
        else,
            data=angle(DATA.data)/pi; ii_ang=1; climx=V.clim; V.clim=[-1,1];
        end
    case {65},      % "A" to toggle between scales and scales2;
        if ~isfield(DATA,'scales2') | ~isfield(DATA,'labels2'),
            disp('Given DATA structure does not have scales2 and/or labels2 fields!!');
        else
            if ii_sc2,
        		axvals=DATA.scales; axlabs=DATA.labels;
            else
        		axvals=DATA.scales2; axlabs=DATA.labels2;
            end
			for jdim=1:DATA.ndim, 
                axlims0{jdim}=[min(axvals{jdim}), max(axvals{jdim})];
			end
			axlims=axlims0;
            V.iiij=set_iiij(axlabs,dlab);            % Reset iiij flags for each dimension;
            ii_sc2=1-ii_sc2;
        end
    case {117},     % "u" to unwrap
		disp(axlabs);
		str=sprintf('%i,',dims);
		disp(['Dimensions = [',str(1:length(str)-1),']']);
		cmm=input(['Enter dimension # over which to unwrap and half-cycle wrap tolerance: '],'s'); 
		cmm=str2num(cmm); iiok=1;
        if isempty(cmm), disp('No entry - ignoring command'); iiok=0; end
        if round(cmm(1))~=cmm(1) | cmm(1)<1 | cmm(1)>DATA.ndim, 
            disp('Dimension must be integer from 1 to ndim'); iiok=1; 
        end
        if length(cmm)==1, cmm(2)=pi; end
        if iiok, data=unwrap(DATA.data,cmm(2),cmm(1)); end
    case {108},     % "l" to label and mark peaks (by calling peak_label)
        peak_label_grid; break; return;
    case {84},      % "T" to toggle thresholding
        if ~iithresh,
            cmm=input(['Enter threshold (clims = ',num2str(V.clim),'): '],'s');
            thresh=str2num(cmm); iithresh=1;
        else
            iithresh=0;
        end
    case 77,        % "M" to make an AVI movie;
        jdim=vdims(3); nframe=dims(jdim); lims=[axvals{jdim}(1),axvals{jdim}(end)];
		set(gcf,'DoubleBuffer','on');
		set(gca,'NextPlot','replace','Visible','off');
        disp(' ');
        disp(['AVI movie over dimensions label = ',axlabs{jdim},'; min,max,# values = ', ...
                num2str([lims(1),lims(2),nframe])]);
        inp=str2num(input('    Enter # FPS, ii_ax_only, ii_rev, ii_suf: ','s'));
        if length(inp)<1, disp('At least FPS must be entered - start again if desired'); break; end
        if length(inp)<2, inp(2)=1; end
        if length(inp)<3, inp(3)=0; end
        if length(inp)<4, inp(4)=0; end
        fps=inp(1); ii_ax_only=inp(2); ii_rev=inp(3); ii_suf=inp(4); suf=[];
        if ii_suf, suf=input('    Enter suffix to add to DATA.title for AVI file name root: ','s'); end
        if ii_rev, iiframe=[nframe:-1:1]; else, iiframe=[1:nframe]; end
        avi_file=[DATA.title,suf,'.avi'];
		mov = avifile(avi_file,'fps',fps,'Compression','None');
        disp(['    Movie will have ',int2str(nframe),' frames ...']);
		for jf=1:nframe,
			KV{jdim}=iiframe(jf);
			if vdims(1)<vdims(2),
				datax=reshape(data(KV{1},KV{2},KV{3},KV{4},KV{5},KV{6},KV{7}),nytake,nxtake);
			else
				datax=reshape(data(KV{1},KV{2},KV{3},KV{4},KV{5},KV{6},KV{7}),nxtake,nytake).';
			end		
			imagesc(xax,yax,datax,V.clim); xlabel(xlab); ylabel(ylab);
			colormap(V.cmap);
%			plot_size(gca,V.unit,V.size(1),V.size(2));
            if any(V.ii_img==[-1]), iiij0=V.iiij{8}; else, iiij0=V.iiij{vdims(1)}; end
            tlab=[axlabs{jdim},' = ',num2str(axvals{jdim}(KV{jdim}),3)];
            set_plot_look(tlab,ylab,iiij0,V.iigrid,ident,dlab);
            if ii_ax_only,
                F=getframe(gca);
            else
    			F = getframe(gcf);
            end
			mov = addframe(mov,F);
		end
		mov = close(mov);
        disp(['    AVI output file = ',avi_file]);
        disp(['    Insert into PPT file with Insert => Movies => File, or Double Click on .avi file to play in Windows Media Player']);
    case 38,        % "&" to set iilog;
        str=sprintf('    %s   ',DATA.labels{1:DATA.ndim}); disp(['Axis labels: ',str]);
        disp(['Current iilog = ',int2str(V.iilog)]);
        V.iilog=str2num(input(['Enter iilog for each dimension: '],'s'));
    case 91,        % "[" to toggle axis('tight');
        ii_tight=1-ii_tight;
	case -999,
	otherwise
		disp(['Unknown button pushed = ',int2str(button)]);
	end
%
%%    iiwrap=find(jfix>dims(vdims(3))); jfix(iiwrap)=1;
%%    iiwrap=find(jfix<1); jfix(iiwrap)=dims(vdims(3));
    jfix=mod(jfix-1,dims(vdims(3))) + 1;
%%    if jfix>dims(vdims(3)), jfix=1; elseif jfix<1, jfix=dims(vdims(3)); end
%
% Guard against not plotting anything and getting nyax=0 or nxax=0:
%    if isempty(axind{vdims(1)}), axind{vdims(1)}=[1:dims(vdims(1))]; end
%    if isempty(axind{vdims(2)}), axind{vdims(2)}=[1:dims(vdims(2))]; end
	KV{vdims(1)}=axind{vdims(1)}; KV{vdims(2)}=axind{vdims(2)}; KV{vdims(3)}=jfix(1);
    for jdim=4:length(vdims),
        jd=vdims(jdim);
        if length(KV{jd})>1, KV{jd}=1; end
%        disp([jd,KV{jd},dims(jd)])
        if KV{jd}>dims(jd), KV{jd}=1; end
        if KV{jd}<1, KV{jd}=dims(jd); end
    end
	nytake=length(axind{vdims(1)}); nxtake=length(axind{vdims(2)});
	if vdims(1)<vdims(2),
		datax=reshape(data(KV{1},KV{2},KV{3},KV{4},KV{5},KV{6},KV{7}),nytake,nxtake);
	else
% Must transpose:
		datax=reshape(data(KV{1},KV{2},KV{3},KV{4},KV{5},KV{6},KV{7}),nxtake,nytake).';
	end		
	yax=axvals{vdims(1)}(KV{vdims(1)});
	xax=axvals{vdims(2)}(KV{vdims(2)});
	nyax=length(yax); nxax=length(xax);
% % 	ylab=axlabs{vdims(1)}; xlab=axlabs{vdims(2)};
    ylab=label_check(axlabs{vdims(1)},axind{vdims(1)}); 
    xlab=label_check(axlabs{vdims(2)},axind{vdims(2)});
%     if V.ii_img==-1, jd=1; elseif V.ii_img==0, jd=2, else, jd=3; end
    if vdims(3)==jdim_dlab,
        dlab=label_check(dlabs,KV{vdims(3)}); %%disp(['xlab,ylab,dlab = ',xlab,' ',ylab,' ',dlab]);
    else
        dlab=label_check(dlabs,[]);
    end
    iilog=V.iilog([vdims(1) vdims(2) 6]);
% Threshold if desired:
    if iithresh, ii=find(datax<thresh); datax(ii)=V.clim(1); end
% Construct title:
    tlab=[]; fmt='%0.5g';
    if ~any(V.ii_img==[3,4,5]),
        for jd=length(vdims):-1:3,
            jdim=vdims(jd); 
            if jdim<=DATA.ndim, 
                if ~isempty(tlab), tlab=[tlab,'; ']; end
                tlab=tlab_check(tlab,axlabs{jdim},axvals{jdim}(KV{jdim}),fmt);
%                 tlab=[tlab,axlabs{jdim},' = ',sprintf('%0.5g',axvals{jdim}(KV{jdim}))];
            end
        end
    else
        for jd=length(vdims):-1:4,
            jdim=vdims(jd); if ~isempty(tlab), tlab=[tlab,'; ']; end
            tlab=tlab_check(tlab,axlabs{jdim},axvals{jdim}(KV{jdim}),fmt);
%            tlab=[tlab,axlabs{jdim},' = ',sprintf('%g',axvals{jdim}(KV{jdim}))];
        end
        jdim=vdims(3); if ~isempty(tlab), tlab=[tlab,'; ']; end
        ndim3=dims(jdim); nplot=min(prod(V.grid_dims),ndim3); 
        jfix2=mod(jfix + nplot-2,ndim3)+1;
        str=sprintf('[%1.2f,%1.2f]',axvals{jdim}([jfix,jfix2]));
%         tlab=[tlab,axlabs{jdim},' = ',str];
        tlab=tlab_check(tlab,axlabs{jdim},str,fmt);
    end
    if ndim_ok<=2, tlab=[]; end
%
    jdim_ax=V.ii_img + 2;  if jdim_ax>=6, jdim_ax=jdim_ax-5; end
    if jdim_ax==1 | jdim_ax==2,
        tlab=make_title(axlabs,axvals,axind,vdims,jdim_ax,tlab,fmt);
    end
%
    if isempty(V.clim),
		V.clim=dbdyn_calc2([],[],datax);
	else
		V.clim=dbdyn_calc2(V.clim(1),V.clim(2),datax);
	end
%
%	if iixmm==1, xmin=xmm(1); xmax=xmm(2); end
%	if iiymm==1, 
%		if V.ii_img>0, ymin=ymm(1); 
%			ymax=ymm(2);
%		else
%			ymin=ymm(1); ymax=ymm(2);	
%		end
%	end
%
	if V.ii_img==1,
        if ii_tight, V.clim=[min(datax(:)),max(datax(:))]; end
		imagesc(xax,yax,datax,V.clim); xlabel(xlab); ylabel(ylab);
		colormap(V.cmap);
    elseif any(V.ii_img==[3,4,5]),
 % Grid of images or line plots:
        if V.ii_img==4, ylab=dlab; elseif V.ii_img==5, xlab=dlab; end
		if isempty(MG) | ~all(V.size==MG.size) | ~all(V.grid_dims==MG.dims),
			MG=grid_axes(V.size,V.grid_dims,[],[],[],xlab,ylab,dlab); 
		end
        ndim3=dims(vdims(3));
		clf; MG.handles=zeros(1,MG.nplot); jplot=0; jfix0=jfix-1;
        for jplot=1:min(MG.nplot,ndim3),
            if V.ii_row_major,
                jcol=mod(jplot-1,MG.dims(2)) + 1; jrow=floor((jplot-1)/MG.dims(2)) + 1;
            else
                jrow=mod(jplot-1,MG.dims(1)) + 1; jcol=floor((jplot-1)/MG.dims(1)) + 1;
            end
            MG.handles(jplot)=axes('Units','in','Position',MG.ax_pos(:,jrow,jcol));
            jfix0=mod(jfix0,ndim3) + 1; KV{vdims(3)}=jfix0;
			if vdims(1)<vdims(2),
				datax=reshape(data(KV{1},KV{2},KV{3},KV{4},KV{5},KV{6},KV{7}),nytake,nxtake);
			else
				datax=reshape(data(KV{1},KV{2},KV{3},KV{4},KV{5},KV{6},KV{7}),nxtake,nytake).';
			end
            if V.ii_img==3, 
                imagesc(xax,yax,datax,V.clim);
            elseif V.ii_img==4, 
				xx=[min(xax),max(xax)]; if xx(1)==xx(end) & length(xx)>1, xx(end)=xx(1) + 1; end
        		plotll(xax,datax,iilog([2 3]),SYM,COL,DOT,STY,0); 
		        axis([xx V.clim]); if ii_tight, axis('tight'); end
                if isfield(DATA,'back_col'), set(gca,'Color',DATA.back_col); hold on; end
            elseif V.ii_img==5, 
				yy=[min(yax),max(yax)]; if yy(1)==yy(end) & length(yy)>1, yy(end)=yy(1) + 1; end
                plotll(yax,datax,iilog([3 1]),SYM,COL,DOT,STY,1); 
				axis([V.clim yy]); if ii_tight, axis('tight'); end
                if isfield(DATA,'back_col'), set(gca,'Color',DATA.back_col); hold on; end
            end
            iix_lab=(jrow==MG.dims(1) & jcol==1); iiy_lab=iix_lab;
            if MG.iixlab(jrow,jcol), xlabel(xlab); end; 
            if MG.iixtick(jrow,jcol)==0, 
                set(MG.handles(jplot),'XtickLabel',[]);
            elseif jcol>1,
% % %                 xticks=get(gca,'Xtick'); xticks=xticks(2:end); set(gca,'Xtick',xticks);
            end
            if MG.iiylab(jrow,jcol), ylabel(ylab); end
            if MG.iiytick(jrow,jcol)==0, set(MG.handles(jplot),'YtickLabel',[]); end
            if MG.iitlab(jrow,jcol), mytitle(tlab); end
            if V.ii_img==3 & MG.iicbar(jrow,jcol), 
                hc=mycolorbar2('vert',0,dlab);
                plot_set3(hc,V.lwidth,V.fname,V.ptsize,V.iibold);
                if MG.iiclab(jrow,jcol)==0, set(get(hc,'Ylabel'),'String',[]); end
                if MG.iictick(jrow,jcol)==0, set(hc,'YTickLabel',[]); end
            end
            if V.ii_img==3, colormap(V.cmap); end
            if jrow==1 & jcol==MG.dims(2), ident2=ident; else, ident2=[]; end
            set_plot_look([],ylab,V.iiij{vdims(1)},V.iigrid,ident2,dlab);
            pos=get(gcf,'Position');
			width=V.size(1); height=V.size(2);
			if width<0, 
                ax=axis; iiprop=1; w=-width*abs(ax(2)-ax(1)); 
                if w<12 & w>.2, width=w; else, disp(['Bad proportional dimension calc: width set to 5']); width=5; end
			end
			if height<0, 
                ax=axis; iiprop=1; h=-height*abs(ax(4)-ax(3)); 
                if h<9 & h>.2, height=h; else, disp(['Bad proportional dimension calc: height set to 5']); height=3; end
			end
			fig_size=[width+2.25 height+1.85];
			max_size=[12.5,9];		% Max size of screen;
			hoff=min(max_size(1) - fig_size(1),pos(1));
			voff=min(max_size(2) - fig_size(2),pos(2));
			set(gcf,'Units','Inches','Position',[hoff voff fig_size]);
            h=text_place(1,1,num2str(axvals{vdims(3)}(jfix0),4));
        end
	elseif V.ii_img==2,
		cinc=round(V.clim(2)-V.clim(1))/10;
		cvals=[V.clim(1):cinc:V.clim(2)];
		[c,h]=contour(xax,yax,datax,cvals); xlabel(xlab); ylabel(ylab);
        if isfield(DATA,'back_col'), set(gca,'Color',DATA.back_col); hold on; end
		clabel(c,h); grid on;
		axis('ij');
	elseif V.ii_img==-1,
% 		xx=[min(xax),max(xax)]; 
        xx=axlims{vdims(2)}; if xx(1)==xx(end) & length(xx)>1, xx(end)=xx(1) + 1; end
		plotll(xax,datax.',iilog([2 3]),SYM,COL,DOT,STY,0);
        dlab=label_check(dlabs,KV{vdims(1)});
        xlabel(xlab); ylabel(dlab); grid on;
		axis([xx V.clim]); if ii_tight, axis('tight'); end
        if isfield(DATA,'back_col'), set(gca,'Color',DATA.back_col); end
	elseif V.ii_img==0,
% 		yy=[min(yax),max(yax)]; 
        yy=axlims{vdims(1)}; if yy(1)==yy(end) & length(yy)>1, yy(end)=yy(1) + 1; end
		plotll(yax,datax,iilog([3 1]),SYM,COL,DOT,STY,1); 
        dlab=label_check(dlabs,KV{vdims(2)});
		xlabel(dlab); ylabel(ylab); grid on;
		axis([V.clim yy]); if ii_tight, axis('tight'); end
        if isfield(DATA,'back_col'), set(gca,'Color',DATA.back_col); hold on; end
	end
%    
    if ~any(V.ii_img==[3,4,5]), 
		plot_size(gca,V.unit,V.size(1),V.size(2),[],[],iifig_size,0);
        if any(V.ii_img==[-1]), iiij0=V.iiij{8}; else, iiij0=V.iiij{vdims(1)}; end
        set_plot_look(tlab,ylab,iiij0,V.iigrid,ident,dlab);
    end
%
% Break if no changes desired:
	if ~iich, break; end
%%keyboard
% Otherwise get input key:
	[xpt,ypt,button]=ginput(1);
         
end
zoom on;
DATA.clim=V.clim;
DATA.vdims=vdims; V.vdims=vdims;
if nargout>1, Vx.vdims=vdims; Vx.ii_img=V.ii_img; Vx.iiq=V.iiq; Vx.KV=KV; end
% Save plotting defaults in file view_def
expr=['save view_def V']; eval(expr);
%
%%%
%
function set_plot_look(tlab,ylab,iiij,iigrid,ident,dlab)
%
view_global
% If time is not on vertical axis, use axis('xy'):
if any(V.ii_img==[1,2,3]),
	if ~strncmp(ylab,'Time',4) & ~strncmp(ylab,'Sequ',4), axis('xy'); end
end
%
if iiij==1, axis('ij'); else, axis('xy'); end
if iigrid==1; grid on; elseif iigrid==-1; grid off; end
%%if iiclip==1; clipline(gca); end
%
if ~isempty(tlab), mytitle([tlab]); end
plot_set3(gca,V.lwidth,V.fname,V.ptsize,V.iibold);
if (V.ii_img==1 | V.ii_img==2) & V.iibar==1, hc=mycolorbar2('vert',0,dlab); end;
if ~isempty(ident) & V.ident, h=text_place(2,2,ident); end
%
%%%
%
function plotll(xax,datax,iilog,sym,col,dot,sty,iiflip); 
%
[nr,nc]=size(datax);
nx=length(xax);
if nr~=nx & nc==nx, 
	datax=datax.'; 
	[nr,nc]=size(datax);
end
if ischar(col), col2=col; ncol=length(col2); col=cell(1,ncol); for j=1:ncol, col{j}=col2(j); end; end
if ischar(sty), sty2=sty; nsty=length(sty2); sty=cell(1,nsty); for j=1:nsty, sty{j}=sty2(j); end; end
if ischar(sym), sym2=sym; nsym=length(sym2); sym=cell(1,nsym); for j=1:nsym, sym{j}=sym2(j); end; end
%
nlog=iilog(1)+2*iilog(2);
ncol=length(col); nsty=length(sty); nsym=length(sym); ndot=length(dot);
for jplot=nc:-1:1,
	jcol=mod(jplot-1,ncol) + 1; jsty=mod(jplot-1,nsty) + 1;
    jsym=mod(jplot-1,nsym) + 1; jdot=mod(jplot-1,ndot) + 1;
    symbol=sym{jsym}; if ~isempty(findstr(symbol(1),'n ')), symbol='none'; end
    style=sty{jsty}; 
    if any(style(1)==['d_']), style='--'; end
    if iiflip==0,
        plot_cfill(xax,datax(:,jplot),symbol,col{jcol},dot{jdot},style,1.5,nlog);
    else
        plot_cfill(datax(:,jplot),xax,symbol,col{jcol},dot{jdot},style,1.5,nlog);
    end
    hold on;
end
hold off;
return
%
if iilog(1)==0 & iilog(2)==0,
	for jplot=nc:-1:1,
		jcol=mod(jplot-1,ncol) + 1;
		plot(xax,datax(:,jplot),col(jcol)); hold on;
	end
elseif iilog(1)==1 & iilog(2)==0,
	for jplot=nc:-1:1,
		jcol=mod(jplot-1,ncol) + 1;
		semilogx(xax,datax(:,jplot),col(jcol))
	end
elseif iilog(1)==0 & iilog(2)==1,
	for jplot=nc:-1:1,
		jcol=mod(jplot-1,ncol) + 1;
		semilogy(xax,datax(:,jplot),col(jcol))
	end
elseif iilog(1)==1 & iilog(2)==1,
	for jplot=nc:-1:1,
		jcol=mod(jplot-1,ncol) + 1;
		loglog(xax,datax(:,jplot),col(jcol))
	end
end
%
%%%
%
function MG=grid_axes(t_size,grid_dims,ax_buf,ax_betw,dxdy_eq,xlab,ylab,clab)
%
if nargin<3 | isempty(ax_buf), ax_buf=1; end; 
if nargin<4 | isempty(ax_betw), ax_betw=0.14; end;
if nargin<5, dxdy_eq=[]; end
if nargin<6, xlab=' '; end
if nargin<7, ylab=' '; end
if nargin<8, clab=' '; end
%
width=t_size(1); height=t_size(2);
if width<0, 
    ax=axis; iiprop=1; w=-width*abs(ax(2)-ax(1)); 
    if w<12 & w>.2, width=w; else, disp(['Bad proportional dimension calc: width set to 5']); width=5; end
end
if height<0, 
    ax=axis; iiprop=1; h=-height*abs(ax(4)-ax(3)); 
    if h<9 & h>.2, height=h; else, disp(['Bad proportional dimension calc: height set to 5']); height=3; end
end
%
MG.size=[width,height];
MG.hor_len=(width-(grid_dims(2)-1)*ax_betw)/grid_dims(2);
MG.ver_len=(height-(grid_dims(1)-1)*ax_betw)/grid_dims(1);
MG.dims=grid_dims; MG.ax_betw=ax_betw; MG.ax_buf=ax_buf; MG.dxdy_eq=dxdy_eq;
if ~isempty(dxdy_eq),
	outsize=ax_eq_size([MG.hor_len MG.ver_len],dxdy_eq(1),dxdy_eq(2));
	MG.hor_len=outsize(1); MG.ver_len=outsize(2);
end
%
MG.ax_pos=zeros(4,grid_dims(1),grid_dims(2));
MG.iixlab=zeros(grid_dims);
MG.iiylab=zeros(grid_dims); 
MG.iixtick=zeros(grid_dims);
MG.iiytick=zeros(grid_dims);
MG.iicbar=zeros(grid_dims);
MG.iiclab=zeros(grid_dims);
MG.iictick=zeros(grid_dims);
MG.iitlab=zeros(grid_dims); 
jrmid=round((MG.dims(1)+1)/2); jcmid=round((MG.dims(2)+1)/2);
%
% Factor to see if labels fit on each axes:
inches_per_letter=1.5/18;       % About 18 characters fit in 1.5 inches - adjust if desired;
horfac=length(xlab)*inches_per_letter;       
verfac=length(ylab)*inches_per_letter;
barfac=length(clab)*inches_per_letter;
for jrow=1:MG.dims(1),
    for jcol=1:MG.dims(2),
		hstart=ax_buf + (jcol-1)*(MG.hor_len+ax_betw);
		vstart=ax_buf + height - (jrow*(MG.ver_len+ax_betw));
		MG.ax_pos(:,jrow,jcol)=[hstart,vstart,MG.hor_len,MG.ver_len]';
        if jrow==MG.dims(1),
            if MG.hor_len >=horfac | jcol==jcmid; MG.iixlab(jrow,jcol)=1; end
            if MG.hor_len >=horfac | jcol==jcmid; MG.iixtick(jrow,jcol)=1; end
        end
        if jcol==1,
            if MG.ver_len >=verfac | jrow==jrmid; MG.iiylab(jrow,jcol)=1; end
            if MG.ver_len >=verfac | jrow==jrmid; MG.iiytick(jrow,jcol)=1; end
        end
        if jcol==MG.dims(2),
            MG.iicbar(jrow,jcol)=1;
            if MG.ver_len >=barfac | jrow==jrmid, MG.iiclab(jrow,jcol)=1; end
            if MG.ver_len >=barfac | jrow==jrmid, MG.iictick(jrow,jcol)=1; end
        end
        if jrow==1 & jcol==round((MG.dims(2)+1)/2), MG.iitlab(jrow,jcol)=1; end
    end
end
MG.nplot=MG.dims(1)*MG.dims(2);
%
%%%
%
function axind=get_axis_indices(axlabs,axvals,axind,vdims,jdim_ax,ii_indx)
%
jdim=vdims(jdim_ax); nvals=length(axvals{jdim});
if ischar(axlabs{jdim}),
    disp(['Axis label = ',axlabs{jdim}]);
else
    disp(['Axis label = ',sprintf('%s',axlabs{jdim}{1}),sprintf('/%s',axlabs{jdim}{2:end})]); 
end
disp(sprintf('Axis limits = %2.2f,%2.2f',axvals{jdim}([1,end])));
disp(['Number of points on axis = ',int2str(nvals)]);
if ii_indx,
    str=input('Enter index (indices) to plot: ','s');
else
    str=input('Enter [axmin,axmax] range of values to plot or list of [axval1; axval2; ...] to plot: ','s');
end
if isempty(str),
    axind{jdim}=[1:nvals];
elseif ii_indx,
    vals=str2num(str); 
    axind{jdim}=unique(round(vals(find(vals>=1 & vals<=nvals))));
else,
    vals=str2num(str);
    [nr,nc]=size(vals);
    if nr==1 & nc==2,
        axind{jdim}=find(axvals{jdim}>=vals(1) & axvals{jdim}<=vals(2));
    elseif nc==1,
        vmat=repmat(axvals{jdim}(:)',[nr,1]) - repmat(vals,[1,nvals]);
        [dum,axind{jdim}]=min(abs(vmat),[],2);
%        keyboard
    end
end
%
%%%
%
function tlab=make_title(axlabs,axvals,axind,vdims,jdim_ax,tlab,fmt)
%
jdim=vdims(jdim_ax); nvals=length(axind{jdim});
if nvals>10,
%    str=sprintf('[%1.2f,%1.2f]',axvals{jdim}(axind{jdim}([1,end])));
    str=sprintf(['[',fmt,',',fmt,']'],axvals{jdim}(axind{jdim}([1,end])));
else
%    str=sprintf('%1.2f ',axvals{jdim}(axind{jdim}));
    str=sprintf([fmt,' '],axvals{jdim}(axind{jdim}));
end
if ~isempty(tlab), tlab=[tlab,'; ']; end
% % tlab=[tlab,axlabs{jdim},' = ',str];
tlab=tlab_check(tlab,axlabs{jdim},str,fmt);
%
%%%
%
function iiij=set_iiij(axlabs,dlab)
%
iiij=cell(8,1);
for jdim=1:length(axlabs),
    ylab=axlabs{jdim};
    iiij{jdim}=0;
    if ischar(ylab),
    	if ~isempty(findstr('Depth',ylab)), iiij{jdim}=1; end
	    if strncmp('Time - ',ylab,7), iiij{jdim}=1; end
    end
end
jdim=8; ylab=dlab;
iiij{jdim}=0;
if ischar(ylab),
    if ~isempty(findstr('Depth',ylab)), iiij{jdim}=1; end
    if strncmp('Time - ',ylab,7), disp('Auto on Time'); iiij{jdim}=1; end
end
%
%%%
%
function disp_instructions
%
disp(' ')
disp('view5 help')
disp(' ')
disp('Place crosshairs over figure and enter one of the keystroke commands below.');
disp('Some commands take effect immediately;')
disp('  e.g., ''L'' immediately switches from image to line plot;  ''I'' from line to image.')
disp('Other comands require further input from command line;')
disp('  e.g., ''c'' changes the color scale.  After entering ''c'', go to the command line')
disp('    and enter new color scale limits.')
disp(' ')
disp('Basic Commands')
disp('  carriage return = exit view5')
disp('  c = change Color scale')
disp('  s = change image Size')
disp('  m = change color Map')
disp('  L = Line plot, horizontal')
disp('  +/- = change line plot index; e.g., move line plot in time')
disp('  P = multiple line Plots (each row of image becomes a different color line)')
disp('  V = Vertical line plot')
disp('  I = Image plot (switch back from line plot)')
disp('  left click mouse = zoom (must click twice to define rectangle)')
disp('    right click mouse = restore full image')
disp('  l = Label & mark peaks (finds local maximum near crosshairs)')
disp('  F = spawn new Figure window (i.e., to save current view in old window)')
disp('  down-arrow or keypad 2 = choose dimensions to image')
disp(' ')
disp('Manipulate Current Image')
disp('  i = toggle axis ij/xy (flip vertical axis)')
disp('  / = switch x-y axes')
disp('  ? = switch x-y & hor/ver (rotate image)')
disp('  b = toggle colorBar on/off')
disp('  g = toggle Grid lines on/off')
disp('  x = change X-axis limits')
disp('  y = change Y-axis limits')
disp('  t to toggle Time axis between time and sequence number')
disp('  C = contours')
disp(' ')
disp('Line Plot Commands')
disp('  =/_ to set line plot index(es)/value(s)')
disp('  h = set line colors and styles')
disp('  H = change symbols and symbol sizes')
disp('  Y = symbols & no lines')
disp('  w = change line Width')
disp('  [ = set axis(''tight'') automatically for each line plot')
disp(' ')
disp('Text Commands')
disp('  B = toggle Bold')
disp('  p = change font Point size')
disp(' ')
disp('Manipulating Multi-Dimensional (> 2) Data Sets')
disp('  G = Grid of images')
disp('  M = Movie')
disp('  left/right arrows or keypad 4/6 = vary index of first fixed dimension')
disp('  keypad 7/9 = vary index of second fixed dimension')
disp('  keypad 1/3 = vary index of third fixed dimension')
disp('  up-arrow or keypad 8 = cycle through dimensions')
disp('    * = cycle opposite way')
disp('  5 = cycle through fixed dim')
disp('  z/Z = set fixed dimension by index/value')
disp(' ')
disp('Special Purpose Commands')
disp('  A = toggle scales/scales2')
disp('  d = convert to dB (10*log10)')
disp('  D = convert to dB (20*log10)')
disp('  a = toggle dB/(angle/pi)')
disp('  u = unwrap phase')
disp('  T = threshold')


function [f_file,f_root,iif,path_back]=check_for_file(f_root,f_suf,f_label);
%
% Call [f_file,f_root,iif,path_back]=check_for_file(f_root,f_suf,f_label)
%
% Checks if file f_file=[f_root,f_suf] is local.  If not, prompts user to
% choose file from files with suffix f_suf.
% Returns file name f_file, file root f_root, flag iif=0 for no file 
% chosen, and path back to original directory path_back.
%
% Example call:
%	[geom_file,geom_root,iif,path_back]=check_for_file(geom_root,'.geom', ...
%		'Receiver Array Geometry');
%	if ~iif, return; end
%	...
%	if ~isempty(path_back); eval(['cd ''',path_back,'''']); end
%
f_file=[f_root,f_suf]; 
path_back=[]; iif=1;
if isempty(f_root) | exist(f_file,'file')~=2,
	if ~isempty(f_root) & ~all(f_root==' '), 
		disp([f_label,' file ',f_file,' not found locally.']);
	end
	[f_file,path_name]=uigetfile(['*',f_suf], ...
		['Please Choose ',f_suf,' File (Cancel to abort)']);
	if f_file==0, f_root=[]; iif=0; return; end
	path_back=pwd; eval(['cd ''',path_name,'''']);
	f_root=f_file(1:length(f_file)-length(f_suf));
end
%
%%%
%
function dlab=dlab_check(ii,dlab)
%
if ii==1,
    if ischar(dlab), 
        dlab=[dlab,' dB']; 
    else, 
        for j=1:length(dlab), dlab{j}=[dlab{j},' dB']; end; 
    end
elseif ii==2,
    if ischar(dlab), 
        dlab=dlab(1:end-3);
    else, 
        for j=1:length(dlab), dlab{j}=dlab{j}(1:end-3); end; 
    end
end
%
%%%
%
function ylab=label_check(axlab,axind);
%
if iscell(axlab),
    if isempty(axind), axind=[1:length(axlab)]; end
    if length(axind)==1,
        ylab=axlab{axind};
    else
        ylab=axlab{axind(1)};
        for j=2:length(axind),
            ylab=[ylab,'/',axlab{axind(j)}];
        end
    end
else
    ylab=axlab;
end
%
%%%
%
function tlab=tlab_check(tlab,axlab,axvals,fmt);
%
if ischar(axvals),
    str=axvals;
else
    str=sprintf(fmt,axvals);
end
if ischar(axlab),
    tlab=[tlab,axlab,' = ',str];
else
    if length(axlab)==1,
        tlab=[tlab,axlab{1},' = ',str];
    else
        tlab=[tlab,axlab{1}];
        for j=2:length(axlab), tlab=[tlab,'/',axlab{j}]; end
        tlab=[tlab,' = ',str];
    end
end
 
