function [S11, S21, S12, S22, freq] = hp8510c(fname)
% Author : Nilesh Kamdar
% This function will take in a file as the parameter
% and give five outputs. S11, S22, S12, S21 and frequency.
% Each S parameter returned is an array with imaginary
% elements i.e S11real + j*S11imag. The function
% strips off the network analyzer header and returns
% the S-params and the frequency sweep for the readings

% open the file
fid = fopen(fname);

% check if file exists in directory.
% Note: for function to work, both the function file
% and the network analyzer output file have to be in 
% same directory.
if (fid == -1)
   disp('Invalid File name');
   break;
end

% initialize a few variables
flag1 = 0;
k = 1;
count = 0;

% start endless loop of reading file
while 1
   % read one line at a time as string
  	line = fgetl(fid);
     
   % when last line break out of while loop
   if ~isstr(line)
     	break;
   end
   %disp(line)
   
   warning off;
   
   % search for the line with frequency parameters
   % this line starts with SEG 
   if (findstr(line, 'SEG ') == 1)
      [word, remain] = strtok(line); % This removes the word SEG
      [f1, remain] = strtok(remain); % This removes the start frequency
      [f2, totpts] = strtok(remain); % This removes the stop frequency and total no of pts
      f1 = eval(f1);  % convert string to numeric
      f2 = eval(f2);  % convert string to numeric
      totpts = eval(totpts);  % convert string to numeric
      step = (f2 - f1)/(totpts - 1);  %calculate the step increment
      freq = f1:step:f2;  % set up the frequency sweep variable
      
   % search for BEGIN which means s params start at next line
   elseif (findstr(line, 'BEGIN') == 1)  
      flag1 = 1;
      count = count + 1; % this will indicate if the params are s11 or s12 or s21 or s22
      
   % search for END which means s params ended.
   % now put collected s params in suitable variables
   elseif (findstr(line, 'END') == 1)
      flag1 = 0;
      k = 1;
      switch (count)
      	case 1, S11 = Sreal + i.*Simag;
      	case 2, S21 = Sreal + i.*Simag;
      	case 3, S12 = Sreal + i.*Simag;
      	case 4, S22 = Sreal + i.*Simag;
      end
      
   % enters this part only if begin has been found and no end has been found
   % Thus this line contains the sparam itself   
   elseif (flag1 == 1)
      % parsing using delimiter ','
      [part1, part2] = strtok(line, ','); % gets S11 real
      [part2, part3] = strtok(part2, ','); % gets S11 imag
      Sreal(k) = eval(part1);  % convert string to numeric
      Simag(k) = eval(part2);  % convert string to numeric
      k = k + 1;
   end

   warning on;
end
fclose(fid); % close the file
