function res = load( fn, varargin )
%LOAD Load workspace variables from disk and keep a log of files
%  that are loaded for the compiler_survey tool.
%
%   This load function has the same interface as the MATLAB
%   built-in function.  Its sole purpose is to remember all
%   of the .mat files that were loaded during an instrumented
%   function for the compiler_survey tool.  It will save
%   the name of any .mat file loaded into the survey_settings
%   .mat file.
%
%   Type help load for full information about valid arguments
%   to the built-in load function.
%
%   See also COMPILER_SURVEY, LOAD

% $Revision: 1.1 $  $Date: 1998/10/06 18:36:58 $
% Copyright (c) 1984-1998 by The MathWorks, Inc.

    
    survey_file = which('survey_settings.mat');
    d = fileparts( survey_file );
    matname = fullfile( d, 'survey_settings.mat' );
    matfiles = load_variable_from_matfile( matname, 'matfiles' );
    if (isempty(matfiles))
        matfiles = {};
    end
    file = which(fn);
    if (isempty(file))
        file = which( [ fn '.mat' ] );
        if (isempty(file))
            error( [ fn':Can't open file.' ] );
        end
    end

    fprintf( 1, 'Remembering .mat file: "%s"\n', file );
    matfiles{end+1} = file;
    save( matname, '-append', 'matfiles' );

    if (nargout == 0)
        s = builtin( 'load', fn, varargin{:} );
        fns = fieldnames(s);
        for i=1:length(fns)
            assignin( 'caller', fns{i}, eval( ['s.' fns{i} ] ) );
        end
    else
        res= builtin( 'load', fn, varargin{:} );
    end


function y = load_variable_from_matfile( matname, varname )
    y = [];
    vars = whos( '-file', matname );
    for (i=1:length( vars ))
        if (strcmp( vars(i).name, varname ))
            st = builtin( 'load', matname, varname );
            cl = struct2cell(st);
            y = cl{1};
        end
    end

