%PR_READDATASET Convert text file into PRTools dataset
%
%   A = PR_READDATASET(FILE,NHEAD,DELIM,MISVAL,FORMAT,NLAB)
%
%INPUT
%  FILE       - filename
%  NHEAD      - number of headerlines to be skipped, default 0
%  DELIM      - delimiter characters, default ' '
%  MISVAL     - character used for missing values, default '?'
%  FORMAT     - format needed for interpreting feature types of columns.
%               default is determined from first line, e.g. 'nncc' for two
%               numeric and two categorical features, see SETFEATDOM and
%               PR_CELL2DSET
%  NLAB       - feature to be interpreted as class label, default [].
%
%OUTPUT
%  A          - PRTools dataset
%
%SEE ALSO
%DATASETS, SETFEATDOM, PR_CELL2DSET

% Copyright: R.P.W. Duin

function a = pr_readdataset(file,varargin)

  [nhead,del,misval,form,flab] = setdefaults(varargin,0,' ','?',[],[]);

  [fid,msg] = fopen(file);
  if fid < 1
  	error(msg)
  end
  if isempty(form)        % if no format given ...
    for j=1:nhead+1
      s = fgetl(fid);     % derive it from the first nonheader line
    end        
    s = mytextscan(s,'c',del,0); % use all %s for time being
    form = getform(s);    % convert fields to %n where appropriate
    fseek(fid,0,-1);      % restart
  end
  c = mytextscan(fid,strrep(form,'n','s'),del,nhead);
  a = pr_cell2dset(c,form,misval);
  if ~isempty(flab)
    a = feat2lab(a,flab);
  end
  
return

function s = mytextscan(fid,forms,del,nhead)
  form = repmat('%%',1,numel(forms));
  form(2:2:end) = forms;
  forms = strrep(form,'c','s');
  if del == ' '
    s = textscan(fid,forms,'Headerlines',nhead);
  else
    s = textscan(fid,forms,'Delimiter',del,'Headerlines',nhead);
  end
  if ~ischar(fid)
    fclose(fid);
  end
return

function form = getform(s)
  s = char(s{1});
  form = repmat('n',1,size(s,1));
  for j=1:size(s,1)
    if ~isempty(regexp(s(j,:),'[^0-9+-.eE ]','once'))
      form(j) = 'c';
    end
  end
return

