function sp = read_sp(filename)
% sp = read_sp(filename)
%
%  Reads a CMS Save Point file
%
% written by Alex Sanchez

if nargin==0
    fpath = '..\..\test_cases\field\Gironde\runs\hybrid3\';
    fname = 'Flow_GE03_eta.sp';
    filename = [fpath,fname];
end

fid=fopen(filename,'r');
sp.variable = 'scalar';
while 1
    row = fgetl(fid);
    if ~ischar(row), break, end
    row = strtrim(row);
    ind = strfind(row,' ');
    if ~isempty(ind)
        card = row(1:ind(1)-1);
        arg = strtrim(row(ind(1)+1:end));
    else
        card = row;
        arg = [];
    end
    if isempty(card), continue, end
    switch (card)
        case 'SAVE_POINT_OUTPUT'
            sp.variable = arg;
        case 'REFERENCE_TIME'
            ind2 = strfind(row,'UTC');
            sp.reference_time_str = arg;
            sp.reference_time = datenum(row(ind(1)+1:ind2-1),...
                'yyyy-mm-dd HH:MM:SS');
        case 'SAVE_POINT_LABEL'
            sp.label = regexprep(arg,'"','');
        case 'CREATION_DATE'
            sp.creation_date = arg;
        case 'HORIZ_PROJECTION'
            sp.horizontal_projection = arg;
        case 'VERT_DATUM'
            sp.vertical_datum = arg;
        case 'TIME_UNITS'
            sp.time_units = arg;
        case 'OUTPUT_UNITS'
            sp.output_units = arg;
        case 'CMS_VERSION'
            sp.cms_version = arg;
        case 'NUMBER_POINTS'
            sp.number_points = str2double(arg);
        case 'NAME_BEGIN'
            sp.names = cell(sp.number_points,1);
            for i=1:sp.number_points
                row = fgetl(fid);
                row = regexprep(row,'"','');
                sp.names{i} = strtrim(row);
            end
        case 'NAME_END'
        case 'XY_BEGIN'
            sp.xy = zeros(sp.number_points,2);
            for i=1:sp.number_points
                sp.xy(i,:) = fscanf(fid,'%f %f\r',2);
            end
        case 'XY_END'
        case 'SCALAR_TS_BEGIN'
            sp.time = [];
            sp.(sp.variable) = [];
            while 1
                dat = fscanf(fid,'%f ',sp.number_points+1);
                if isempty(dat), break, end
                sp.time(end+1,1) = dat(1);
                sp.(sp.variable)(end+1,:) = dat(2:end);
            end
        case 'VECTOR_TS_BEGIN'
            sp.time = [];
            sp.(sp.variable) = [];
            while 1
                dat = fscanf(fid,'%f ',sp.number_points*2+1);
                if isempty(dat), break, end
                sp.time(end+1,1) = dat(1);
                sp.(sp.variable)(end+1,:) = dat(2:end);
            end
        otherwise
            disp(['Card: ',card,' not found'])
    end
end
fclose(fid);

return


