function [out, delimiter, headerlines] = importdata(varargin)
%IMPORTDATA Load workspace variables from disk.
%
% IMPORTDATA(FILENAME) loads data from FILENAME into the workspace.
% A = IMPORTDATA(FILENAME) loads data from FILENAME into A.
%
% IMPORTDATA(FILENAME, D) loads data from FILENAME using D as the column
% separator (if text).  Use '\t' for tab.
%
% IMPORTDATA looks at the file extension to determine which helper function
% to use.  If the extension is mentioned in FILEFORMATS, IMPORTDATA will
% call the appropriate helper function with the maximum number of output
% arguments.  If the extension is not mentioned in FILEFORMATS, IMPORTDATA
% calls FINFO to determine which helper function to use.  If no helper
% function is defined for this extension, IMPORTDATA treats the file as
% delimited text.  Empty outputs from the helper function are removed from
% the result.
%
% Examples:
%
%    s = importdata('ding.wav')
% s =
%
%    data: [11554x1 double]
%      fs: 22050
%
%   s = importdata('flowers.tif');
%   size(s)
% ans =
%
%    362   500     3
%
% See also: LOAD, FILEFORMATS

% Copyright 1984-2000 The MathWorks, Inc.
% $Revision: 1.10 $  $Date: 2000/08/24 12:43:30 $ 

error(nargchk(1,3,nargin));
error(nargoutchk(0,3,nargout));

FileName = varargin{1};

if nargin > 1
    requestedDelimiter = varargin{2};
else
    requestedDelimiter = NaN;
end

if nargin > 2
    requestedHeaderLines = varargin{3};
else
    requestedHeaderLines = NaN;
end

out = [];

if nargout > 1
    delimiter = [];
end

if nargout > 2
    headerlines = 0;
end

fromClipboard = logical(0);

if strcmpi(FileName,'-pastespecial')
    % fetch data from clipboard
    cb = clipboard('paste');
    if isnan(requestedDelimiter)
        delimiter = guessdelim(cb);
    else
        delimiter = sprintf(requestedDelimiter);
    end
    [out.data, out.textdata, headerlines] = stringparse(cb, delimiter, requestedHeaderLines);
    out = LocalRowColShuffle(out);

   FileType = '';
   fromClipboard = logical(1);
else
    % fetch data from file
    if exist(FileName) ~= 2
        error('Unable to open file.')
    end
    [FileType,openCmd,loadCmd,descr] = finfo(FileName);
    
    delimiter = NaN;

    [p,DataName] = fileparts(FileName);

    if ~isempty(loadCmd) & ~strcmp(loadCmd,'importdata')
        out.data = feval(loadCmd, FileName);
    else
        switch FileType
         case 'xls'
          % special case for single sheet
          if length(descr) == 1
              [n,s] = xlsread(FileName,descr{1});
              if ~isempty(n)
                  out.data = n;
              end
              if ~isempty(s)
                  out.textdata = s;
              end
              out = LocalRowColShuffle(out);
          else
              % create dummy field so assignments below work nicely
              out.foo = '';
              for i = 1:length(descr)
                  [n,s] = xlsread(FileName,descr{i});
                  if ~isempty(n)
                      name = descr{i};
                      out = setfield(out,name,n);
                  end
                  if ~isempty(s)
                      name = [descr{i} 'textdata'];
                      out = setfield(out,[descr{i} 'textdata'],s);
                  end
                  % row and column header support for multiple sheets not implemented
              end
          end
                  
         case 'wk1'
          [out.data, out.textdata] = wk1read(FileName);
          out = LocalRowColShuffle(out);
         case 'avi'
          out = aviread(FileName);
         case 'im'
          [out.cdata, out.colormap] = imread(FileName);
         case {'au','snd'}
          [out.data, out.fs] = auread(FileName);
         case 'wav'
          [out.data, out.fs] = wavread(FileName);
         case 'mat'
          wasError = 0;
          try
              if ~isempty(whos('-file',FileName))
                  % call load with -mat option
                  out = load('-mat',FileName);
              else
                  wasError = 1;
              end
          catch
              wasError = 1;
          end
          if wasError
              % call load with -ascii option
              out = load('-ascii',FileName);
          end
          if isempty(out)
              error('Unable to load file.  Not a MAT file.');
          end
         otherwise
          % try to treat as hidden mat file
          try
              out = load('-mat',FileName);
          end
          if isempty(out)
              % file is an unknown format, treat it as text
              [out, delimiter, headerlines] = LocalTextRead(FileName, requestedDelimiter, requestedHeaderLines);
          end
        end
    end
end

if (isstruct(out) & length(out) == 1)
    % remove empty fields from output struct
    names = fieldnames(out);
    for i = 1:length(names)
        if isempty(getfield(out, names{i}))
            out = rmfield(out, names{i});
        end
    end
    if ~isempty(out)
        % flatten output struct if single variable
        names = fieldnames(out);
        if length(names) == 1
            out = getfield(out, names{1});
        end
    end
end

if isempty(out)
    if fromClipboard
        error('Clipboard does not contain any recognizable data.');
    else
        error(sprintf('Unable to load file.\nSee FILEFORMATS for more options.'));
    end
end


function [out, delimiter, headerlines] = LocalTextRead(filename, requestedDelimiter, hlines)

% get the delimiter for the file
if isnan(requestedDelimiter)
    fid = fopen(filename);
    str = char(fread(fid, 4096)');
    fclose(fid);
    delimiter = guessdelim(str);
else
    delimiter = sprintf(requestedDelimiter);
end

% try load first (it works with tabs, spaces, and commas)
out = [];
if isnan(hlines) & ~isempty(findstr(delimiter, sprintf('\t ,')))
    try
        out = load('-ascii', filename);
        headerlines = 0;
    end
end
if isempty(out)
    string = fileread(filename);

    if isempty(string), error('Empty file.'), end

    try
        [out.data, out.textdata, headerlines] = stringparse(string, delimiter, hlines);
        out = LocalRowColShuffle(out);
    catch
        out = [];
        headerlines = 0;
    end
end

function out = LocalRowColShuffle(in)

out = in;

if isempty(in) | ~isfield(in, 'data') | ~isfield(in,'textdata') | isempty(in.data) | isempty(in.textdata)
    return;
end

[dm, dn] = size(in.data);
[tm, tn] = size(in.textdata);

if tn == 1 & tm == dm
    % use as row headers
    out.rowheaders = in.textdata(:,end);
elseif tn == dn
    % use last row as col headers
    out.colheaders = in.textdata(end,:);
end
