%--------------------------------------------------------------------------
% Function: [ I ] = FT_finesse_load_interpolation_data( filename )
%
% Loads the interpolation data that FINESSE outputs when using the command
%   
%   conf [component] save_interp_file 1
%
% in the kat file when using maps. A structure is returned containing the
% the various coupling coefficients found. With X/Y components and complex
% Z component.
%
% Input:
%   filename: Filename of interpolation data e.g. bs_00_00.interp
%
% Output:
%   I:        Struct containing various coupling coefficients
%
% Daniel Brown 21/01/2013
%--------------------------------------------------------------------------
function [ I ] = FT_finesse_load_interpolation_data( filename )

    baseid='FT_read_kat_output_knm';

    if (~ischar(filename))
        msgid=[baseid,':checkinarg'];
        msg='input argument must be a filename';
        error(msgid,msg);
    end
    
    [fid, result]=fopen(filename,'r');

    if (fid==-1)
        msgid=[baseid,':fileopen'];
        error(msgid,result);
    end

    not_done = true;
    I = struct;
    prevknm = 0;
    N = 0;
    
    while not_done
        
        line = fgetl(fid); 

        if ~ischar(line)
            not_done = false;
        else

            vals = textscan(line,'%f');
            knm = vals{1}(1);
            sknm = sprintf('K%d',vals{1}(1));

            if ~isfield(I,sknm)
                fprintf('Found coupling coefficient K%d...\n',knm);
                I.(sknm) = struct('X',[],'Y',[],'Z',[],'N',0);
            end
            
            I.(sknm).N= I.(sknm).N + 1;
            
            I.(sknm).X(I.(sknm).N) = vals{1}(2);
            I.(sknm).Y(I.(sknm).N) = vals{1}(3);
            I.(sknm).Z(I.(sknm).N) = vals{1}(4) + vals{1}(5).*1i;
            
            prevknm = knm;
        end
    end
end

