%---------------------------------------------------------------------  
% function [Run] = FT_run_kat_simulation(FT, Run)
% 
% Runs a Finesse simulation, as specified in a 'run' structure
% and loads the ouput data into the given 'run' structure.
%
% run: structure defining the input file and is returned with the
%      output data attached
% FT: structure containing Finesse info
% verbose: 1 prints information, 0 is silent
%
% Part of the SimTools package
% Andreas Freise 22.05.08 afreise@googlemail.com
%---------------------------------------------------------------------  

function [Run] = FT_run_kat_simulation(FT, Run, verbose)

  % base string for error message id
  baseid='FT_run_kat_simulation';

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

  if(verbose)
    disp('--------------------------------------------------------------------');
  end
  
  % check for right number of outputs
  msg = nargoutchk(0, 1, nargout);
  if (msg)
    msgid=[baseid,':checkoutputs'];
    error(msgid,msg)
  end

  basename=FT_prepare_kat_filename(Run.filename);
  [katfile,outfile,logfile,mfile,gnufile]=FT_set_kat_filenames(basename);
  
  commandstring=[FT.katbinary,' --perl1 ',Run.options,' ',katfile];
  
  if(verbose)
    disp(['Starting Finesse: ',commandstring]);
  end
  [status,result] = system(commandstring);
  
  if (status)
    msgid=[baseid,':FinesseError'];
    error(msgid,result);
  elseif (verbose)
    disp('     ... done!');
  end
  
  % if output is set: read data file
  if (nargout==1)
    Run=FT_read_kat_output_data(Run, outfile);
  end
  
    
  