% A function to properly clear MATLAB memory for LTPDA.
%
% M Hewitson 06-08-08
%
% $Id: mc.m,v 1.11 2011/02/03 13:42:43 ingo Exp $
%

% Remove this object from memory so we can clear classes
% prefs = getappdata(0, 'LTPDApreferences');
% prefs.misc.default_window = '';

% TODO: We need to close all GUIs before doing this - Prefs GUI and Repo Gui

function mc()
  
  setappdata(0, 'LTPDApreferences', []);
  
  % Remove the repository manager
  rm = getappdata(0, 'LTPDARepositoryManager');
  if ~isempty(rm)
    % store the connections so they don't get lost
    rm.manager.closeAllConnections;
    conns = rm.manager.getConnections;
    delete(rm);
    setappdata(0, 'LTPDAConnections', conns);
  end
  setappdata(0, 'LTPDARepositoryManager', []);
  
  evalin('caller', 'clear');         % Deletes the timer-objects
  clear classes                      % Deletes the local variables
  evalin('caller', 'clear classes'); % Deletes the variables in the caller function
  evalin('base', 'clear classes');   % Deletes the variables in the 'base' workspace
  
  % Load the preferences again
  LTPDAprefs.loadPrefs;
  
  % Make a new Repository Manager
  conns = getappdata(0, 'LTPDAConnections');
  rm = LTPDARepositoryManager;
  if ~isempty(conns)
    % and put back the existing connections
    for kk = 1:conns.size
      conn = conns.get(kk-1);
      rm.newConnection(char(conn.getHostname), ...
        char(conn.getDatabase), ...
        char(conn.getUsername), ...
        char(conn.getPassword));
    end
  end
  setappdata(0, 'LTPDAConnections', []);
  
end
