function nc_addhist ( ncfile, varargin )
% NC_ADDHIST:  Either appends or constructs a history attribute.
%
% USAGE: nc_addhist ( ncfile, attval );
% USAGE: nc_addhist ( ncfile, varname, attval );
%
% This follows the NCO convention that history is prepended, rather 
% than appended.  In other words, ncdumping the file will have the
% most recent history attribution at the top.
% 
% In the first case, a global attribute is written.  In the second,
% a variable attribute is written.
%
% PARAMETERS:
% Input:
%    ncfile:  name of netcdf file
%    varname:  Optional.  If not supplied, assume usage of
%       global history attribute.  If present, assume usage
%       of variable history attribute.
%    attval:  String of information to be tacked on to the
%       history attribute.  If the history attribute is not
%       present, create it.
% Output:
%    None.  In case of an error, an exception is thrown.
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Id: nc_addhist.m 1738 2006-08-29 15:30:09Z johnevans007 $
% $LastChangedDate: 2006-08-29 11:30:09 -0400 (Tue, 29 Aug 2006) $
% $LastChangedRevision: 1738 $
% $LastChangedBy: johnevans007 $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%



if nargin < 2 
	error ( '%s:  too few input arguments.\n\n', mfilename );
end
if nargin > 3 
	error ( '%s:  too many input arguments.\n\n', mfilename );
end

if ( nargin == 2 )
	varname = 'GLOBAL';
	attval = varargin{1};
else
	varname = varargin{1};
	attval = varargin{2};
end

if ~ischar(attval)
	error ( '%s:  history attribute addition must be character.\n\n', mfilename );
end


try
	old_hist = nc_attget ( ncfile, varname, 'history' );
catch
	%
	% The history attribute must not have existed.  That's ok.
	old_hist = '';
end


if isempty(old_hist)
	new_history = sprintf ( '%s:  %s', datestr(now), attval );
else
	new_history = sprintf ( '%s:  %s\n%s', datestr(now), attval, old_hist );
end
nc_attput ( ncfile, varname, 'history', new_history );


return;

