function varargout=loadi(varargin)
% Duplicates Matlab load function except ignores case on the filename.
% Searches the current path for anything that strcmpi's with the given
% filename, then uses that filename for the load command.
% Calling sequence same as load.
% Author: Ben Barrowes 3/2009, Barrowes Consulting, barrowes@alum.mit.edu
% Get the path and append the current directory to it
p=path; p=textscan(p,'%s','delimiter',pathsep);p=p{1}; p={pwd,p{:}}.';
% default if no filename given
if length(varargin)==0
varargin{1}='matlab.mat';
end
% which input holds the filename?
fnInSpot=1;
for i=1:length(varargin)
if ~strncmp(varargin{i}(1),'-',1)
fnInSpot=i;
break
end
end
% append '.mat' if no extension
[ps,fn,ext]=fileparts(varargin{fnInSpot});
tryForAscii=0;
if isempty(ext)
fnOrig=varargin{fnInSpot};
varargin{fnInSpot}=[varargin{fnInSpot},'.mat'];
tryForAscii=1;
end
% search the path for anthing that strcmpi's with the given filename
found=0;
for i=1:length(p)
dd=dir(p{i});
match=find(strcmpi({dd.name},varargin{fnInSpot}));
if ~isempty(match)
match=match(1);
newFilename=dd(match).name;
found=1;
break
end % if ~isempty(match)
end % for i=1:length(p)
if found
foundDir=i;
else
if tryForAscii
% try again on the filename with no extension
varargin{fnInSpot}=fnOrig;
found=0;
for i=1:length(p)
dd=dir(p{i});
match=find(strcmpi({dd.name},varargin{fnInSpot}));
if ~isempty(match)
match=match(1);
newFilename=dd(match).name;
found=1;
break
end % if ~isempty(match)
end % for i=1:length(p)
if found
foundDir=i;
else
error(['didn''t find any strcmpi matches to',varargin{fnInSpot}])
end
else
error(['didn''t find any strcmpi matches to',varargin{fnInSpot}])
end % if tryForAscii
end % if found
% construct the call to load
loadStr='';
for i=1:length(varargin)
if i==fnInSpot
loadStr=[loadStr,'''',newFilename,''''];
else
loadStr=[loadStr,'''',varargin{i},''''];
end
if i~=length(varargin)
loadStr=[loadStr,','];
end
end
% call load either with no outputs in the calling workspace, or return a struct
disp(['Found following file:'])
disp([p{foundDir},filesep,newFilename])
if nargout==0
evalin('caller',['load(',loadStr,');'])
% If this was an ascii file, then rename the new variable to the old name
if ~strcmp(ext,'.mat')
[ps,fnNew]=fileparts(newFilename);
evalin('caller',[fn,'=',fnNew,'; clear ',fnNew])
end
else
eval(['outStruct=load(',loadStr,');']);
varargout={outStruct};
end