%---------------------------------------------------------------------  
% function [status, Run] = FT_read_kat_output_header(Run, outfile)
% 
% Reads the header of a Finesse data output file.
%
% outfile: string, name of the Finesse output file to read
% Run: run structure
% status: integer, contains an error code
%         0: header has been found
%         1: header has not been found
%
% Part of the SimTools package
% Andreas Freise 22.05.08 afreise@googlemail.com
%---------------------------------------------------------------------    

function [status, Run] = FT_read_kat_output_header(Run, outfile)

  baseid='FT_read_kat_output_header';
  
  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

  [FID, result]=fopen(outfile,'r');
        
  if (FID==-1)
    msgid=[baseid,':fileopen'];
    error(msgid,result);
  end
      
  line1=fgets(FID);
  line2=fgets(FID);
  line3=fgets(FID);

  if (line3(1)=='%')
    % found header
    status=0;
    line1=strtrim(line1(2:length(line1)));
    line2=strtrim(line2(2:length(line2)));
    line3=strtrim(line3(2:length(line3)));
  
    Run.Finesse_version=line1;
    
    %str=regexp(line2,',','split');
    %Run.col_names=regexp(line3,',','split');

    str=FT_split_line(line2,',');
    Run.col_names=FT_split_line(line3,',');

    Run.x1axis=strtrim(cell2mat(Run.col_names(1,1)));
    tmp=cell2mat(str(1,1));
    if(tmp(1)=='3')
      Run.x2axis=strtrim(cell2mat(Run.col_names(1,2)));      
      Run.has_x2axis=1;
    else
      Run.x2axis='';      
      Run.has_x2axis=0;
    end

    Run.y1axis=strtrim(cell2mat(str(1,2)));
    Run.y1axis=Run.y1axis(9:length(Run.y1axis));

    [row,col]=size(str);
    if (col==3)
      Run.y2axis=strtrim(cell2mat(str(1,3)));
      Run.y2axis=Run.y2axis(9:length(Run.y2axis));
      Run.has_y2axis=1;
    else
      Run.y2axis='';
      Run.has_y2axis=0;
    end
    Run.n_outputs=length(Run.col_names)-1-Run.has_y2axis;
  else
    status=1;
  end
  
  fclose(FID);

