function outputStruct=DatareadS2p(filename)
% Reads the Agilent PNA *s2p files and returns a struct with the Sparameters
% in the Real/Imag format
%
% Input
% filename  string with the file name. Example: data.s2p
%
% Output    Struct with the Sparameters (complex number)
%           outputStruct.stimulus       Stimulus
%           outputStruct.S11            S11
%           outputStruct.S12            S12
%           outputStruct.S21            S21
%           outputStruct.S22            S22
%           outputStruct.stimulusLabel  Units of the Stimulus
%
%   v1, 5/03/2013
%
% function outputStruct=DatareadS2p(filename)

% Check that the file is in the correct format
if strfind(filename,'.s2p'), 
else
    error('It is not a *.s2p file'); 
end

% Read the line giving the units and the format
fid=fopen(filename);
for ii=1:5,
    tline = fgets(fid);
end
tline = fgets(fid); % to read the xaxis units and the data format
LineBeginning=strfind(tline,'#');
Sposition=strfind(tline,'S');
xunits=tline(LineBeginning+2:Sposition-2);
DataType=tline(Sposition+3:Sposition+4);
fclose(fid);

% read the data
[haxis,S11aa,S11bb,S21aa,S21bb,S12aa,S12bb,S22aa,S22bb]=...
    textread(filename,'%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f','headerlines',6);

% Compute the real/imaginary part of the data, depending on the format
if (strcmp(DataType,'MA')),
    S11data=S11aa.*exp(1i*S11bb/360*2*pi);
    S22data=S22aa.*exp(1i*S22bb/360*2*pi);
    S21data=S21aa.*exp(1i*S21bb/360*2*pi);
    S12data=S12aa.*exp(1i*S12bb/360*2*pi);
elseif (strcmp(DataType,'dB'))
    S11data=10.^(S11aa/20).*exp(1i*S11bb/360*2*pi);
    S22data=10.^(S22aa/20).*exp(1i*S22bb/360*2*pi);
    S21data=10.^(S21aa/20).*exp(1i*S21bb/360*2*pi);
    S12data=10.^(S12aa/20).*exp(1i*S12bb/360*2*pi);
elseif (strcmp(DataType,'RI'))
    S11data=S11aa+1i*S11bb;
    S22data=S22aa+1i*S22bb;
    S21data=S21aa+1i*S21bb;
    S12data=S12aa+1i*S12bb;
else
    error('Data Format not known');
end


% Build the output struct
outputStruct.stimulus=haxis;
outputStruct.S11=S11data;
outputStruct.S12=S12data;
outputStruct.S21=S21data;
outputStruct.S22=S22data;
outputStruct.stimulusLabel=xunits;


