function analyses(handle);
% a function used in cmgtool data analyses.
% here the handle is the xhand.XXXX designate different analyzing methods.
global xfile xf xhand xnum xcount whereat whichnew jtime binasked whichbin
global xslide xfnew xsave ncf whichfile initialplot timebase initialsave tflag
global tdomain fdomain liststore xfnewstore whereatstore xcountstore goodindex 
global ratioxy ratiox ratioy

switch handle

case 'run_fdomain'
	u=get(xhand.ana(1),'string');
	if isempty(spacebuster(u))
		errordlg('Parameters need to be filled first!','Error');
		return;
	end;
	[t,s]=strtok(u,'[]');
	if isempty(spacebuster(s))
		xspec=0;
	else
		xspec=1;
		u=t;
	end;
	vari=varifieldconfig(1,u);
	
	junk=whichfile(1,:);
	file_used=junk(junk>0);
	numberoffiles=length(file_used);
	if numberoffiles>1
		tempf=sort(file_used);
		tempf=diff(tempf);
		nzeros=length(find(tempf==0));
		numberoffiles=numberoffiles-nzeros;
	end;

	if isempty(file_used)
		return;
	elseif numberoffiles>1 % multiple files, timebase problem needs to be dealt with
		
		[overlap,endmin,endmax,minmax,maxdeltat,thetime]=isoverlap(file_used,'ana');
		
		if overlap
			timebase=endmin : maxdeltat : endmax;
			timebase=timebase(:);
		else
			errordlg('There is no overlap between the two files','Error');
			set(xhand.notes,'string','Ready - Waiting for command...');
			return;
		end;
		
	else   % single file, so there is no timebase problem
		overlap=0;
		rtime=timeloading(file_used(1),'ana');
		
		timebase=rtime*24*3600000; %%%% milliseconds %%%%
		thetime{1}=timebase;
		thetime{2}=timebase;
	end;

	for i=1:length(vari),	
		if whichfile(1,i)<10
			u=ncf(whichfile(1,i)).file{vari{i}}(goodindex{whichfile(1,i)},:);
		else
			u=xfnew(whichnew.ana(1,i)).data(:,:);
		end;
		if overlap
			uf{i}=interp1q(thetime{i},u,timebase);
		else
			uf{i}=u;
		end;
			
		uf{i}=dataclean(uf{i}(:));
		uf{i}(isnan(uf{i})==1)=0;
	end;
	if length(uf{1})<256
		selection = questdlg('Variable has less than 256 points, continue?',...
	                   'Warning',...
	                   'Yes','No','No');
		switch selection,
		case 'No'
			return;
		case 'Yes',
		end;
	end;
		
	method=get(xhand.analyzeit,'value') - 1;
	switch method
	case 1 %spectrum
		thetitle={' ','NFFT','NOVERLAP','Fs','Pr'};
		defaultvalue={' ', [256], [128], [2], [0.95]};
		for i=2:5
			temp{i}=spacebuster(get(xhand.ana(i),'string'));
			if isempty(temp{i})
				ntemp{i}=defaultvalue{i};
			else
				ntemp{i}=str2num(temp{i});
				if isempty(ntemp{i}),
					errordlg([thtitle{i} ' must be numeric!'],'Error');
					return;
				end;
			end;
		end;
		if length(uf{1})<ntemp{2}
			errordlg('NFFT is too large.','Error');
			return;
		end;
% 		if ntemp{2}==256
% 			ntemp{2}=length(uf);
% 		end;
		set(xhand.notes,'string','Computing spectra...');
		if xspec
			if ~(length(vari)==2)
				errordlg('Two variables are needed in Cross-spectrum.','Error');
				set(xhand.notes,'string','Ready - Waiting for command...');
				return;
			end;
			[thespec,thefreq]=spectrum(uf{1},uf{2},ntemp{2},ntemp{3},ntemp{2},ntemp{4},ntemp{5});			
			temp1=epicremover(vari{1});
			temp2=epicremover(vari{2});
			junk=renew(thespec,[temp1 'xx' temp2 '_specx'],whichnew.ana(1,1));
			xfnew(junk).freqx=thefreq;
			xfnew(junk).files=file_used;
			[xfnew(junk).attname,xfnew(junk).att]=newattrib([temp1 'xx' temp2 '_specx'],thespec,file_used);
		else
			for i=1:length(vari)
				[thespec,thefreq]=spectrum(uf{i},ntemp{2},ntemp{3},ntemp{2},ntemp{4},ntemp{5});				
				tempy=epicremover(vari{i});
				junk=renew(thespec,[tempy '_spec'],whichnew.ana(1,i));
				xfnew(junk).freq=thefreq;
				xfnew(junk).files=file_used(i);
				[xfnew(junk).attname,xfnew(junk).att]=newattrib([tempy '_spec'],thespec,file_used(i));
			end;
		end;
		set(xhand.newvarlist,'string',xf.newvarlist);
		set(xhand.notes,'string','Ready - Waiting for command...');
		
	case {2,3} %Xcov or Xcorr
		delt=str2num(get(xhand.dt,'string'));
		temp=spacebuster(get(xhand.ana(2),'string'));
		if isempty(temp)
			ntemp=length(uf{1})-1;
		else
			ntemp=str2num(temp);
			if isempty(ntemp),
				errordlg('Maxlags must be numeric!','Error');
				return;
			end;
			ntemp=round(ntemp/delt);
			if ntemp<3
				errordlg('Maxlags is too small.','Error');
				return;
			end;
		end;
		allopts={'biased','unbiased','coeff','none'};
		opts='none';
		for i=1:4
			opvalue(i)=get(xhand.options(i),'value');
		end;
		if any(opvalue)
			opts=allopts{find(opvalue==1)};
		end;
		xco={'','xcov','xcorr'};
		xcotail={'','_cov','_corr'};
		xcotailx={'','_covx','_corrx'};
		set(xhand.notes,'string','Computing Xcov or Xcorr...');
		if xspec
			if ~(length(vari)==2)
				errordlg('Two variables are needed in Cross-Covaience.','Error');
				set(xhand.notes,'string','Ready - Waiting for command...');
				return;
			end;
			eval(['[thespec,thefreq]=' xco{method} '(uf{1},uf{2},ntemp,opts);']);
			thefreq=thefreq*delt;
			temp1=epicremover(vari{1});
			temp2=epicremover(vari{2});
			junk=renew(thespec,[temp1 'xx' temp2 xcotailx{method}],whichnew.ana(1,1));
			xfnew(junk).lag=thefreq;
			xfnew(junk).files=file_used;
			[xfnew(junk).attname,xfnew(junk).att]=newattrib([temp1 'xx' temp2 xcotail{method}],thespec,file_used);
		else
			for i=1:length(vari)
				eval(['[thespec,thefreq]=' xco{method} '(uf{i},ntemp,opts);']);
				thefreq=thefreq*delt;
				tempy=epicremover(vari{i});
				junk=renew(thespec,[tempy xcotail{method}],whichnew.ana(1,i));
				xfnew(junk).lag=thefreq;
				xfnew(junk).files=file_used(i);
				[xfnew(junk).attname,xfnew(junk).att]=newattrib([tempy xcotail{method}],thespec,file_used(i));
			end;
		end;
		set(xhand.newvarlist,'string',xf.newvarlist);
		set(xhand.notes,'string','Ready - Waiting for command...');
		
	case 4
		
	end;
	liststore{2}=xf.newvarlist;
	xfnewstore{2}=xfnew;
	whereatstore{2}=whereat;
	xcountstore{2}=xcount.new;
	
case 'run'
	msg={'There has been an error or errors!',...
	'Hints:',...
	'1. Check your spelling.',...
	'2. Variables are from the variables windows.',...
	'3. Variables dimensions should agree.'};
	
	method=get(xhand.analyzeit,'value') - 1;
	methodstr=get(xhand.analyzeit,'string');
	switch method
	
	case 1  % arithmetic
		msg_arith={'There has been an error or errors!',...
		'Hints:',...
		'1. Check your spelling.',...
		'2. RHS variables are from the variables windows.',...
		'3. Vector dot-mulitiplication and division',...
		'   need to use the .* or ./ oprators.',...
		'4. Dimensions of variables should agree.'};
		formula=get(xhand.ana(1),'string');
		s=formula;
		if isempty(s),
			errordlg('Parameters need to be filled first!','Error');
			return;
		end;
		j=0;
		while ~isempty(s)
			j=j+1;
			[vari{j},s]=strtok(s,' ^=+-/*\[]().;');
		end;
		if isempty(vari{j}),
			j=j-1;
		end;
		atime=[];
		for i=2:j,
			testing=[exist(vari{i})~=2 exist(vari{i})~=5];
			if any(isletter(vari{i})) & all(testing)
				[index,pick]=search(vari{i});
				if pick=='all',
					eval([vari{i} '=xfile{xf.varlist{index}}(goodindex{xnum.file},:);']);
					atime=jtime{xnum.file};
				elseif pick=='new',
					eval([vari{i} '=xfnew(index).data;']);
					if isempty(xfnew(index).time)
						atime=jtime{whereat(index)};
					else
						atime=xfnew(index).time;
					end;
				else
					errordlg(msg_arith,'Error');
					return;
				end;
			
% 				vari{i}=dataclean(vari{i});
			end;
			if ~isempty(findstr(':',vari{i}))
				subrange=1;
				[thisrange,junk]=strtok(vari{i},',');
			else 
				subrange=0;
			end;
		end;
		if subrange
			eval(['atime=atime(' thisrange ');']);
		end;
			
		try
			eval([spacebuster(formula) ';']);
		catch
			errordlg(msg_arith,'Error');
			return;
		end;
		indx=find(strcmp(lower(xf.newvarlist),[lower(vari{1}) '_fh'])==1);
		if ~isempty(indx),
			xf.newvarlist{indx}=[vari{1} '_fh'];
			eval(['xfnew(indx).data=' vari{1} ';']);
			xfnew(indx).time=atime;
			whereat(indx)=xnum.file;
		else
			xcount.new=xcount.new+1;
			xf.newvarlist{xcount.new}=[vari{1} '_fh'];
			eval(['xfnew(xcount.new).data=' vari{1} ';']);
			xfnew(xcount.new).time=atime;
			whereat(xcount.new)=xnum.file;
			indx=xcount.new;
		end;
		[xfnew(indx).attname,xfnew(indx).att]=newattrib(vari{1},xfnew(indx).data,xnum.file);
		set(xhand.newvarlist,'string',xf.newvarlist);
		
	case {2, 3, 13} % filtering
		u=get(xhand.ana(1),'string');
		fs=spacebuster(get(xhand.ana(2),'string'));
		fc='just filling in';
		subsamp='just filling in';
		if method~=3
			fc=spacebuster(get(xhand.ana(3),'string'));
			subsamp=spacebuster(get(xhand.ana(4),'string'));
		end;
		dummy=[~isempty(fs),~isempty(fc),~isempty(spacebuster(u))];
		if ~all(dummy),
			errordlg('Parameters need to be filled first!','Error');
			return;
		end;
		if strmatch('all',lower(spacebuster(u)),'exact')
			notvar={'time','time2','depth','lat','lon'};
			vari=xf.varlist;
			for jj=1:length(notvar)
				mark=strcmpi(notvar{jj},vari);
				vari=vari(find(mark==0));
			end;
			u=vari;
		end;
		vari=varifieldconfig(1,u);
		for i=1:length(vari),
			[index,pick]=search(vari{i});
			if pick=='all',
				uf=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
				thetime=jtime{xnum.file};
				origfiles=xnum.file;
			elseif pick=='new',
				uf=xfnew(index).data;
				if isempty(xfnew(index).time)
					thetime=jtime{whereat(index)};
				else
					thetime=xfnew(index).time;
				end;
				origfiles=whereat(index);
			else
				errordlg(msg,'Error');
				return;
			end;
			data{i}=uf;
		end;
		
		fs=str2num(fs);
		if isempty(fs),
			errordlg('The content must be numeric!','Error');
			return;
		end;
	
		if method~=3
			fc=str2num(fc);
			if isempty(fc),
				errordlg('The content must be numeric!','Error');
				return;
			end;
			if isempty(subsamp)
				subsamp=1;
			else
				subsamp=str2num(subsamp);
				if isempty(subsamp),
					errordlg('The content must be numeric!','Error');
					return;
				end;				
			end;
		end;
	
		if method==2;
			set(xhand.notes,'string','FILTFILT filtering...');
			for i=1:length(vari),	
				uf=dataclean(data{i});
				uf(find(isnan(uf)==1))=0;
			
				if length(uf)<16,
					errordlg('Length of variable must be longer than 15.','Error');
					set(xhand.notes,'string','Ready - Waiting for command...');
					return;
				end;
				[b,a]=butter(5,2*fc/fs);
				uf=filtfilt(b,a,uf);
				uf=uf(1:subsamp:end,:);
				
				junky=epicremover(vari{i});
				temp=renew(uf,[junky '_filt'],whichnew.ana(1,i));
				xfnew(temp).time=thetime(1:subsamp:end);
				[xfnew(temp).attname,xfnew(temp).att]=newattrib([junky '_filt'],xfnew(temp).data,origfiles);
				set(xhand.newvarlist,'string',xf.newvarlist);
			end;
			set(xhand.notes,'string','Ready - Waiting for command...');
		end;
	
		if method==3
			if str2num(get(xhand.dt,'string'))~=3600
				errordlg('PL33 can ONLY be used on HOURLY data.','Error');
				return;
			end;
			set(xhand.notes,'string','PL33 filtering...');
			for i=1:length(vari)
				datatemp=dataclean(data{i});
% 				datatemp(find(isnan(datatemp)==1))=0;
				[uf,jdf]=rpspl33(datatemp,thetime,fs);
				if uf==-1 and jdf==-1
					set(xhand.notes,'string','Ready - Waiting for command...');
					return;
				end;

				junky=epicremover(vari{i});
				temp=renew(uf,[junky '_f33'],whichnew.ana(1,i));
				xfnew(temp).time=jdf;
				[xfnew(temp).attname,xfnew(temp).att]=newattrib([junky '_f33'],xfnew(temp).data,origfiles);
				set(xhand.newvarlist,'string',xf.newvarlist);
			end;
			set(xhand.notes,'string','Ready - Waiting for command...');
		end;
	
		if method==13
			set(xhand.notes,'string','Data gap bridging...');
			for i=1:length(vari),	
				uf=dataclean(data{i});
				nogap=1;
				[uf,nogap]=bridgemain(uf,fs,fc,subsamp,vari{i});
				if nogap
					break;
				end;
				
				junky=epicremover(vari{i});
				temp=renew(uf,[junky '_brdg'],whichnew.ana(1,i));
				xfnew(temp).time=thetime;
				[xfnew(temp).attname,xfnew(temp).att]=newattrib([junky '_brdg'],xfnew(temp).data,origfiles);
				set(xhand.newvarlist,'string',xf.newvarlist);
			end;
			set(xhand.notes,'string','Ready - Waiting for command...');
		end;
	
	case {4, 12} % rotating and wind stress
		newtime=[];
		isanum=1;
		ustr=spacebuster(get(xhand.ana(1),'string'));
		vstr=spacebuster(get(xhand.ana(2),'string'));
		thetastr=spacebuster(get(xhand.ana(3),'string'));
		dummy=[~isempty(ustr),~isempty(vstr),~isempty(thetastr)];
		if ~all(dummy),
			errordlg('Parameters need to be filled first!','Error');
			return;
		end;
		[index,pick]=search(ustr);
		if pick=='all',
			u=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
		elseif pick=='new',
			u=xfnew(index).data;
			newtime=xfnew(index).time;
		else
			errordlg(msg,'Error');
			return;
		end;	
		[index,pick]=search(vstr);
		if pick=='all',
			v=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
			origfiles=xnum.file;
		elseif pick=='new',
			v=xfnew(index).data;
			origfiles=whereat(index);
			newtime=xfnew(index).time;
		else
			errordlg(msg,'Error');
			return;
		end;
		if ~(length(u)==length(v)),
			errordlg(msg,'Error');
			return;
		end;
		if method==12
			theta=str2num(thetastr);
			if ~isempty(theta)
				theta=theta*ones(size(u));
			else
				[index,pick]=search(thetastr);
				if pick=='all',
					theta=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
					origfiles=xnum.file;
				elseif pick=='new',
					theta=xfnew(index).data;
					origfiles=whereat(index);
				else
					errordlg(msg,'Error');
					return;
				end;
			end;
			set(xhand.notes,'string',['Analyzing ' methodstr{method+1} '...']);
			u=dataclean(u);
			v=dataclean(v);
			theta=dataclean(theta);
			for i=1:length(u)
				w10(i)=speed10(u(i),theta(i));
			end;
			u=w10(:);
			uew=u.*sin(v.*pi/180);
			uns=u.*cos(v.*pi/180);
			xstr = ((0.8 + (.065*u))*.012).*u.*uew;
			ystr = ((0.8 + (.065*u))*.012).*u.*uns;
			temp=renew(xstr,'Wstress_EW',whichnew.ana(1,1));
			xfnew(temp).time=newtime;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib('Wstress_EW',xfnew(temp).data,origfiles);
			temp=renew(ystr,'Wstress_NS',whichnew.ana(1,1));
			xfnew(temp).time=newtime;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib('Wstress_NS',xfnew(temp).data,origfiles);
		end;
		
		if method==4	
			theta=str2num(thetastr)*pi/180;
			if isempty(theta),
				errordlg('Angle must be numeric!','Error');
				return;
			end;
			set(xhand.notes,'string',['Analyzing ' methodstr{method+1} '...']);
			u=dataclean(u);
			v=dataclean(v);
		
			ur=u.*cos(theta)+v.*sin(theta);
			vr=-u.*sin(theta)+v.*cos(theta);
			
			varifieldconfig(1,ustr);
			varifieldconfig(2,vstr);
			
			junky=epicremover(ustr);
			temp=renew(ur,[junky '_r'],whichnew.ana(1,1));
			xfnew(temp).time=newtime;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib([junky '_r'],xfnew(temp).data,origfiles);
			junky=epicremover(vstr);
			temp=renew(vr,[junky '_r'],whichnew.ana(2,1));
			xfnew(temp).time=newtime;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib([junky '_r'],xfnew(temp).data,origfiles);
		end;
		set(xhand.newvarlist,'string',xf.newvarlist);
		set(xhand.notes,'string','Ready - Waiting for command...');
		
	case {5, 6, 11} % uv2speed and speed2uv and principal axis
		global oldscat
		newtime=[];
		ustr=spacebuster(get(xhand.ana(1),'string'));
		vstr=spacebuster(get(xhand.ana(2),'string'));
		dummy=[~isempty(ustr),~isempty(vstr)];
		if ~all(dummy),
			errordlg('Parameters need to be filled first!','Error');
			return;
		end;
		[index,pick]=search(ustr);
		if pick=='all',
			u=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
		elseif pick=='new',
			u=xfnew(index).data;
		else
			errordlg(msg,'Error');
			return;
		end;
		[index,pick]=search(vstr);
		if pick=='all',
			v=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
			origfiles=xnum.file;
		elseif pick=='new',
			v=xfnew(index).data;
			origfiles=whereat(index);
			newtime=xfnew(index).time;
		else
			errordlg(msg,'Error');
			return;
		end;
		if ~(length(u)==length(v)),
			errordlg(msg,'Error');
			return;
		end;

		set(xhand.notes,'string',['Analyzing ' methodstr{method+1} '...']);
		u=dataclean(u);
		v=dataclean(v);
	
		if method==5
			spd=sqrt(u.^2 + v.^2);
			dir=atan2(u,v)*180/pi;
			indx=find(dir<0);
			dir(indx)=dir(indx)+360;
			
			ss=upper([ustr(1) vstr(1)]);
			temp=renew(spd,['spd_' ss],whichnew.ana(1,1));
			xfnew(temp).time=newtime;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib(['spd' '_uv2spd'],xfnew(temp).data,origfiles);
			temp=renew(dir,['dir_' ss],whichnew.ana(2,1));
			xfnew(temp).time=newtime;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib(['dir' '_uv2spd'],xfnew(temp).data,origfiles);
		elseif method==6
			uew=u.*sin(v.*pi/180);
			uns=u.*cos(v.*pi/180);
					
			temp=renew(uew,'EW_vel',whichnew.ana(1,1));
			xfnew(temp).time=newtime;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib(['east' '_spd2uv'],xfnew(temp).data,origfiles);
			temp=renew(uns,'NS_vel',whichnew.ana(2,1));
			xfnew(temp).time=newtime;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib(['north' '_spd2uv'],xfnew(temp).data,origfiles);
		end;
		set(xhand.newvarlist,'string',xf.newvarlist);
		if method==11
			figure(xhand.figF);
			set(xhand.figF,'name','PCA plot');
			scat=get(xhand.checkbox,'value');
			if ~initialplot
				if oldscat~=scat
					initialplot=1;
				end;
			end;
			if initialplot
				clf;
				indx=find(isnan(u)==0);u=u(indx);v=v(indx);
				indx=find(isnan(v)==0);u=u(indx);v=v(indx);
				
				axislimit=pca(u,v,scat);
				oldscat=scat;
				fnames=get(xhand.filename,'string');
				title(fnames{xnum.file+1}(4:end));
				xlabel(strrep(ustr,'_','\_'));ylabel(strrep(vstr,'_','\_'));
				
				set(xhand.ylimedit(5),'visible','on',...
					'Position',[250 200 70 20].*ratioxy,...
					'string',['-' num2str(axislimit) ', ' num2str(axislimit)]);
				set(xhand.plotheader(5),'visible','on',...
					'Position',[250 220 70 10].*ratioxy,...
					'string','Axis Limits');
				initialplot=0;
			else
				temp=get(xhand.ylimedit(5),'string');
				try
					ylim=str2num(temp);
				catch
					errordlg('Likely a typo in Ylim!','Error');
					return;
				end;
				if ylim(1)>=ylim(2)
					errordlg('Ylim(1) should always be less than Ylim(2)!','Error');
					return;
				end;
				axis([ylim(1) ylim(2) ylim(1) ylim(2)]);
			end;
		end;
		set(xhand.notes,'string','Ready - Waiting for command...');
		
	case {7, 8, 14} % averaging and subsampling and statistics
		ustr=get(xhand.ana(1),'string');
		thetastr=spacebuster(get(xhand.ana(2),'string'));
		dummy=[~isempty(spacebuster(ustr)),~isempty(thetastr)];
		if ~all(dummy),
			errordlg('Parameters need to be filled first!','Error');
			return;
		end;
		theta=str2num(thetastr);
		if isempty(theta) & method~=14
			errordlg('Length must be integer!','Error');
			return;
		end;
		if strmatch('all',lower(spacebuster(ustr)),'exact')
			notvar={'time','time2','depth','lat','lon'};
			vari=xf.varlist;
			for jj=1:length(notvar)
				mark=strcmpi(notvar{jj},vari);
				vari=vari(find(mark==0));
			end;
			ustr=vari;
		end;
		vari=varifieldconfig(1,ustr);
		for i=1:length(vari),	
			[index,pick]=search(vari{i});
			if pick=='all',
				u=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
				tt=24*36e5*jtime{xnum.file};
				origfiles=xnum.file;
			elseif pick=='new',
				u=xfnew(index).data;
				if isempty(xfnew(index).time)
					tt=jtime{whereat(index)};
				else
					tt=xfnew(index).time;
				end;
				tt=24*36e5*tt;
				origfiles=whereat(index);
			else
				errordlg(msg,'Error');
				return;
			end;
			
			set(xhand.notes,'string',['Analyzing ' methodstr{method+1} '...']);
			u=dataclean(u);
	
			if method==7
				cols=floor(length(tt)/theta);
				temp=reshape(tt(1:theta*cols),theta,cols);
				temp=mean(temp);
				tavg=temp';
				uavg=[];
				for kk=1:size(u,2)
					temp=reshape(u(1:theta*cols,kk),theta,cols);
					temp=mean(temp);
					uavg=[uavg temp'];
				end;							
				junky=epicremover(vari{i});
				temp=renew(uavg,[junky '_avg'],whichnew.ana(1,i));
				xfnew(temp).time=tavg/(24*3600000);
				[xfnew(temp).attname,xfnew(temp).att]=newattrib([junky '_avg'],xfnew(temp).data,origfiles);
			elseif method==8
				uavg=u(1: theta+1 : length(tt),:);
				tavg=tt(1: theta+1 : length(tt),:);
									
				junky=epicremover(vari{i});
				temp=renew(uavg,[junky '_sub'],whichnew.ana(1,i));
				xfnew(temp).time=tavg/(24*3600000);
				[xfnew(temp).attname,xfnew(temp).att]=newattrib([junky '_sub'],xfnew(temp).data,origfiles);
			elseif method==14
				u=nanbuster(u);
				ustats(i,1)=mean(u);
				ustats(i,3)=std(u);
				ustats(i,4)=max(u);
				ustats(i,5)=min(u);
				
				if ~isempty(theta)
					ustats(i,2)=std(u)*mdsti(0.05,theta)/sqrt(theta+1);
				else
					[out1,out2]=xcorr(u,'coeff');
					out1(1:length(u)-1)=[];
					out2(1:length(u)-1)=[];
					dum=find(out1<=0.2);
					if ~isempty(dum)
						dum=dum(1);
					else 
						dum=length(out1);
					end;
					figure(11);
					plot(out2(1:dum),out1(1:dum));
					ok=0;
					while ~ok
						[x,y]=ginput(1);
						x=round(abs(x));
						def{1}=num2str(x);
						def{2}=num2str(y);
						answer=inputdlg('Is the selected autocorrelation scale value OK?',...
							'Your selection',1,def);
						ok=~isempty(answer);
					end;
					xx=round(length(u)/x);
					ustats(i,2)=std(u)*mdsti(0.05,xx)/sqrt(xx+1);
				end;
				if i==length(vari)
					fprintf('\n');
					fprintf('==== Statistics Report ====================\n');
					fprintf('      # of valid points:%8d\n',length(u));
					fprintf('      Start Time:%40s\n',num2str(gregorian(min(tt)/24/36e5)));
					fprintf('      Stop  Time:%40s\n',num2str(gregorian(max(tt)/24/36e5)));
					if isempty(theta)
						close(11);
						fprintf('      Correlation amplitude:%10s\n',def{2});
						tjunk=diff(tt);
						tjunk=tjunk(1)/1000;
						fprintf('      correlation time scale:%10.2f Days\n',tjunk*x/24/3600);
						fprintf('      Degree of freedom:%5d\n',x);
					else
						fprintf('      Degree of freedom:%5d\n',theta);
					end;
					fprintf('\n');
					fprintf('%50s\n','      MEAN  ERRORBAR      STDV       MAX       MIN');
					disp(ustats);
					fprintf('============================================\n');
					fprintf('\n');
				end;
			end;	
			set(xhand.newvarlist,'string',xf.newvarlist);
		end; % of for i=1:length(vari)
		set(xhand.notes,'string','Ready - Waiting for command...');
			
	case 9 % Merging files on provided variables to a uniform timebase
		for i=1:5
			mystr{i}=get(xhand.ana(i),'string');
			if isempty(spacebuster(mystr{i}))
				errordlg('Parameters need to be filled first!','Error');
				return;
			end;
		end;
				
		strvar=mystr{1};
		if strmatch('all',lower(spacebuster(strvar)),'exact')
			notvar={'time','time2','depth','lat','lon'};
			varia=xf.varlist;
			for jj=1:length(notvar)
				mark=strcmpi(notvar{jj},varia);
				varia=varia(find(mark==0));
			end;
		else
			numvar=0;
			while ~isempty(strvar)
				numvar=numvar+1;
				[varia{numvar},strvar]=strtok(strvar,' ,');
			end;
		end;
		tmin=strrep(mystr{3},'-',' ');tmin=strrep(tmin,':',' ');
		tmax=strrep(mystr{4},'-',' ');tmax=strrep(tmax,':',' ');
		try
			jd0=julian(str2num(tmin));
			jd1=julian(str2num(tmax));
		catch
			errordlg('Time input must be numerical','Error');
			return;
		end;
		if jd0>=jd1
			errordlg('Tstop must alwasy be larger than Tstart.','Error');
			return;
		end;
		try
			dt=str2num(mystr{5});
		catch
			errordlg('Input in Interval field must be nuermical','Error');
			return;
		end;
		numfile=str2num(mystr{2});
		mergfrom=[];
		filenames=get(xhand.filename,'string');
		for i=1:length(numfile)
			for j=1:length(varia)
				mydata{i,j}=ncf(numfile(i)).file{varia{j}}(goodindex{numfile(i)},:);
				if isempty(mydata{i,j})
					errordlg(['The variable <' varia{j} '> does''nt exist in file ' num2str(numfile(i))],'Error');
					return;
				end;
			end;
			mytime{i}=jtime{numfile(i)};
			mergfrom=[mergfrom filenames{numfile(i)+1}(3:end) ', '];
		end;
		mergfrom=mergfrom(1:end-2);
		
		set(xhand.notes,'string',['Analyzing ' methodstr{method+1} '...']);
		for i=1:length(numfile)
			for j=1:length(varia)
				mydata{i,j}=dataclean(mydata{i,j});
			end;
		end;

		npts=((jd1-jd0)/(dt/3600/24))+1;
		jdi=0:npts-1;
		jdi=jdi*dt;
		jdi=jdi(:);
		for j=1:length(varia)
			wi{j}=jdi*nan;
			for i=1:length(numfile)
				jd=24*3600*(mytime{i} - jd0);
% 				jd=jd(:,:);
				temp=mydata{i,j}(:,:);
				temp(find(isnan(temp)==1))=1e35;
				w=interp1q(jd,temp,jdi);
% 				w=interp1(jd,mydata{i,j},jdi);
				w(w>1e15)=nan;
				ind=find(~isnan(w));
				wi{j}(ind)=w(ind);
			end;
		end;
		jd=jd0+jdi/3600/24;
		
		for j=1:length(varia)
			junky=epicremover(varia{j});
			temp=renew(wi{j},[junky '_merg'],-1);
			xfnew(temp).time=jd;
			xfnew(temp).mergfrom=mergfrom;
			[xfnew(temp).attname,xfnew(temp).att]=newattrib([junky '_merg'],xfnew(temp).data,numfile);
			set(xhand.newvarlist,'string',xf.newvarlist);
		end;
		set(xhand.newvarlist,'enable','on');
		set(xhand.notes,'string','Ready - Waiting for command...');
		
	case 10 % inter-file calculations
		for i=1:5
			mystr{i}=get(xhand.ana(i),'string');
			if isempty(spacebuster(mystr{i}))
				errordlg('Parameters need to be filled first!','Error');
				return;
			end;
		end;
	
		set(xhand.notes,'string',['Analyzing ' methodstr{method+1} '...']);
		junk=whichfile(:,1);
		file_used=junk(junk>0);

		numberoffiles=length(file_used);
		if numberoffiles>1
			tempf=sort(file_used);
			tempf=diff(tempf);
			nzeros=length(find(tempf==0));
			numberoffiles=numberoffiles-nzeros;
		end;
	
		if isempty(file_used)
			return;
		elseif numberoffiles>1 % multiple files, timebase problem needs to be dealt with
			
			[overlap,endmin,endmax,minmax,maxdeltat,thetime]=isoverlap(file_used,'ana');
			
			if overlap
				timebase=endmin : maxdeltat : endmax;
				timebase=timebase(:);
			else
				errordlg('There is no overlap between the two files','Error');
				set(xhand.notes,'string','Ready - Waiting for command...');
				return;
			end;
			
		else   % single file, so there is no timebase problem
			overlap=0;
			rtime=timeloading(file_used(1),'ana');
			
			timebase=rtime*24*3600000; %%%% milliseconds %%%%
			thetime{1}=timebase;
			thetime{2}=timebase;
		end;
	
		filenames=get(xhand.filename,'string');
		f2f=[];
		thisunit='';
		for i=1:2
			dum=[3 5];
			f2f=[f2f filenames{mod(whichfile(dum(i),1),10)+1}(3:end) ', '];
			vari=strtok(mystr{dum(i)},' ,');
			if whichfile(dum(i),1)<10
				u=ncf(whichfile(dum(i),1)).file{vari}(goodindex{whichfile(dum(i),1)},:);
				dum=att(ncf(whichfile(dum(i),1)).file{vari});
				if ~isempty(dum)
					indx=find(strcmp(ncnames(dum),'units'));
					thisunit=spacebuster(dum{indx}(:));
				end;
			else
				u=xfnew(whichnew.ana(dum(i),1)).data(:,:);
			end;
			if overlap
				param{i}=interp1q(thetime{i},u,timebase);
			else
				param{i}=u;
			end;
			param{i}=dataclean(param{i}(:));
		end;
		f2f=f2f(1:end-2);
		eval([mystr{1} '=' num2str(mystr{2}) '*param{1}+' num2str(mystr{4}) '*param{2};']);
		eval(['temp=renew(' mystr{1} ',[mystr{1} ''_f2f''],-1);']);
		xfnew(temp).time=timebase/24/3600000;
		xfnew(temp).f2f=f2f;
		[xfnew(temp).attname,xfnew(temp).att]=newattrib([mystr{1} '_f2f'],xfnew(temp).data,file_used);
		xfnew(temp).att{3}=thisunit;
		set(xhand.newvarlist,'string',xf.newvarlist);
		set(xhand.notes,'string','Ready - Waiting for command...');
		set(xhand.newvarlist,'enable','on');
		
	case 15 % Bob Beardsly's tidal analysis
		for i=1:5
			mystr{i}=get(xhand.ana(i),'string');
			if isempty(spacebuster(mystr{i}))
				errordlg('Parameters need to be filled first!','Error');
				return;
			end;
		end;
		strvar=mystr{1};
		numvar=0;
		while ~isempty(strvar)
			numvar=numvar+1;
			[vari{numvar},strvar]=strtok(strvar,' ,');
		end;
		if length(vari)>2
			vari=vari(1:2);
		end;
		parm{1}=[];parm{2}=[];
		for i=1:length(vari),	
			[index,pick]=search(vari{i});
			if pick=='all',
				u=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
				tt=jtime{xnum.file};
				origfiles=xnum.file;
			elseif pick=='new',
				u=xfnew(index).data;
				if isempty(xfnew(index).time)
					tt=jtime{whereat(index)};
				else
					tt=xfnew(index).time;
				end;
				origfiles=whereat(index);
			else
				errordlg(msg,'Error');
				return;
			end;
			parm{i}=dataclean(u);
		end;
		if ~isempty(parm{2}) & length(parm{1})~=length(parm{2})
			errordlg('The length of the two variables must be equal!','Error');
			return;
		end;
		
		ylab='';
		newvnum=whichnew.ana(1,1);
		if newvnum==0 % variables not from the newwindow
			ylab=att(ncf(whichfile(1,1)).file{vari{1}});
			if ~isempty(ylab)
				indx=find(strcmp(ncnames(ylab),'units'));
				ylab=ylab{indx}(:);
			end;
		else
			ylab=xfnew(newvnum).attname;
			if ~isempty(ylab)
				indx=find(strcmp(ylab,'units'));
				ylab=xfnew(newvnum).att{indx};
			end;
		end;
		
		delt=str2num(mystr{2});
		tstart=str2num(mystr{3});
		latit=str2num(mystr{4});
		ray=str2num(mystr{5});
		tseris=parm{1}(:);
		if ~isempty(parm{2})
			tseris=parm{1}(:)+parm{2}(:)*sqrt(-1);
		end;
		if tstart(1)<100
			tstart(1)=1900+tstart(1);
		end;
		if length(tstart)<3
			tstart=[tstart 1 0];
		elseif length(tstart)<4
			tstart=[tstart 0];
		elseif length(tstart)>4
			tstart=tstart(1:4);
		end;
		
		[x1,x2,x3,x4]=tide2(tseris,delt,tstart,latit,ray);
		
		figure(xhand.figT);
		if ~isreal(x4)
			hdl=timeplt(tt,[real(tseris) real(x4) imag(tseris) imag(x4)],[1 1 2 2]);
		else
			hdl=timeplt(tt,[tseris,x4]);
		end;
		for i=1:length(hdl)
			newstr=strrep(vari{i},'_','\_');
			stacklbl(hdl(i),newstr,ylab);
			legend(hdl(i),'Original','Predicted');
		end;

	end; % switch method-1
	liststore{1}=xf.newvarlist;
	xfnewstore{1}=xfnew;
	whereatstore{1}=whereat;
	xcountstore{1}=xcount.new;

case 'startstop'
	if (get(xhand.analyzeit,'value')-1)==9	
		try
			numfile=str2num(get(xhand.ana(2),'string'));
		catch
			errordlg('Input in Filenumber field must be nuermicals separated by comma or space','Error');
			return;
		end;
		if length(numfile)>xcount.file
			errordlg('There aren''t so many files in the session!','Error');
			return;
		end;
		mintmin=1e35;maxtmax=0;
		for i=1:length(numfile)
			tmin=min(jtime{numfile(i)});
			tmax=max(jtime{numfile(i)});
			if tmin<mintmin
				mintmin=tmin;
			end;
			if tmax>maxtmax
				maxtmax=tmax;
			end;
		end;
		[ymd,hms]=getgregorian(mintmin);
		ymd=strrep(ymd,' - ','-'); hms=strrep(hms,' : ',':');
		set(xhand.ana(3),'fontsize',floor(8*ratiox),'string',[ymd '  ' hms]);
		[ymd,hms]=getgregorian(maxtmax);
		ymd=strrep(ymd,' - ','-'); hms=strrep(hms,' : ',':');
		set(xhand.ana(4),'fontsize',floor(8*ratiox),'string',[ymd '  ' hms]);
	end;

case 'titlab1' % Fill the title and ylabel fileds if avilable
	fillvoid(1,'keybd');
case 'titlab2'
	fillvoid(2,'keybd');
case 'titlab3'
	fillvoid(3,'keybd');
case 'titlab4'
	fillvoid(4,'keybd');
	
case 'plot_fdomain'
	panels=(get(xhand.graphit,'value') - 1);
	switch panels
	case 1 
		myplt='loglog';
	case 2
		myplt='semilogy';
	case 3
		myplt='semilogx';
	case 4
		myplt='plot';
	end;
	oldfname=[];
	filename=get(xhand.filename,'string');
	varia=get(xhand.varpanedit(1),'string');
	if isempty(varia)
		errordlg('Parameters need to be filled first!','Error');
		return;
	end;
	i=0;temp=varia;
	while ~isempty(varia)
		i=i+1;
		[t{i},varia]=strtok(varia,' ,');
	end;
	files=i;
	varia=temp;
	switch isempty(findstr(varia,'_specx'))
	case 0 %cross-spectra
		if files>1
			errordlg('Cross-spectrum can only be plotted one at a time.','Error');
			return;
		end;
		temp=varia(1:findstr(varia,'_specx')-1);
		if whichnew.graph(1)>0
			fnum=xfnew(whichnew.graph(1)).files;%whereat(whichnew.graph(1));
			myspec=xfnew(whichnew.graph(1)).data;
			myfreq=xfnew(whichnew.graph(1)).freqx;
		elseif whichnew.graph(i)==0
			fnum=xnum.file;
			myspec=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
			myfreq=xfile{[temp xtail]}(goodindex{xnum.file},:);
		else
			errordlg('Variable not found','Error');
			return;
		end;

		cols=[1 2 4 5];
		xlab={' ',' ','Frequency, Hz','Frequency, Hz'};
		ylab={'PSD, unit/Hz','PSD, unit/Hz','Phase, deg.',' '};
		junk=findstr(temp,'xx');
		tit={temp(1:junk-1),temp(junk+2:end),'Phase','Coherence'};
		figure(xhand.figF);
		set(xhand.figF,'name','FDomain Plot');
		set(xhand.notes,'string','Plotting Spectra...');
		for i=1:4
			subplot(2,2,i);
			ydata=real(myspec(:,cols(i)));
			if i<3
				ydata=[ydata ydata-real(myspec(:,i+5)) ydata+real(myspec(:,i+5))];
			end;
			if i==3
				ydata=angle(ydata)*180/pi;
			end;
			thisplt=myplt;
			if ~isempty(find(ydata<0))
				if strcmpi(myplt,'loglog')
					thisplt='semilogx';
				elseif strcmpi(myplt,'semilogy')
					thisplt='plot';
				end;
			end;
			eval(['handles=' thisplt '(myfreq,ydata);']);
			set(handles(1),'linewidth',2);
			if i<3
				set(handles(2),'color','g','linestyle',':');
				set(handles(3),'color','g','linestyle',':');
			end;
			xlabel(xlab{i});
			ylabel(ylab{i});
			text(.7,.9,tit{i},'units','normalized');
			if i<3
				fname=filename{fnum(i)+1};
				[junk,fname]=strtok(fname,' ');
				junky=strrep(fname,'_','\_');
				title(junky);
			end;
% 			if strcmpi(oldfname,fname)==0
% 				junky=strrep(fname,'_','\_');
% 				title(junky);
% 				oldfname=fname;
% 			end;
		end;
		set(xhand.notes,'string','Ready - Waiting for command...');
	
	case 1 %autospectra, xcov and xcorr
		figure(xhand.figF);
		set(xhand.figF,'name','Fdomain Plot');
		set(xhand.notes,'string','Plotting Spectra...');
		for i=1:files
			xlab='Lag, Sec.';
			if ~isempty(findstr(t{i},'_spec'))
				mytail='_spec';xtail='freq';
				xlab='Frequency, Hz';
				ylab='PSD, unit/Hz';
			elseif ~isempty(findstr(t{i},'_cov'))
				mytail='_cov';xtail='lag';
				ylab='Covarience';
			elseif ~isempty(findstr(t{i},'_corr'))
				mytail='_corr';xtail='lag';
				ylab='Correlation';
			else
				errordlg('Variable does not have spectra data.','Error');
				close(3);
				set(xhand.notes,'string','Ready - Waiting for command...');
				return;
			end;
			temp=t{i}(1:findstr(t{i},mytail)-1);
			tit=strrep(temp,'xx',' - ');
			if whichnew.graph(i)>0
				fnum=xfnew(whichnew.graph(i)).files;%whereat(whichnew.graph(i));
				myspec=xfnew(whichnew.graph(i)).data;
				eval(['myfreq=xfnew(whichnew.graph(i)).' xtail ';']);
			elseif whichnew.graph(i)==0
				fnum=xnum.file;
				myspec=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
				myfreq=xfile{[temp xtail]}(goodindex{xnum.file},:);
			else
				errordlg('Variable not found','Error');
				return;
				set(xhand.notes,'string','Ready - Waiting for command...');
			end;
			if strcmpi(mytail,'_spec')
				myspec=[myspec(:,1) myspec(:,1)-myspec(:,2) myspec(:,1)+myspec(:,2)];
			end;
			fname=filename{fnum+1};
			[junk,fname]=strtok(fname,' ');

			subplot(files,1,i);
			eval(['handles=' myplt '(myfreq,myspec);']);
			set(handles(1),'linewidth',2);
			if strcmpi(mytail,'_spec')
				set(handles(2),'color','g','linestyle',':');
				set(handles(3),'color','g','linestyle',':');
			end;
			xlabel(xlab);ylabel(ylab);
			text(.7,.9,tit,'units','normalized');
			
			fname=filename{fnum+1};
			[junk,fname]=strtok(fname,' ');
			junky=strrep(fname,'_','\_');
			title(junky);
			
% 			if strcmpi(oldfname,fname)==0
% 				junky=strrep(fname,'_','\_');
% 				title(junky);
% 				oldfname=fname;
% 			end;
		end;
		set(xhand.notes,'string','Ready - Waiting for command...');
	end; % switch
	
case 'adcpview'
	ustr=spacebuster(get(xhand.ana(1),'string'));
	vstr=spacebuster(get(xhand.ana(2),'string'));
	dummy=[~isempty(ustr),~isempty(vstr)];
	if ~all(dummy),
		errordlg('Parameters need to be filled first!','Error');
		return;
	end;
	[index,pick]=search(ustr);
	if pick=='all',
		u=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
	elseif pick=='new',
		u=xfnew(index).data;
	else
		errordlg(msg,'Error');
		return;
	end;
	[index,pick]=search(vstr);
	if pick=='all',
		v=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
		origfiles=xnum.file;
	elseif pick=='new',
		v=xfnew(index).data;
		origfiles=whereat(index);
	else
		errordlg(msg,'Error');
		return;
	end;
	if size(u,2)<=1 | size(v,2)<=1
		errordlg('Not a data of ADCP velocity profile...','Error');
		return;
	end;	
	rtime=timeloading(whichfile(1,1),'ana');
	viewadcp(rtime,u,v);
	
case 'plot_scatter'
	global oldscat
	ustr=spacebuster(get(xhand.ana(1),'string'));
	vstr=spacebuster(get(xhand.ana(2),'string'));
	dummy=[~isempty(ustr),~isempty(vstr)];
	if ~all(dummy),
		errordlg('Parameters need to be filled first!','Error');
		return;
	end;
	[index,pick]=search(ustr);
	if pick=='all',
		u=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
	elseif pick=='new',
		u=xfnew(index).data;
	else
		errordlg(msg,'Error');
		return;
	end;
	[index,pick]=search(vstr);
	if pick=='all',
		v=xfile{xf.varlist{index}}(goodindex{xnum.file},:);
		origfiles=xnum.file;
	elseif pick=='new',
		v=xfnew(index).data;
		origfiles=whereat(index);
	else
		errordlg(msg,'Error');
		return;
	end;
	isadcp=0;
	if size(u,2)>1 | size(v,2)>1
		whichbin=inputdlg('Bin(s) to plot (One bin at a time):',...
						'Input Bin Number',1,{'[1]'});
		whichbin=str2num(char(whichbin));
		isadcp=1;
		if isempty(whichbin)
			errordlg('Bin number out of range','Error');
			return;
		elseif length(whichbin)>1
			errordlg('Plot ONE bin at a time, please','Error');
			return;
		elseif min(whichbin)<=0 | max(whichbin)>size(u,2)
			errordlg('Bin number out of range','Error');
			return;
		end;
		initialplot=1;
	else
		whichbin=1;
	end;	
	u=u(:,whichbin);
	v=v(:,whichbin);
	if ~(length(u)==length(v)),
		errordlg('The two variables have different lengthes!','Error');
		return;
	end;
	u=dataclean(u);
	v=dataclean(v);

	figure(xhand.figF);
	set(xhand.figF,'name','Scatter Plot');
	scat=2-get(xhand.checkbox,'value');
	if ~initialplot
		if oldscat~=scat
			initialplot=1;
		end;
	end;
	if initialplot
		clf;
		indx=find(isnan(u)==0);u=u(indx);v=v(indx);
		indx=find(isnan(v)==0);u=u(indx);v=v(indx);
		
		axislimit=pca(u,v,scat);
		oldscat=scat;
		filenames=get(xhand.filename,'string');
		fnum=whichfile(1,whichfile(1,:)>0);
		fnum=mod(fnum,10);
		if length(fnum)==1
			[junk,filetit]=strtok(filenames{fnum+1},' ');
		end;
		title(strrep(filetit,'_','\_'));
		xlabel(strrep(ustr,'_','\_'));ylabel(strrep(vstr,'_','\_'));
		if isadcp
			text(0.1*axislimit,0.85*axislimit,['Bin # ' num2str(whichbin)]);
		end;
		set(xhand.ylimedit(5),'visible','on',...
			'Position',[250 200 70 20].*ratioxy,...
			'string',['-' num2str(axislimit) ', ' num2str(axislimit)]);
		set(xhand.plotheader(5),'visible','on',...
			'Position',[250 220 70 10].*ratioxy,...
			'string','Axis Limits');
		initialplot=0;
	else
		temp=get(xhand.ylimedit(5),'string');
		try
			ylim=str2num(temp);
		catch
			errordlg('Likely a typo in Ylim!','Error');
			return;
		end;
		if ylim(1)>=ylim(2)
			errordlg('Ylim(1) should always be less than Ylim(2)!','Error');
			return;
		end;
		axis([ylim(1) ylim(2) ylim(1) ylim(2)]);
	end;
	
case 'plot'
	if xslide.from >= xslide.to,
		warndlg('Things can''t END before it BEGIN! Check the sliders.','Warning');
		return;
	end;
	msg_plot={'There has been an error or errors in plotting!',...
	'Hints:',...
	'1. Check your spelling.',...
	'2. If there are more than one variable in a subplot,',...
	'   variables need to be separated by commas or spaces.',...
	'3. Vector plots should be represented as ''[A, B]''.',...
	'4. Dimensions of variables and time should agree.'};
	panels=(get(xhand.graphit,'value') - 1);
	for ik=1:panels,
		eval(['var' num2str(ik) '=get(xhand.varpanedit(ik),''string'');']);
		eval(['dummy(' num2str(ik) ')=~isempty(var' num2str(ik) ');']);
	end;
	if ~all(dummy),
		errordlg('Parameters need to be filled first!','Error');
		return;
	end;
%%%
	junk=whichfile;
	file_used=junk(junk>0);

	numberoffiles=length(file_used);
	if numberoffiles>1
		tempf=sort(file_used);
		tempf=diff(tempf);
		nzeros=length(find(tempf==0));
		numberoffiles=numberoffiles-nzeros;
	end;
%%%
% 	ana_items=length(get(xhand.analyzeit,'string'));
% 	file_used=[];
% 	for i=[1:xcount.file,11:ana_items*10]
% 		if any(find(whichfile==i))
% 			file_used=[file_used i];
% 		end;
% 	end;
% 	numberoffiles=length(file_used);

	if isempty(file_used)
		return;
	elseif numberoffiles>1 % multiple files, timebase problem needs to be dealt with

		[overlap,endmin,endmax,minmax,maxdeltat,thetime]=isoverlap(file_used,'graph');
		
		if overlap
			timebase=endmin : maxdeltat : endmax;
			timebase=timebase(:);
			global xx;
			xx=timebase;
		else
			timebase=[];
			minmax=sort(minmax);
			for i=1:numberoffiles
				timebase=[timebase minmax(i,1):maxdeltat:minmax(i,2)];
			end;
			timebase=timebase(:);
			
		end;
	else   % single file, so there is no timebase problem
		overlap=0;
		
		rtime=timeloading(file_used(1),'graph');
		
		timebase=rtime*24*3600000; %%%% milliseconds %%%%		
		thetime{1}=timebase;
	end;

	ydata=[];
	panum=[];
	for ik=1:panels,
		eval(['[t,s]=strtok(var' num2str(ik) ',''[]'');']);
		switch isempty(spacebuster(s))
		case 1 % Line plots
			stickplot=0;			
			kk=0;
			while ~isempty(t)
				kk=kk+1;
				[vari{kk},t]=strtok(t,' ,');
			end;
			numberofvar(ik)=kk;
			cols=[];
			for jk=1:kk
				if whichfile(ik,jk)==0
					errordlg('Error in input, likely a typo.','Error');
					return;
				end;
				try
					if whichfile(ik,jk)<10
						u=ncf(whichfile(ik,jk)).file{vari{jk}}(goodindex{whichfile(ik,jk)},:);
					else
						u=xfnew(whichnew.graph(ik,jk)).data(:,:);
					end;
				catch
					errordlg({'Error in typing....',...
						'Hint: Blank the field, press RETURN, then type.',...
						'  or  Start all over by clicking GraphIt.',...
						'  Avoid typing, use mouse.'},'Error');
					return;
				end;
				adcpvar=0;
				cols=[cols size(u,2)];
				if ~isempty(diff(cols)) & any(diff(cols))
					errordlg('The number of colums of the variables must be the same.','Error');
					return;
				end;
				if size(u,2)>1
					adcpvar=1;
				end;
				if size(u,2)>1 & ~binasked
					whichbin=inputdlg('Which bin(s) do you want to plot:',...
									'Input Bin Number',1,{'[1]'});
					whichbin=str2num(char(whichbin));
					if isempty(whichbin)
						errordlg('Bin number out of range','Error');
						binasked=0;
						return;
					end;
						
					if min(whichbin)<=0 | max(whichbin)>size(u,2)
						errordlg('Bin number out of range','Error');
						binasked=0;
						return;
					end;
					binasked=1;
				end;
				u=u(:,whichbin);
				if numberoffiles>1
					timeid=find(file_used==whichfile(ik,jk));
					if overlap
% 						u=interp1(thetime{timeid},u,timebase,'*linear');
						u=interp1q(thetime{timeid(1)},u,timebase);
					else
						v=nan*ones(length(timebase),size(u,2));
						index=find(timebase>=min(thetime{timeid(1)}) & timebase<=max(thetime{timeid(1)}));
% 						v(index,:)=u;
% 						v(index,:)=interp1(thetime{timeid},u,timebase(index),'*linear');
						v(index,:)=interp1q(thetime{timeid(1)},u,timebase(index));
						u=v;
					end;
				end;
				try
					ydata=[ydata u];
					panum=[panum ik*ones(size(whichbin))];
				catch
	% 				errordlg(msg_plot,'Error');
					errordlg(lasterr,'Error');
					return;
				end;
			end; % for jk=

			if adcpvar & panels==1
				panum=[];junkk=[];
				numberofbins=length(whichbin);
				for numindx=1:numberofbins
					panum=[panum numindx*ones(1,kk)];
					for numindx2=1:kk
						junkk=[junkk (numindx2-1)*numberofbins+numindx];
					end;
				end;
				tempdata=ydata(:,junkk);
				ydata=tempdata;
			end;
		case 0 % stick plots
			stickplot=1;
			if whichfile(ik,1)~=whichfile(ik,2)
				errordlg({'Vector plot must be in the form of [U, V]',...
					'Both U and V must be from the same file'},...
					'Error');
				return;
			end;
			[vari{1},t]=strtok(t,' ,');
			vari{2}=strtok(t,' ,');
			numberofvar(ik)=2;

			if whichfile(ik,1)<10
				realu=ncf(whichfile(ik,1)).file{vari{1}}(goodindex{whichfile(ik,1)},:);
			else 
				realu=xfnew(whichnew.graph(ik,1)).data(:,:);
			end;
			if whichfile(ik,2)<10
				imagu=ncf(whichfile(ik,2)).file{vari{2}}(goodindex{whichfile(ik,1)},:);
			else 
				imagu=xfnew(whichnew.graph(ik,2)).data(:,:);
			end;
			adcpvar=0;
			if size(realu,2)>1
				adcpvar=1;
			end;
			if size(realu,2)>1 & ~binasked
				whichbin=inputdlg('Which bin do you want to plot:',...
								'Input Bin Number',1,{'[1]'});
				whichbin=str2num(char(whichbin));
					
				if min(whichbin)<=0 | max(whichbin)>size(realu,2)
					errordlg('Bin number out of range','Error');
					binasked=0;
					return;
				end;
				binasked=1;
			end;
			realu=realu(:,whichbin);
			imagu=imagu(:,whichbin);
			if numberoffiles>1
				timeid1=find(file_used==whichfile(ik,1));
				timeid2=find(file_used==whichfile(ik,2));
				if overlap
% 					realu=interp1(thetime{timeid1},realu,timebase,'*linear');
% 					imagu=interp1(thetime{timeid2},imagu,timebase,'*linear');
					realu=interp1q(thetime{timeid1(1)},realu,timebase);
					imagu=interp1q(thetime{timeid2(1)},imagu,timebase);
				else
					realv=nan*ones(length(timebase),size(realu,2));
					index=find(timebase>=min(thetime{timeid1(1)}) & timebase<=max(thetime{timeid1(1)}));
					realv(index,:)=realu;
					realu=realv;
					realv=nan*ones(length(timebase),size(imagu,2));
					index=find(timebase>=min(thetime{timeid2(1)}) & timebase<=max(thetime{timeid2(1)}));
					realv(index,:)=imagu;
					imagu=realv;
				end;
			end;
			realu=dataclean(realu);
			imagu=dataclean(imagu);
			ycomplex=realu+imagu*sqrt(-1);
			try
				ydata=[ydata ycomplex];
				panum=[panum ik*ones(size(whichbin))];
			catch
% 				errordlg(msg_plot,'Error');
				errordlg(lasterr,'Error');
				return;
			end;
			
		end; % switch isempty
		tit{ik}=get(xhand.titpanedit(ik),'string');
		ylab{ik}=get(xhand.ypanedit(ik),'string');
		if isempty(ylab{ik})
			ylab{ik}='Y-unit';
			set(xhand.ypanedit(ik),'string',ylab{ik});
		end;
	end; % for ik
 
	timebase=timebase/3600000/24;  %%%% Julian days %%%%
		
	xdata=timebase;
	if initialplot
		xslide.from=min(xdata);
		xslide.to=max(xdata);		
		[ymd,hms]=getgregorian(xslide.from);
		set(xhand.zoomymdfrom,'visible','on','enable','on','string',ymd);
		set(xhand.zoomhmsfrom,'visible','on','enable','on','string',hms);
		[ymd,hms]=getgregorian(xslide.to);
		set(xhand.zoomymdto,'visible','on','enable','on','string',ymd);
		set(xhand.zoomhmsto,'visible','on','enable','on','string',hms);
		set(xhand.zoomslidefrom,'visible','on','enable','on','value',0);
		set(xhand.zoomslideto,'visible','on','enable','on','value',1);
		slideconfig(xdata);
	end;
	range=find(xdata>=xslide.from & xdata<=xslide.to);
	if length(xdata)~=length(ydata)
% 		display('we');errordlg(msg_plot,'Error');
		errordlg(lasterr,'Error');
		return;
	end;
	for ik=1:panels
		temp=get(xhand.ylimedit(ik),'string');
		if isempty(temp)
			ylim=[];
			break;
		else
			try
				ylim(ik,:)=str2num(temp);
			catch
				errordlg('Likely a typo in Ylim!','Error');
				return;
			end;
			if ylim(ik,1)>=ylim(ik,2)
				errordlg('Ylim(1) should always be less than Ylim(2)!','Error');
				return;
			end;
		end;
	end;
	set(xhand.notes,'string','Plotting TimeSeries...');
	ydata=dataclean(ydata);
	filenames=get(xhand.filename,'string');
	for ik=1:panels
		fnum=whichfile(ik,whichfile(ik,:)>0);
		fnum=mod(fnum,10);
		if length(fnum)==1
			[junk,filetit{ik}]=strtok(filenames{fnum+1},' ');
		else
			temp=[];
			for j=1:xcount.file
				if ~isempty(find(fnum==j))
					temp=[temp j];
				end;
			end;
			temp2=[];
			for j=1:length(temp)
				[junk,junk2]=strtok(filenames{temp(j)+1},' ');
				temp2=[temp2 ', ' junk2];
			end;
			filetit{ik}=temp2(3:end);
		end;
		eval(['teststr=var' num2str(ik) ';']);
% 		if whichfile(ik,1)>40 & whichfile(ik,1)<50
		if ~isempty(findstr(teststr,'_merg'))	
			filetit{ik}=xfnew(whichnew.graph(ik,1)).mergfrom;
		end;
% 		if whichfile(ik,1)>70 & whichfile(ik,1)<80
		if ~isempty(findstr(teststr,'_f2f'))	
			filetit{ik}=['Inter-file, ' xfnew(whichnew.graph(ik,1)).f2f];
		end;
		
		filetit{ik}=strrep(filetit{ik},'_','\_');
		tempstr{ik}='';
	end;
	
	realylim=ylim;
	realpanels=panels;
	realpanum=panum;
	
	if panels==1 & length(panum)>=numberofvar(panels)
		if stickplot
			panum=1:length(panum);
			realpanum=panum;
		else
			panum=1:length(panum)/numberofvar(panels);
% 			realpanum=[];
% 			for kkk=1:numberofvar(panels)
% 				realpanum=[realpanum panum];
% 			end;
		end;
		realylim=[];
		if ~isempty(ylim)
			for kkk=1:length(realpanum)
				realylim(kkk,:)=ylim;
			end;
		end;
		realpanels=length(panum);
		temp=tit{1};temp2=ylab{1};temp3=filetit{1};
		for kkk=1:realpanels
			if adcpvar
				tempstr{kkk}=['(Bin #' num2str(whichbin(kkk)) ')'];
			else
				tempstr{kkk}='';
			end;
			tit{kkk}=temp;
			ylab{kkk}=temp2;
			filetit{kkk}=temp3;
		end;
	elseif adcpvar & ~stickplot
		for kkk=1:panels
			if numberofvar(kkk)>1
				errordlg('Please use one-panel plot for inter-variable comparison','Error');
				return;
			end;
			tempstr{kkk}=tit{kkk};
			for jjj=1:length(whichbin)
				test{jjj}=['(Bin #' num2str(whichbin(jjj)) ')'];
			end;
			tit{kkk}=test;
		end;
	end;
   figure(xhand.figT);


   clf;
	handle=timeplt(xdata(range),ydata(range,:),realpanum,realylim);
	initialplot=0;
	for ik=1:realpanels
% 		stacklbl(handle(ik),tempstr{ik},ylab{ik});
		axes(handle(ik));
		ylabel(ylab{ik});
		if ~isempty(tempstr{ik})
			title([filetit{ik} ' - ' tempstr{ik}]);
		else
			title(filetit{ik});
		end;
		kx=0;
		dummy=tit{ik};
		if ~iscellstr(tit{ik})
			while ~isempty(dummy)
				kx=kx+1;
				[leg{kx},dummy]=strtok(dummy,',');
				leg{kx}=epicremover(leg{kx});
			end;
			
	 		legend(char(leg));
			clear leg;
		else
			legend(char(tit{ik}));
		end;
	end;
   for ik=1:panels
		temp=get(handle(ik),'ylim');
		ylimplot{ik}=[num2str(floor(temp(1))) ', ' num2str(ceil(temp(2)))];
		set(xhand.ylimedit(ik),'visible','on','string',ylimplot{ik} );
	end;
	pos=get(xhand.ylimedit(panels),'position');
	pos=pos(2);
	set(xhand.ylimheader,'position',[5 25+pos/ratioy 50 15/ratioy].*ratioxy,...
		'visible','on');
	set(xhand.notes,'string','Ready - Waiting for command...');

case 'save_fdomain'
	warndlg('Not implemented yet.','Notes');
	
case 'save'
% 	myflag=[];
% 	for i=1:xcount.save,
% 		if ~isempty(findstr(xf.savevarlist{i},'_'))
% 			dum=findstr('_',fliplr(xf.savevarlist{i}));
% 			thisindex=find(strcmpi(xf.savevarlist{i}(end-dum+1 : end),tflag)==1);
% 			if ~isempty(thisindex)
% 				myflag=tflag{thisindex};
% 			end;
% 			break;
% 		end;
% 		if ~isempty(myflag)
% 			break;
% 		end;
% 	end;
% 
% 	if isempty(myflag) | isempty(whichnew.save)
% 		xdata=jtime{xsave(1).file};
% 	else
% 		xdata=xfnew(whichnew.save(1,1)).time;
% 		if strcmpi(myflag,'_merg')
% 			mergfrom=xfnew(whichnew.save(1,1)).mergfrom;
% 		end;
% 		if strcmpi(myflag,'_f2f')
% 			f2f=xfnew(whichnew.save(1,1)).f2f;
% 		end;
%  	end;
	if initialsave
		if whichnew.save(1,1)==0
			xdata=jtime{xsave(1).file};
		else
			if ~isempty(xfnew(whichnew.save(1,1)).time)
				xdata=xfnew(whichnew.save(1,1)).time;
			else
				xdata=jtime{xsave(1).file};
			end;
			if ~isempty(findstr(xf.savevarlist{1},'_merg'))
				mergfrom=xfnew(whichnew.save(1,1)).mergfrom;
			end;
			if ~isempty(findstr(xf.savevarlist{1},'_f2f'))
				f2f=xfnew(whichnew.save(1,1)).f2f;
			end;
	 	end;
		timebase=xdata;
	
		xslide.from=min(xdata);
		xslide.to=max(xdata);
		askrange=questdlg('Specify time range of saved file?','???','No','Yes','No');
	else 
		askrange='No';
	end;
	if strcmpi(askrange,'Yes')
% 		initalsave=1;
		[ymd,hms]=getgregorian(min(xdata));
		set(xhand.zoomymdfrom,'visible','on','string',ymd);
		set(xhand.zoomhmsfrom,'visible','on','string',hms);
		[ymd,hms]=getgregorian(max(xdata));
		set(xhand.zoomymdto,'visible','on','string',ymd);
		set(xhand.zoomhmsto,'visible','on','string',hms);
		set(xhand.zoomslidefrom,'visible','on','enable','on','value',0);
		set(xhand.zoomslideto,'visible','on','enable','on','value',1);
		slideconfig(xdata);
		initialsave=0;
		return;
	else
		initialsave=0;
	end;
	
	xdata=timebase;
	range=find(xdata>=xslide.from & xdata<=xslide.to);
	if xslide.from >= xslide.to,
		warndlg('Things can''t END before it BEGIN! Check the sliders.','Warning');
		return;
	end;
	form=get(xhand.saveit,'value') - 1;
	switch form
	
	case 1 %ascii
		yformat=[];
		ydata=[];
		xdatag=gregorian(xdata(range));
		for i=1:xcount.save
			temp=xsave(i).data;
			temp2=size(temp,2);
			for j=1:temp2
				yformat=[yformat ' %8.4g'];
			end;
			
			if length(temp)<length(range);
				temp(end+1 : length(range),:)=nan;
			end;
			ydata=[ydata temp(range,:)];
		end;
		ydata(find(isnan(ydata)==1))=1e35;%-999999;

		[ascif,ascipath]=uiputfile('*.dat','Save as ASCII');
		if (ascif==0),
		% 	warndlg('No file is selected, try again...','Warning!');
			initialsave=1;
			return;
		end;
		ascif=[ascipath ascif];
		fid=fopen(ascif,'w');
		if fid<0,
			errordlg('The named file might be still open!','Error');
			return;
		end;
		set(xhand.notes,'string','Saving an ASCII file...');
		fprintf(fid,'%%********** Attributes from the parent file **************\n');
		for i=1:length(ncf(xsave(1).file).topattlist),
			field1=num2str(length(ncf(xsave(1).file).topattlist{i}));
			field2=num2str(length(ncf(xsave(1).file).topatt{i}(:,:)));
			eval(['fprintf(fid,''%% %' field1 's:%' field2 's\n'',ncf(xsave(1).file).topattlist{i},ncf(xsave(1).file).topatt{i}(:,:));']);
		end;
		fprintf(fid,'%%********** End of attributes from the parent file *******\n%%\n');
		fprintf(fid,'%% Variable_Number: %d\n',length(xf.savevarlist));
		fprintf(fid,'%% Variable_Name: ');
		for i=1:length(xf.savevarlist),
% 			fprintf(fid,'%s, ',xf.savevarlist{i});
			fprintf(fid,'%s ',xf.nicknames{i});
		end;
		fprintf(fid,'\n');
		fprintf(fid,'%% Variable_epic: \n');
		fprintf(fid,'%% %s\n',['Created using CMGTOOL on ' datestr(now)]);
		fprintf(fid,'%% --------------------------------------------------\n');
		fprintf(fid,'%% YY MM DD HH MM  SS ');
		for i=1:xcount.save
% 			fprintf(fid,'%8s',xf.savevarlist{i});
			fprintf(fid,'%9s',xf.nicknames{i});
			for j=2:size(xsave(i).data,2)
				fprintf(fid,'%9s',['(' num2str(j) ')']);
			end;
		end;
		fprintf(fid,'\n');
		timeformat=['%4d %2d %2d %2d %2d %3.1g '];
		fprintf(fid,[timeformat yformat '\n'],[xdatag';ydata']);
		set(xhand.notes,'string','Ready - Waiting for command...');
		fclose(fid);
		
	case 2 %mat file
		[ascif,ascipath]=uiputfile('*.mat','Save as Matlab file');
		if (ascif==0),
			initialsave=1;
			return;
		end;
		set(xhand.notes,'string','Saving an MATLAB file...');
		ascif=[ascipath ascif];
		time=xdata(range);
		allvar=[];
		for i=1:xcount.save
			temp=xsave(i).data;
			if length(temp)>length(range)
				temp=temp(range,:);
			end;
% 			eval([xf.savevarlist{i} '=temp;']);
% 			allvar=[allvar '''' xf.savevarlist{i} ''',']; %Went through this pain to accomadate the Desktop folder in Mac
			eval([xf.nicknames{i} '=temp;']);
			allvar=[allvar '''' xf.nicknames{i} ''',']; %Went through this pain to accomadate the Desktop folder in Mac
		end;
		allvar=allvar(1:end-1);
		eval(['save(ascif,''time'',' allvar ');']);
		set(xhand.notes,'string','Ready - Waiting for command...');
		
	case 3 %netCDF
		global array tarray
		load epickey.mat; % a .mat file contains info for the epic code.
		for i=1:xcount.save,
% 			array(i).name=xf.savevarlist{i};
			array(i).name=xf.nicknames{i};
			temp=xsave(i).data;
			rows(i)=size(temp,1);
			cols(i)=size(temp,2);
			
			if min(size(temp))>1 & strcmpi(computer,'MAC2')==1
				errordlg('Can''t save metrix into netCDF file YET! Stay Tuned.','Error');
				return;
			end;
			if length(temp)>length(range)
				temp=temp(range,:);
			end;
			temp(find(isnan(temp)==1))=-999999;%1e35;
			array(i).value=temp;
			array(i).yes=0;
			strflag={'_filt','_r','_avg','_sub','_merg','_f33','_f2f'};

			tempy=ncf(xsave(1).file).varlist;
			if whichnew.save(i)==0
				test=find(strcmpi(tempy,array(i).name)==1);
				array(i).att=att(ncf(xsave(1).file).file{ncf(xsave(1).file).varlist{test}});
				array(i).attnames=ncnames(array(i).att);
			else
				array(i).att=xfnew(whichnew.save(i)).att;
				array(i).att{2}=xf.nicknames{i};
				array(i).attnames=xfnew(whichnew.save(i)).attname;
			end;
			[headstr,tailstr{i}]=strtok(array(i).name,'_');
			array(i).name=headstr;
				
		end;
		
		tarray(1).epic=624; %time -- julian days
		tarray(1).name='time';
		tarray(1).value=floor(xdata(range));
		tarray(1).yes=100;
		tarray(2).epic=624; %time2 -- millisec since midnight
		tarray(2).name='time2';
		tarray(2).value=(xdata(range)-floor(xdata(range)))*24*3600000;
		tarray(2).yes=100;
		num_rows=length(tarray(1).value);
		scalar(1).name='Lat';
		scalar(2).name='Lon';
		scalar(3).name='Depth';
		
		scalar(1).epic=500;
		scalar(2).epic=502;
		scalar(3).epic=3;
		
		for i=1:3
			temp=find(strcmpi(scalar(i).name,ncf(xsave(1).file).varlist)==1);
			if ~isempty(temp)
				scalar(i).value=ncf(xsave(1).file).file{temp}(:);
			else 
				scalar(i).value=-999999;%1e35;
			end;
		end;
				
		% create the netCDF file
		ncmex ( 'SETOPTS', 0 );
		[ascif,ascipath]=uiputfile('*.cdf','Save as netCDF');
		if (ascif==0),
		% 	warndlg('No file is selected, try again...','Warning!');
			initialsave=1;
			return;
		end;
		ascif=[ascipath ascif];
		ncid = ncmex ( 'CREATE', ascif, 'NC_CLOBBER' );
		if ( ncid == -1 )
			errordlg('The named file couldn''t be created!','Error');
			return;
		end;
	
		set(xhand.notes,'string','Saving an netCDF file...');
		
		% dimension definition
		ncmex ( 'DIMDEF', ncid, 'scalar',1 );
		ncmex ( 'DIMDEF', ncid, 'rows', 'UNLIMITED' );
		
		[sid rcode]=ncmex('DIMID',ncid,'scalar');
		for i=1:3,% vardef--scalar
			sdef=ncmex('VARDEF', ncid, scalar(i).name, 'FLOAT', 1,sid);
		end;
		[tid rcode]=ncmex('DIMID',ncid,'rows');
		for i=1:2,
			tdef=ncmex('VARDEF', ncid, tarray(i).name, 'LONG', 1, tid);
		end;
		
		for i =1:xcount.save,% vardef--array
			[m,n]=size(array(i).value);
			if m<num_rows
				hh=ncmex('DIMDEF', ncid, 'rows3',m);
				[dimid3(i) rcode]=ncmex('dimid',ncid,'rows3');
				if n>1
					hh=ncmex('DIMDEF',ncid,'cols',n);
					[dimid2 rcode]=ncmex('dimid',ncid,'cols');
					hh=ncmex('VARDEF', ncid, array(i).name, 'float', 2, [dimid3(i) dimid2]);
				else
					hh=ncmex('VARDEF', ncid, array(i).name, 'float', 1, dimid3(i));
		      end;
		   else   
				if n>1
					hh=ncmex('DIMDEF',ncid,'cols',n);
					[dimid2 rcode]=ncmex('dimid',ncid,'cols');
					hh=ncmex('VARDEF', ncid, array(i).name, 'float', 2, [tid dimid2]);
				else
					hh=ncmex('VARDEF', ncid, array(i).name, 'float', 1, tid);
				end;
		   end;
				
		end;
	
		% global attributes
		attnames=ncnames(ncf(xsave(1).file).topatt);
		for i=1:length(attnames);
			attnames{i}=strrep(attnames{i},char(10),'');
		end;
		for i=1:length(ncf(xsave(1).file).topatt),
			temp=ncf(xsave(1).file).topatt{i}(:);
			indxx=findstr(temp,'\0');
			temp(indxx:end)=[];
			status =ncmex('ATTPUT',ncid,'GLOBAL',attnames{i},'CHAR',...
			length(temp),temp);
		end;
		addition=['Edited using CMGTOOL on ' datestr(now)];
		status =ncmex('ATTPUT',ncid,'GLOBAL','notes','CHAR',...
		length(addition),addition);
		
% 		load epickey.mat; % a .mat file contains info for the epic code.
		temp={'name','long_name','generic_name','units','Fortran_format','other'};
		
		% attput the scalars
		for i=1:3,
			ncmex('ATTPUT',ncid,scalar(i).name,'epic_code','LONG',1,scalar(i).epic);
			for j=1:length(temp),
				test=eval(['epic_att(scalar(i).epic).' temp{j}]);
				ncmex('ATTPUT',ncid,scalar(i).name,temp{j},'CHAR',length(test),test);
			end;
		end;
	
		for i = 1:2,% attput the time arrays
			ncmex('ATTPUT',ncid,tarray(i).name,'epic_code','LONG',1,tarray(i).epic);
			for j=1:length(temp),
				eval(['test=epic_att(tarray(i).epic).' temp{j} ';']);
				ncmex('ATTPUT',ncid,tarray(i).name,temp{j},'CHAR',length(test),test);
			end;
		end;
		
		for i = 1:xcount.save,% attput the arrays
% 			if array(i).yes>=100,
			for j=1:length(array(i).attnames),
				if ~ischar(array(i).att{j}(:)),
					status=ncmex('ATTPUT',ncid,array(i).name,array(i).attnames{j},'LONG',...
					length(array(i).att{j}(:)),array(i).att{j}(:));
				else	
					status=ncmex('ATTPUT',ncid,array(i).name,array(i).attnames{j},'CHAR',...
					length(array(i).att{j}(:)),array(i).att{j}(:));
				end;
			end;
% 			end;
			
			switch array(i).yes
			case {1, 6}
				ncmex('ATTPUT',ncid,array(i).name,'notes','CHAR',8,'FILTERED');
			case 2
				ncmex('ATTPUT',ncid,array(i).name,'notes','CHAR',7,'ROTATED');
			case 3
				ncmex('ATTPUT',ncid,array(i).name,'notes','CHAR',8,'AVERAGED');
			case 4
				ncmex('ATTPUT',ncid,array(i).name,'notes','CHAR',10,'SUBSAMPLED');
			case 5
				mergfrom=['Merged from ' mergfrom];
				len=length(mergfrom);
				ncmex('ATTPUT',ncid,array(i).name,'notes','CHAR',len,mergfrom);
			case 7
				f2f=['Calculated from ' f2f];
				len=length(f2f);
				ncmex('ATTPUT',ncid,array(i).name,'notes','CHAR',len,f2f);
			end; % switch array(i).yes
			
% 			if ~isempty(tailstr{i})
% 				ncmex('ATTPUT',ncid,array(i).name,'processed_with','CHAR',...
% 					length(tailstr{i}),tailstr{i});
% 			end;
		end; % for attput array
		
		% end definitions
		hh=ncmex ( 'ENDEF', ncid );
		
		for i=1:3,% varput the scalars
			sput=ncmex('VARPUT1',ncid,scalar(i).name,[0],scalar(i).value);
		end;
	
		for i = 1:2,% varput the time arrays
			tput=ncmex('VARPUT',ncid,tarray(i).name,0,num_rows,tarray(i).value);
		end
	
		for i=1:xcount.save,% varput the arrays
		   [m,n]=size(array(i).value);
		   if m<num_rows
		      for j=1:n
		         hh=ncmex('VARPUT',ncid,array(i).name,[0 j-1],[m 1],array(i).value(:,j));
		      end;
			else   
		      for j=1:n
		         hh=ncmex('VARPUT',ncid,array(i).name,[0 j-1],[num_rows 1],array(i).value(:,j));
		      end;
			end;
		end;
	
		% close out
		ncmex ( 'CLOSE', ncid );
		set(xhand.notes,'string','Ready - Waiting for command...');
		
	end; %switch form
	initialsave=1;
end; % switch

return;


function [t]=varifieldconfig(num,varia)
% create the parameter whichnew and whichfile after typing variables in analyzing fields.
global whichnew whichfile whereat xnum tflag

if ~iscell(varia)
	i=0;
	while ~isempty(varia)
		i=i+1;
		[t{i},varia]=strtok(varia,' ,');
	end;
else
	t=varia;
	i=length(t);
end;
j=length(find(whichfile(num,:)>0));
if i>j
	for kk=j+1 : i
		[indx,pick]=search(t{kk});
		if pick=='all'
			whichfile(num,kk)=xnum.file;
			whichnew.ana(num,kk)=0;
		elseif pick=='new'
			whichnew.ana(num,kk)=indx;
			whichfile(num,kk)=10+whereat(indx);
			
			dum=findstr('_',fliplr(t{kk}));
			if ~isempty(dum)
				thisindex=find(strcmpi(t{kk}(end-dum+1 : end),tflag)==1);
				if ~isempty(thisindex)
					suffixstr=tflag{thisindex};
				end;
			end;
% 			for ijk=1:length(tflag)
% 				dum=length(tflag{ijk})-1;
% 				if strcmpi(t{kk}(end-dum : end),tflag{ijk})
% 					suffixstr=tflag{ijk};
% 					break;
% 				end;
% 			end;
			
			if strcmpi(suffixstr,'_avg')
				whichfile(num,kk)=20+whereat(indx);
			elseif strcmpi(suffixstr,'_sub')
				whichfile(num,kk)=30+whereat(indx);
			elseif strcmpi(suffixstr,'_merg')
				whichfile(pan,i+1)=40+whereat(whichnew.ana(pan,i+1));
			elseif strcmpi(suffixstr,'_f33')
				whichfile(pan,i+1)=50+whereat(whichnew.ana(pan,i+1));
			elseif strcmpi(suffixstr,'_filt')
				whichfile(pan,i+1)=60+whereat(whichnew.ana(pan,i+1));
			elseif strcmpi(suffixstr,'_f2f')
				whichfile(pan,i+1)=70+whereat(whichnew.graph(pan,i+1));
			elseif strcmpi(suffixstr,'_fh')
				whichfile(pan,i+1)=80+whereat(whichnew.graph(pan,i+1));
			elseif strcmpi(suffixstr,'_brdg')
				whichfile(pan,i+1)=90+whereat(xnum.newvarlist);
			end;
		end;
	end;
elseif j>i
	whichfile(num,i+1 : j)=0;
	whichnew.ana(num,i+1)=0;
end;
return;

function newstr=quotebuster(oldstr)
% get rid of () [] and {}
if ~isempty(findstr(oldstr,'('))
	oldstr=strrep(oldstr,'(','_');	
	oldstr=strrep(oldstr,')','_');
end;
if ~isempty(findstr(oldstr,'['))
	oldstr=strrep(oldstr,'[','_');	
	oldstr=strrep(oldstr,']','_');
end;
if ~isempty(findstr(oldstr,'{'))
	oldstr=strrep(oldstr,'{','_');	
	oldstr=strrep(oldstr,'}','_');
end;
newstr=oldstr;

return;

function mydata=dataclean(mydata);
mydata(mydata>1e15)=nan;
mydata(mydata<-1e15)=nan;
mydata(mydata==-999999)=nan; %for ADCP file (_FillValue)
mydata(mydata==999999)=nan;
mydata(mydata==-9999)=nan; %for ADCP file (_FillValue)
mydata(mydata==9999)=nan;
return;

function mydata=nanbuster(mydata);
% remove all NaN, used in Statistics calculations
mydata=mydata(:);
if size(mydata,2)==1 %not work on matrices
	index=find(isnan(mydata)==1);
	mydata(index)=[];
end;
return;


function [overlap,endmin,endmax,minmax,maxdeltat,thetime]=isoverlap(myfiles,tail);
% check overlap when multiple files are involved in calculations
global jtime whichnew whichfile xfnew

mm=length(myfiles);
for i=1:mm
	rtime=timeloading(myfiles(i),tail);
		
	thetime{i}=rtime*24*3600000.; %%%% milliseconds %%%%
	jdiff{i}=diff(thetime{i});
	minmax(i,:)=[min(thetime{i}), max(thetime{i})];
	deltat(i)=round(mean(jdiff{i}));
end;
endmin=min(min(minmax));
endmax=max(max(minmax));
if any(diff(deltat))
	maxdeltat=max(deltat);
else
	maxdeltat=deltat(1);
end;
overlap=0;
for j=1:mm-1
	for i=j+1 : mm
		overlaptest=find(thetime{i}>minmax(j,1) & thetime{i}<minmax(j,2));
		if ~isempty(overlaptest)
			overlap=1;
			break;
		end;
	end;
	if overlap
		break;
	end;
end;
return;

function rtime=timeloading(onefile,tail);
%load time variables...
global jtime whichfile whichnew xfnew

% if onefile<20
% 	if onefile>10
% 		temp=onefile-10;
% 	else
% 		temp=onefile;
% 	end;
% 	rtime=jtime{temp};
% else
% 	[xx,yy]=find(whichfile==onefile);
% 	eval(['temp=whichnew.' tail '(xx(1),yy(1));']);
% 	rtime=xfnew(temp).time;
% end;

[xx,yy]=find(whichfile==onefile);
eval(['tempthis=whichnew.' tail '(xx(1),yy(1));']);
if tempthis==0
	rtime=jtime{mod(onefile,10)};
	return;
else
	if ~isempty(xfnew(tempthis).time)
		rtime=xfnew(tempthis).time;
	else
		rtime=jtime{mod(onefile,10)};
	end;
end;

return;

function noepic=epicremover(withepic)
% to remove the epic code from the new variables

noepic=withepic;
indx=findstr(withepic,'_');
if ~isempty(indx)
	if length(indx)>1
		subj=withepic(indx(1)+1 : indx(2) -1);
	else
		subj=withepic(indx(1)+1 : end);
	end;
	if ~isempty(str2num(subj)) & isreal(str2num(subj))
		noepic=[withepic(1: indx(1)-1) withepic(indx(1)+2+length(subj) : end)];
	end;
else
	noepic=withepic;
end;
if strcmp(noepic(end),'\')
	noepic(end)=[];
end;
return;

function [attnames,attrib]=newattrib(varname,vari,orig_f)

% To generate attributes for new variables
global xhand ncf fdomain

attnames={'epic_code','name','units','minimum',...
	'maximum','original_files','processed_with'};
	
orig_f=mod(orig_f,10);
[headstr,tailstr]=strtok(varname,'_');
attrib{1}='-999';
attrib{7}=tailstr;
if fdomain
	attrib{2}=varname;
	[headstr,tailstr]=strtok(headstr,'xx');
else
	attrib{2}=headstr;
end;
attrib{3}=' ';
indx=find(isnan(vari)==0);
attrib{4}=min(vari(indx));
attrib{5}=max(vari(indx));
ofiles=[];
fstr=get(xhand.filename,'string');
for i=1:length(orig_f)
	ofiles=[ofiles ',' fstr{orig_f(i)+1}(4:end)];
end;
attrib{6}=ofiles(2:end);
tempy=ncf(orig_f(1)).varlist;
for i=1:length(tempy)
	tempy{i}=epicremover(tempy{i});
end;
test=find(strcmp(tempy,headstr)==1);
if ~isempty(test)
	dum=att(ncf(orig_f(1)).file{test(1)});
	if ~isempty(dum)
		indx=find(strcmp(ncnames(dum),'units'));
		attrib{3}=spacebuster(dum{indx}(:));
		if fdomain
			attrib{3}=['[' attrib{3} ']^2 / Hz'];
		end;
	end;
end;
	

return;

function newspd=speed10(spd,ht)

% m file adjusts wind speed to 10-m height, 
% based on Large and Pond, J.P.O, 11, 324-336, 1981. 
% drag coefficient is function of 10-m height wind, 
% iteration used to arrive at 10-m wind, 
% Sept 1996 CED

if(ht==10)
	newspd=spd;
	return
else
end
%	guess at wind speed at 5 m
%
newspd=5;
for i=1,20;
	%	close in 20 steps or set = NaN
	%
	if(i>=20)
		newspd=nan;
		return
	else
		wind10=newspd;
	end
	%
    if(wind10<11.0)
		coefdrag=1.205e-03;
	else
		coefdrag=(0.49+(0.065*wind10))*1.0e-03; 
	end
	dragadj=1+log(ht/10.0)*sqrt(coefdrag)/0.41; 
	newspd=spd./dragadj;
	if(abs(wind10-newspd)<=0.020000)
		return
	else
	end
end
