function viewn(DATA,vdims,iich,iinewfig)
% Call viewn(DATA,vdims,iich,iinewfig)
%
% Generalization of view3 for n-dimensional data;
% User inputs two dimensions over which to image, one dimension over which to step;
%
% 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;
%
% V.xlab,ylab,zlab,dlab = 		axis labels for x,y,z, data;
% V.ii_img: 	0=line plot; 1=image; 2=contour; 3=shaded line plot (option removed);
% V.iilog(1:4): 0=linear axis, 1=log axis [choose for each of four axes: 
%		y,x,z,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;
%
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 isempty(V), view_global_set; end
%
if ~isfield(V,'iilog') | iscell(V.iilog), V.iilog=zeros(1,4); end
if length(V.iilog)<4, V.iilog, error('Bad V.iilog'); end
if ~isfield(V,'ii_img'), V.ii_img=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,'lcolor'), V.lcolor='rbgmck'; end
if ~isfield(V,'fname'), V.fname='Arial'; end
%
if isempty(DATA),
	disp('No data input to view: choose .mat file or cancel to choose _hdf file');
	[f_file,DATA,iif,path_back]=adi_check_file([],'.mat','.mat'),
	if ~iif,
		[f_file,DATA,iif,path_back]=adi_check_file([],'_hdf','_hdf'),
		if ~iif; 
			[f_file,f_root,iif,path_back]=adi_check_file([],'','ANY'),
			if ~iif, disp('No files chosen.  Returning from view3'); return; end
			clear DATA;
			[DATA.y,DATA.x,DATA.z,DATA.data,DATA.ylab,DATA.xlab,DATA.zlab] = ...
				hdf3dtomatwl(f_file);
			DATA.data=double(DATA.data);
		end
%%		if ~isempty(path_back), cd(path_back); end
	else
%%		if ~isempty(path_back), cd(path_back); end
	end
end
%
if ischar(DATA),
	disp('Checking for _hdf or .mat files ...')
	file_root=DATA; clear DATA;
	if exist([file_root,'_hdf'],'file')==2, 
		[DATA.y,DATA.x,DATA.z,DATA.data,DATA.ylab,DATA.xlab,DATA.zlab] = ...
			hdf3dtomatwl(file_root);
		DATA.data=double(DATA.data);
%%		[y,x,data] = hdftomatlab(file_root); size(data),
%		z=0; V.ylab='Rows'; V.xlab='Cols'; V.zlab='Layers';
	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);
		str=['DATA=S.',fields{1},';'], eval(str);
	else
		disp('Input found to be a string, but no _hdf or .mat file found locally')
		return
	end
end
[ny,nx,nz,nz2,nz3]=size(DATA.data);
% Check that first argument is a structure containing data, axes, and labels:
if ~isstruct(DATA),
	disp('view3 requires DATA structure or _hdf/.mat file root');
	return
end
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,'data'), data=DATA.data; end
if isfield(DATA,'xlab'), V.ylab=DATA.ylab; else, V.ylab='x-axis'; end
if isfield(DATA,'ylab'), V.xlab=DATA.xlab; else, V.xlab='y-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,'dlab'), V.dlab=DATA.dlab; else, V.dlab='Data'; end
if isfield(DATA,'clim'), V.clim=DATA.clim; end
if isfield(DATA,'title'), ident=DATA.title; else, ident=[]; end
%
axlabs={V.ylab; V.xlab; V.zlab; V.z2lab; V.z3lab};
axvals={y; x; z; z2; z3};
%%ny,nx,nz,nz2,nz3,length(y),length(x),length(z),length(z2),length(z3),
%%DATA, keyboard
axlims0={[y(1) y(ny)]; [x(1) x(nx)]; [z(1) z(nz)]; [z2(1) z2(nz2)]; [z3(1) z3(nz3)]};
axlims=axlims0;
axind={[1:ny]; [1:nx]; [1:nz]; [1:nz2]; [1:nz3]};
%
if iinewfig, figure; end
zoom on;
%
[nrow,ncol,nlay,nlay2,nlay3]=size(data);
dims=[nrow,ncol,nlay,nlay2,nlay3]; ndim=length(dims);%% disp(dims);
iiok=find(dims>1); dims_ok=dims(iiok); ndim_ok=length(iiok);
ii1v=find(dims==1); dims_1v=dims(ii1v); ndim_1v=length(iiok);
[dims_sort,ii_sort]=sort(dims_ok);
%
V.ii_img=1; if ndim_ok==1, V.ii_img=-1; end
if isempty(vdims),
	if ndim_ok==1,
		vdims=[iiok ii1v(1) ii1v(2)]; 
	elseif ndim_ok==2,
		vdims=[iiok(1) iiok(2) ii1v(1)];
	elseif ndim_ok>=3,
		vdims=[iiok(ii_sort([ndim_ok,ndim_ok-1,ndim_ok-2]))];
	end
elseif length(vdims)~=3,
	disp('USER ERROR: input vdims must have length 3'); return;
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 V.ii_img==-1 & nvdims(2)<nvdims(1),
	vdims=vdims([2 1 3]);
end
%
if iich,
	disp(['Enter: down-arrow or 2 to change dimensions, ', ...
		'left/right arrows to vary index of fixed dimension, '])
	disp(['  / to switch x-y axes, c to change clim, s to change size, '])
	disp(['  b to toggle colorbar, B to toggle bold, m to change color map, '])
	disp(['  l to change axis labels, i for axis(''ij''), j for axis(''xy''),'])
	disp(['  x to change x-axis limits, y to change y-axis limits,,'])
	disp(['  L for line plot, M for multi-line plot, I for image, C for contours, S for shaded line,'])
	disp(['  +/- to change line plot index, =/_ to set line plot index(es)/value(s),'])
	disp(['  P to pause, p to change point size, w to change line width,'])
	disp(['  h to set line hue(s), e to toggle cliplines call'])
	disp(['  (for clipped lines when copied and pasted), return to end'])
end
iiij=0; iiq=1;
iigrid=0; iiclip=-1; iiv=[]; 
%
jfix=1;
button=-999; 
while ~isempty(button),
%%	button,
	if any(button==[28,52]), 
		jfix=jfix - 1;
	elseif any(button==[29,54]), 
		jfix=jfix + 1;
	elseif any(button==[31,56]),
		disp(['Data dims = ',int2str(dims),'; Current y_dim,x_dim,fix_dim = [', ...
			int2str(vdims),']']);
		cmm=input('Enter new y_dim,x_dim,fix_dim: ','s'); cmm=str2num(cmm);
		if length(cmm)~=3 | any(cmm>=ndim) | any(cmm<1), 
			disp('Invalid dims');
		else
			vdims=cmm;
		end
%%	elseif any(button==[30,50]), 
%%		nfix=nfix + 1;
	elseif button==47, % / to switch x,y axes. 
		vdims=vdims([2 1 3]);
	elseif button==43, % + to increment forward on single line plot 
		iiq=iiq + 1;
	elseif button==45, % - to increment backward on single line plot 
		iiq=iiq - 1;
	elseif button==61, % = to set single line plot indices
		iiq=input('Enter index(es) for line plots ([] for all): ','s'); iiq=str2num(iiq);
	elseif button==95, % _ to set single line plot index by its value
		iiv=input('Enter axis value(s) for line plots ([] for all):','s'); iiv=str2num(iiv);
	elseif button==99, % Lower case c for clim
		cmm=input(['Enter [cmin,cmax] (currently: ',num2str(V.clim),'): '],'s'); cmm=str2num(cmm);
		if length(cmm)~=2 | cmm(1)>=cmm(2), disp('Invalid clims.'); else V.clim=cmm; end
	elseif button==115, % Lower case s for size
		cmm=input('Enter plot size [width,height] in inches: ','s'); cmm=str2num(cmm);
		V.unit='in'; 
		if isempty(cmm), break; end
		V.size=cmm;
	elseif button==109, % Lower case m for map
		V.cmap=input('Enter color map (no quotes) (jet,1-gray,etc): ','s');
		if isempty(V.cmap), break; end
		colormap(V.cmap);
	elseif button==98, % Lower case b to toggle colorbar
		V.iibar=1-V.iibar;
	elseif button==108, % Lower case 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), V.dlab=cmm; end
	elseif button==104, % Lower case h to set line hue(s)
		cmm=input(['Enter line colors (current value = ',V.lcolor, ...
			'); (<cr> to keep same): '],'s');
		if isempty(cmm), cmm='rbgmck'; end
		V.lcolor=cmm;
	elseif button==105, % Lower case i to set axis('ij')
		iiij=1;
	elseif button==106, % Lower case j to set axis('xy')
		iiij=-1;
	elseif button==112, % Lower case p to change point size
		V.ptsize=input('Enter point size: ');
	elseif button==103, % Lower case g to toggle grid on and off
		if iigrid==0, iigrid=1; else, iigrid=-iigrid; end
	elseif button==76, % Upper case L for single line plot
		V.ii_img=-1; iiv=ypt;
	elseif button==77, % Upper case M for multiple line plot
		V.ii_img=-1; iiv=ypt;
	elseif button==73, % Upper case I for image plot
		V.ii_img=1;
	elseif button==67, % Upper case C for contour plot
		V.ii_img=2;
	elseif button==83, % Upper case S for shaded line plot
		V.ii_img=3;
	elseif button==80, % Upper case P to pause so that figure may be copied
		disp('Pausing so that figure may be copied.  Press return to continue.');
		pause;
	elseif button==101, % Lower case e to toggle cliplines call (makes copied plot's lines clipped)
		iiclip=-iiclip,
	elseif button==66, % Upper case B to toggle bold lettering 
		V.iibold=1-V.iibold;
	elseif button==119, % Lower case 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;
	elseif button==120, % Lower case 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]: ','s'); cmm=str2num(cmm);
		if length(cmm)~=2, break; end
		axlims{vdims(2)}=cmm;
		xvals=axvals{vdims(2)};
		axind{vdims(2)}=find(xvals>=cmm(1) & xvals<=cmm(2));
	elseif button==121, % Lower case 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  horizontal axis limits [ymin,ymax]: ','s'); cmm=str2num(cmm);
		if length(cmm)~=2, break; end
		axlims{vdims(1)}=cmm;
		yvals=axvals{vdims(1)};
		axind{vdims(1)}=find(yvals>=cmm(1) & yvals<=cmm(2));
	elseif button==-999,
%
	else
%%		disp('Unknown button pushed...');
	end
%
	if jfix>dims(vdims(3)), jfix=1; elseif jfix<1, jfix=dims(vdims(3)); end
%
	KV={1 1 1 1 1};	KV{vdims(3)}=jfix;
	KV{vdims(1)}=axind{vdims(1)}; KV{vdims(2)}=axind{vdims(2)};
	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}),nytake,nxtake);
	else
% Must transpose:
		datax=reshape(data(KV{1},KV{2},KV{3},KV{4},KV{5}),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)};
	iilog=V.iilog([vdims(1) vdims(2) 4]);
% Case where no axis label given, do not have title (such as 2-D arrays):
	if isempty(axlabs{vdims(3)}), 
		tlab=[]; 
	else, 
		tlab=[axlabs{vdims(3)},'=',num2str(axvals{vdims(3)}(jfix))]; 
	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,
			imagesc(xax,yax,datax,V.clim); xlabel(xlab); ylabel(ylab);
			colormap(V.cmap);
	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);
			V.xlabel(c,h); grid on;
			axis('ij');
	elseif V.ii_img<=0,
		if ~isempty(iiv),
			nv=length(iiv); vmat=abs(ones(nv,1)*yax(:)' - iiv'*ones(1,length(yax)));
			[dum,iiq]=min(vmat,[],2); iiq=iiq'; iiv=[];
		end
		if V.ii_img==0 | isempty(iiq), 
			iiq=[1:size(datax,1)]';
		else
			if iiq<1, iiq=size(datax,1); elseif iiq>size(datax,1), iiq=1; end
		end;
%		size(iiq),size(datax),size(xax),
		plotll(xax,datax(iiq,:),iilog([1 3]),V.lcolor); 
		xlabel(xlab); ylabel(V.dlab); grid on;
		axis([xax(1) xax(nxax) V.clim(1) V.clim(2)]);
		niiq=length(iiq);
		if niiq>0 & niiq<10,	
			yleg=num2str(yax(iiq)');
			leg=[ones(niiq,1)*[ylab(1),' = '],yleg]; 
%			mylegend(leg,0); 
		end
	end
% If time is not on vertical axis, use axis('xy'):
	if V.ii_img==1 | V.ii_img==2,
		if ~strncmp(ylab,'Time',4) & ~strncmp(ylab,'Sequ',4), 
			axis('xy'); 
		end
	end
%
	if iiij==1, axis('ij'); elseif iiij==-1, 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 ~isempty(V.unit),
		plot_size(gca,V.unit,V.size(1),V.size(2));
	end
	if (V.ii_img==1 | V.ii_img==2) & V.iibar==1, hc=mycolorbar2('vert',0); end;
	if ~isempty(ident) & V.ident,
		str=strrep(ident,'_','\_');
		if iiij,
			h=text(xax(nxax),yax(nyax),str);
			set(h,'FontName','Arial','Fontsize',9,'HorizontalAl','Center','VerticalAl','Top'); 
		else
			h=text(xax(nxax),yax(1),str);
			set(h,'FontName','Arial','Fontsize',9,'HorizontalAl','Center','VerticalAl','Bottom'); 
		end
	end
% Break if no changes desired:
	if ~iich, break; end
%%keyboard
% Otherwise get input key:
	[xpt,ypt,button]=ginput(1);
end
% Save plotting defaults in file view_def
expr=['save view_def V']; eval(expr);
%
%%%
%
function plotll(xax,datax,iilog,col); 
%
ncol=length(col);
[nr,nc]=size(datax);
nx=length(xax);
if nr~=nx & nc==nx, 
	datax=datax.'; 
	[nr,nc]=size(datax);
end
%
if iilog(1)==0 & iilog(2)==0,
	for jplot=1:nc,
		jcol=mod(jplot-1,ncol) + 1;
		plot(xax,datax(:,jplot),col(jcol)); hold on;
	end
elseif iilog(1)==1 & iilog(2)==0,
	for jplot=1:nc,
		jcol=mod(jplot-1,ncol) + 1;
		semilogx(xax,datax(:,jplot),col(jcol))
	end
elseif iilog(1)==0 & iilog(2)==1,
	for jplot=1:nc,
		jcol=mod(jplot-1,ncol) + 1;
		semilogy(xax,datax(:,jplot),col(jcol))
	end
elseif iilog(1)==1 & iilog(2)==1,
	for jplot=1:nc,
		jcol=mod(jplot-1,ncol) + 1;
		loglog(xax,datax(:,jplot),col(jcol))
	end
end
hold off;
%
% 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.
