function write_utp_document(outfile, results)
  
  txt = '';
  
  fd = fopen(outfile, 'w+');
  
  fprintf(fd, '\\section{Results}\n');
  
  
  
  while ~isempty(results)
    
    % get the first method
    cls  = results(1).class;
    mthd = results(1).method;
    
    % find all results for this method
    n = 1;
    indices = [];
    clear mresults;
    for ll=1:numel(results)
      if strcmp(cls, results(ll).class) && strcmp(mthd, results(ll).method)
        mresults(n) = results(ll);
        indices = [indices ll];
        n = n + 1;
      end
    end
    if n==1
      mresults = [];
    end
    
    results(indices) = [];
    
    writeTestTable(fd, mresults);
    
    fprintf('remaining %d\n', length(results));
    
  end
  
  
  % write output
  
  
  fclose(fd);
  
end


function txt = writeTestTable(fd, results)
  txt = '';
  
  cls = results(1).class;
  mth = results(1).method;
  
  writeHeader(fd, cls, mth);
  
  for kk=1:numel(results)
    
    res = results(kk);
    
    rcol = '';
    if ~res.a || ~res.s
      rcol = '\rowcolor{red}';
    end
    
    if res.s
      syntax = 'pass';
    else
      syntax = 'fail';
    end
    
    if res.a
      algo = 'pass';
    else
      algo = 'fail';
    end
    
    
    fprintf(fd, '%s \\multirow{2}{3cm}{%s %s} & \\multirow{2}{5cm}{%s} & %s & %s \\\\ \\cline{3-4}\n', rcol, res.num, res.subnum, fix(res.doc.desc), fix(res.doc.syntax), syntax);
    fprintf(fd, '%s        &    & %s & %s \\\\ \\hline\n', rcol, fix(res.doc.algo), algo);
    
  end
  
  writeFooter(fd, cls, mth);
  
  
end

function s = fix(str)
  
  s = strrep(str, '_', '\_');
  s = strrep(s, '^', '\^');
  
  parts = regexp(s, '\n', 'split');
  parts(cellfun('isempty', parts)) = [];
  
  if isempty(parts)
    s = '';
  else
    s = parts{1};
    for kk=2:numel(parts)
      s = [s sprintf('\n') parts{kk}];
    end
  end
  
  
end

function writeHeader(fd, cls, mth)
  
  fprintf(fd, '\\begin{longtable}{|p{3cm}|p{5cm}|p{5cm}|c|} \\hline\n');
  fprintf(fd, '{\\bf %s/%s} &&& \\\\ \\hline\n', cls, mth);
  fprintf(fd, '\\endhead\n');
  
  
end


function writeFooter(fd, cls, mth)
%   fprintf(fd, '\\end{tabular}\n');
%   fprintf(fd, '\\end{center}\n');
  fprintf(fd, '\\caption{Unit tests for %s/%s.}\n', cls, mth);
  fprintf(fd, '\\label{tab:%s_%s}\n', cls, mth);
  fprintf(fd, '\\end{longtable}\n');
  fprintf(fd, '\\clearpage\n\n\n');
end

