function  DB = update_sbj_database(new_entries,spec)

%UPDATE_SBJ_DATABASE -- Updates 'subject descriptor' structures to file.
%
%  DB = update_sbj_database(new_entries,spec)
%
%  NEW_ENTRIES is a structure array of one or more 'subject descriptors'.
%  SPEC is a structure or a file name. It is passed to OPEN_SBJ_DATABASE.
%  The new entries are added to the old database (as opened via SPEC),
%  overwriting any old entries with the same subject numberes (as indicated
%  by FIND_SBJ_DESCR). Finally, the updated database is saved back to
%  the file (if SPEC is a file name) and returned.
%
%  See also SAVE_SBJ_DATABASE, OPEN_SBJ_DATABASE, FIND_SBJ_DESCR.

%  TO DO:  Add an optional MODE argument: '-mat' or '-ascii'

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.0 $  $Date: 2002/01/08 17:49 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

DB = open_sbj_database(spec) ;

for k = 1:length(new_entries)
   curr_entry = new_entries(k) ;
   [d,idx] = find_sbj_descr(curr_entry.sbj_number,DB,0) ;
   if (isempty(idx))       % new entry
      DB(end+1) = curr_entry ;
   else
      DB(min(idx)) = curr_entry ;     % overwrite leftmost old entry
   end
end

if (ischar(spec))   % file name supplied?
   save_sbj_database(spec,DB) ;
%else do not write to disc; simply return as function value
end

%--- Return DB
%%%%% End of file UPDATE_SBJ_DATABASE.M