function  DB = open_sbj_database(spec)

%OPEN_SBJ_DATABASE -- Reads 'subject descriptor' structures from file.
%
%  DB = open_sbj_database(spec)
%
%  SPEC must be either a structure or a name (a string without the '.mat'
%  suffix) of a file created by SAVE_SBJ_DATABASE or UPDATE_SBJ_DATABASE.
%  When SPEC is a structure, OPEN_SBJ_DATABASE simply returns it back.
%  When SPEC is a string, OPEN_SBJ_DATABASE loads the file with this
%  name (see LOAD). It should contain a variable called DB. If no such
%  file exists or if it exists but doesn't contain a variable called DB,
%  an empty structure is returned and a warning is issued.
%
%  See also LOAD, SAVE_SBJ_DATABASE, UPDATE_SBJ_DATABASE, FIND_SBJ_DESCR.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.1 $  $Date: 2004/02/24 13:07 $
%
% 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

empty_DB = struct('sbj_number',{},'group',{},'name',{},'comment',{},...
                  'filename',{},'session',{},'session_log',{}) ;

if (isstruct(spec))
   DB = spec ;            % that was easy enough...
elseif (ischar(spec))     % file name instead of struct?
   if (file_exists([spec,'.mat']))
      S = load(spec,'DB') ;
      if (isfield(S,'DB')) % is there a variable called DB?
         DB = S.DB ;
      else                % else make a DB structure with zero elements
         DB = empty_DB ;
         warning([spec,'.mat contains no DB. Returning an empty DB.']) ;
      end
   else
      DB = empty_DB ;     % no such file exists
      warning([spec,'.mat does not exist. Returning an empty DB.']) ;
   end
elseif (isempty(spec))    % not advertized in the external protocol
   DB = empty_DB ;
else
   error('SPEC must be either a structure or a file name.') ;
end

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