function [data,sess,cond,timepoints,comments]=spm_roi_read_datfile(infile)
% reads in a data file created by spm_roi_compute
% - part of the SPM ROI Toolbox

  
% we use a trick here to figure out how many timepoints there are
% first, open the file using fopen and read in each line, to 
% determine how many lines there are
% then read it in with textread and parse the data

% read in data from file using fopen

fid=fopen(infile,'r');
if fid < 0,
  fprintf('error opening %s\n',infile);
  return;
end;

comment1=fgetl(fid);
comment2=fgetl(fid);
comments={comment1 comment2};
legend=fgetl(fid);
line=cell(1,1);
line_ctr=1;
while 1,
  line(line_ctr)={fgetl(fid)};
  if ~isstr(line{line_ctr}),break,end;
  line_ctr=line_ctr+1;
end;
num_lines=line_ctr-1;  % take off last nice, which has eof marker
fclose(fid);

% read the data as strings in using textread - don't delimit columns
file=textread(infile,'%s','delimiter','\t');

% determine how many columns are in each line
line_length=(size(file,1)-2)/(num_lines+1);

% read in session and cond info
sess=zeros(1,num_lines);
cond=cell(1,num_lines);
data=zeros(num_lines,line_length-2);

ctr=1;
for c=line_length+3:line_length:line_length*(num_lines+1),
  sess(ctr)=str2num(file{c});
  cond(ctr)={file{c+1}};
  for tp=1:line_length-2,
    data(ctr,tp)=str2num(file{c+tp+1});
  end;
  ctr=ctr+1;
end;
timepoints=zeros(1,line_length-2);
for c=5:line_length+2,
  timepoints(c-4)=str2num(file{c});
end;

return;