function outputStruct=DatareadS1p(filename)
% Reads the Agilent PNA *s1p files and returns a struct with the Sparameters
% in the Real/Imag format
%
% Input
% filename  string with the file name. Example: data.s1p
%
% Output    Struct with the Sparameters (complex number)
%           outputStruct.measurement    Measured S parameter
%           outputStruct.stimulus       Stimulus
%           outputStruct.data           S parameter data
%           outputStruct.stimulusLabel  Units of the Stimulus
%
%   v1, 5/03/2013
%
% function outputStruct=DatareadS1p(filename)

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

% Read the line giving the units and the format
fid=fopen(filename);
for ii=1:5,
    tline = fgets(fid);
end
% to read the measurement type
MeasName=tline(25:27);

% to read the xaxis units and the data format
tline = fgets(fid); 
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,SXXaa,SXXbb]=...
    textread(filename,'%f\t%f\t%f','headerlines',6);

% Compute the real/imaginary part of the data, depending on the format
if (strcmp(DataType,'MA')),
    SXXdata=SXXaa.*exp(1i*SXXbb/360*2*pi);
elseif (strcmp(DataType,'dB'))
    SXXdata=10.^(SXXaa/20).*exp(1i*SXXbb/360*2*pi);
elseif (strcmp(DataType,'RI'))
    SXXdata=SXXaa+1i*SXXbb;
else
    error('Data Format not known');
end


% Build the output struct
outputStruct.measurement=MeasName;
outputStruct.stimulus=haxis;
outputStruct.data=SXXdata;
outputStruct.stimulusLabel=xunits;


