function [D,datainfo] = getdata(file,cols)
% =============================================================================
% READ AND PLOT ASCII MATRIX ENTRIES AND AN ASSOCIATED COMMENT TEXT FROM A FILE
% function [D,datainfo] = getdata(file,cols)
% =============================================================================
% file ... name of file (string: default extension='.dat') structured this way:
%          comment lines        (optional)
%          <one or more CRLFs>
%          D11 D12 ... D1n
%          D21 D22 ... D2n      (optional)
%           .   .       .
%          Dm1 Dm2 ... Dmn
% cols ... cols=[c_1,c_2,...,c_k]
%          ... abs(c_i) are indeces of the only columns 1<=abs(c_i)<=n
%              which are to be returned in D in the specified order.
%              c_1<0 => the column abs(c_1) are x-axis coordinates,
%                       the remaining columns are y-axis data
%              (optional: default=[]=all columns selected as y-axis data)
% D        ... [Dij] ... matrix entries read from file
%              []    ... if no entry found
% datainfo ... string matrix containing comment lines read from file
%              []    ... if no nonempty comment found

% (C) 1996, V. Vesely, Masaryk University of Brno (Czech Republic)
%
error(nargchk(1,2,nargin));
if nargin < 2, cols=[]; end
INFO = 1; DATA = 2; CTRL_Z = setstr(26);
if strcmp(computer,'PCWIN'), sep = '\';
else  sep = '/';
end
D=[]; datainfo=[];
dotpos = findstr(file,'.');
if isempty(dotpos)
   file = [file,'.dat'];
elseif ~isempty(findstr(file(dotpos(length(dotpos))+1:length(file)),sep))
   file = [file,'.dat'];
end
fid = fopen(file);
if fid==-1, error(['Can''t open the file ',file]); end
eof = [];
mode = INFO;
while isempty(eof)
  line = fgetl(fid);
  if ~isstr(line), break; end
  eof = findstr(line,CTRL_Z);
  if ~isempty(eof)
     line = line(1:eof(1)-1);
  end
  blanks = isempty(line)|all(line==' ');
  if blanks, mode = DATA; end
  if mode==INFO
     if isempty(datainfo),
        datainfo=line;
     else
        datainfo=str2mat(datainfo,line); end
  elseif ~blanks
     D = sscanf(line,'%f');
     n = length(D);
     D = [D;fscanf(fid,'%f')];
     m = round(length(D)./n);
     if m*n~=length(D)
        fclose(fid);
        error('Matrix lines have not equal length');
     end
     D = reshape(D,n,m).';
     eof = 1;
  end
end
fclose(fid);
xcol = [];
if ~isempty(cols)
   D = D(:,abs(cols));
   if cols(1)<0, xcol = 1; end
end
plotdata(D,datainfo,xcol);
