%---------------------------------------------------------------------  
% function [Run] = FT_read_kat_output_data(Run,outfile)
% 
% Read data from a Finesse output file.
%
% outfile: string, containing name of Finesse output file
% Run: run structure
%
% Part of the SimTools package
% Andreas Freise 22.05.08 afreise@googlemail.com
%---------------------------------------------------------------------  

function [Run] = FT_read_kat_output_data(Run,outfile)

  % base string for error message id
  baseid='FT_read_kat_output_data';
  % check for right number of outputs
  msg = nargoutchk(1, 1, nargout);
  if (msg)
    msgid=[baseid,':checkoutputs'];
    error(msgid,msg)
  end

  if (~isstruct(Run))
    msgid=[baseid,':checkinarg'];
    msg='first input argument must be a "run" structure';
    error(msgid,msg);
  end

  if (~isstr(outfile))
    msgid=[baseid,':checkinarg'];
    msg='second input argument must be a filename';
    error(msgid,msg);
  end
  
  datafile=['./',outfile];

  %disp(['Loading data file: ',datafile]);
  
  checkfile = exist(datafile);
  
  if (checkfile == 2)
    Run.data=0.0;
    Run.data=load(outfile);
    [Run.rows,Run.cols]=size(Run.data);
    [status,Run]=FT_read_kat_output_header(Run, outfile);
    if (status)
      msgid=[baseid,':headernotfound'];
      result=['could not read header in file: ', oufile];
      error(msgid,result);      
    else
      Run.has_header=1;

      if (Run.has_x2axis)
        X=Run.data(:,1);
        Y=Run.data(:,2);

        [row,col]=size(X);
        nxp=length(find (Y(:)==Y(1)));
        nyp=row/nxp;
        Run.y=Y(1:nyp);
        Run.x=X(1:nyp:row);
        Run.n_outputs=Run.cols-2;
        Run.z=zeros(nyp,nxp,Run.n_outputs);
        
        for i=3:Run.cols
          Run.z(:,:,i-2)=reshape(Run.data(:,i),nyp,nxp);
        end
        
      else
        Run.n_outputs=Run.cols-1;
        Run.x=Run.data(:,1);
        Run.y=Run.data(:,2:Run.cols);
        Run.z=0;       
      end
    end
    
  else
    % file not found
    msgid=[baseid,':filenotfound'];
    result=['output file ', oufile,' not found'];
    error(msgid,result);      
  end

