% CB_SUBMIT callback executed when the user clicks on the 'Submit' button
%
% M Hewitson
%
% $Id: cb_submit.m,v 1.1 2008/09/22 14:28:56 hewitson Exp $
%
function cb_submit(varargin)


  myh     = varargin{1};
  mainfig = varargin{end};

  % get object list
  objlist = findobj(mainfig.handle, 'Tag', 'RepoguiWorkspaceObjsList');
  objstr  = get(objlist, 'String');
  vals    = get(objlist, 'Value');

  % Build sinfo structure
  sinfo.conn                   = mainfig.connection;
  sinfo.experiment_title       = get(findobj(mainfig.handle, 'Tag', 'RepoguiExperimentTitleEdit'), 'String');
  sinfo.experiment_description = get(findobj(mainfig.handle, 'Tag', 'RepoguiExperimentDescriptionEdit'), 'String');
  sinfo.analysis_description   = get(findobj(mainfig.handle, 'Tag', 'RepoguiAnalysisDescriptionEdit'), 'String');
  sinfo.quantity               = get(findobj(mainfig.handle, 'Tag', 'RepoguiQuantityEdit'), 'String');
  sinfo.keywords               = get(findobj(mainfig.handle, 'Tag', 'RepoguiKeywordsEdit'), 'String');
  sinfo.reference_ids          = get(findobj(mainfig.handle, 'Tag', 'RepoguiReferenceIDsEdit'), 'String');
  sinfo.additional_comments    = get(findobj(mainfig.handle, 'Tag', 'RepoguiAdditonalCommentsEdit'), 'String');
  sinfo.additional_authors     = get(findobj(mainfig.handle, 'Tag', 'RepoguiAdditionalAuthorsEdit'), 'String');

  if ~isa(sinfo.conn, 'database')
    error('### Please connect to a database before trying to submit.');
  end


  % Build structure array
  k = 1;
  objs = [];
  for j=1:length(vals)

    objname = deblank(strtok(objstr{vals(j)}));
    cmd = sprintf('obj = evalin(''base'', ''%s'');', objname);
    eval(cmd);

    for l=1:numel(obj)
      objs = [objs obj(l)];
      k = k + 1;
    end
  end

  % Submit objects
  try
    [ids, cid] = submit(objs, sinfo);
    if isempty(ids)
      warning('!!! Failed to submit object: %s', objname);
    else
      disp(sprintf('++ Submitted object(s) %s (ref id = %s, collection id = %d)', objname, mat2str(ids), cid));
    end
  catch
    warning('!!! Failed to submit object: %s', objname);
    rethrow(lasterror)
  end
  
end
