function [ pulsarparams ] = readparfile( parfile )

% [ pulsarparams ] = readparfile( parfile )
%
% This function takes in a pulsar TEMPO-style .par file and outputs the 
% parameters in the pulsarparams structure - it doesn't use textscan, so
% can be used with Octave

% check that the file exists
if exist(parfile, 'file') == 0
    disp('Error parameter file does not exist');
    pulsarparams = 0;
    return;
end

% open par file for reading
fp = fopen(parfile, 'r');

i = 1;

% read in one line at a time from the file
while ~feof(fp)
    tline = fgetl(fp);
    
    % check if the line is a comment (use % and # as comment values)
    if ~isempty(strfind(tline, '%')) || ~isempty(strfind(tline, '#'))
        continue;
    end
    
    % get all the values in the line (woudl use 'split' but in Octave 
    % regexp doesn't have a 'split' option) 
    [start, ends] = regexp(tline, '\s+', 'start', 'end');
    linelength = length(tline);
    % set the values
    for k=1:length(start)
        if k == 1
            values{k} = tline(1:start(k)-1);
        else
            values{k} = tline(ends(k-1)+1:start(k)-1);
        end
    end
    if ends(end) < linelength
        values{length(ends)+1} = tline(ends(end)+1:end);
    end
    nvals = length(values); % see how many values are on the line
    disp(nvals);
    
    % if the line only contains a parameter name (i.e. with no associated
    % value) then ignore it
    if nvals == 1 || isempty(char(values(2)));
        continue;
    end
    
    % set parameter name
    pulsarparams.parname{i} = values(1);
   
    % if parameter is pulsar name then set the values separately from the 
    % rest
    if strcmp(char(pulsarparams.parname{i}), 'PSR') || ...
            strcmp(char(pulsarparams.parname{i}), 'PSRJ') || ...
            strcmp(char(pulsarparams.parname{i}), 'PSRB') || ...
            strcmp(char(pulsarparams.parname{i}), 'NAME')
        pulsarparams.parval{i} = values(2);
        pulsarparams.parerr{i} = []; % set this as empty
    % if the values contains just a string, or a colon (e.g for the RA,
    % dec) then set as a string
    elseif isempty(sscanf(char(values(2)), '%f')) || ...
            ~isempty(strfind(char(values(2)), ':'))
        pulsarparams.parval{i} = values(2);
    else
        % convert any exponents written with a D, or d, to E
        newval = regexprep(values(2), 'D', 'E', 'ignorecase'); 
        
        pulsarparams.parval{i} = str2double(newval);        
    end
    
    % check for any error values for the given parameter
    if nvals == 4 && str2double(values(3)) == 1 && ...
            ~isempty(sscanf(char(values(4)), '%f'))
        % convert any exponents written with a D, or d, to E
        newval = regexprep(values(4), 'D', 'E', 'ignorecase');
            
        pulsarparams.parerr{i} = str2double(newval);
    else
        pulsarparams.parerr{i} = [];
    end
    
    i = i+1;
    clear values;
end

pulsarparams.nparams = i-1;

fclose(fp);
    
