function results = var_spher(M,varargin)

%VAR_SPHER estimates a spherical variogram for a given data set
%using nonlinear least squares.

%Written by: TONY E. SMITH, 2/21/98

%Functions called: variogram.m, var_fit.m, spher.m
%
%INPUTS:  M = (nx3)-matrix of locations and data values,
%              M(i) = (Xi,Yi,Zi), i = 1:n
%         varargin = optional bandwidth specification (if not 
%                    specified, the default value is Dmax/2).
%
%OUTPUTS: (i)   results.param = [r,s,a] (= estimated [range,sill,nugget])
%         (ii)  results.dist  = distance values, (Di, i=1:b) 
%         (iii) results.vargm = empirical variogram values Gi at Di
%         (iv)  results.spher = spherical values Vi at Di
%         (v)   results.iter  = number of iterations in FMINS
%         (vi)  results.band  = Bandwidth used in variogram estimates


if nargin > 1
   
   d = varargin{:} ;
      
	[DAT,d] = variogram(M,d) ;

else
   
   [DAT,d] = variogram(M) ;

end

D = DAT(:,1) ;

G = DAT(:,2) ;

y = zeros(1,3) ;

y(1) = max(D) ;      %initial estimate of range = max(D)

y(2) = std(M(:,3))^2 ;        %initial estimate of sill = sample variance

y(3) = max([0,min(G)]) ; %initial estimate of nugget

res = var_fit(y,D,G) ;

p = res.param;

iter = res.iter ;

results.param = p ;

results.dist  = D ;

results.vgm = G ;

results.spher = spher(p,D) ;

results.iter = iter ;

results.band = d;



