function [PERnams,PERvals]=getPeriods(XLSF)
% function [PERnams,PERvals]=getPeriods(XLSF)
% fetch the column labels PERnams and data PERvals from the worksheet PER
% in the parameter workbook XLSF
% Then complete the stress period list from the top down
% where the highest encountered period number is NPER by definition.
% TO 091219 100120

[PERnams,pervals]=getExcelData(XLSF,'PER','Horizontal');

% make sure that the list of stress periods is consistent, apply rules
% for flexibility as defined in the manual
% TO 091211 091218

JP=strmatchi('IPER',PERnams);  % column which holds stress period number
pervals(:,JP)=round(pervals(:,JP)); % in case period numbers are computed in Excel

% Only the stress periods that have iper>0 are valid
pervals=pervals(pervals(:,JP)>0,:);
pervals=sortrows(pervals,JP);

NPER=pervals(end,JP);

% Allow gaps by way of short-hand input

PERvals=NaN(NPER,size(pervals,2)); % Allocate memory for all stress periods 
for iP=size(pervals,1):-1:1         % fill specified layers in, backward
    perNr=min(NPER,pervals(iP,JP));
    PERvals(perNr,:)=pervals(iP,:); % insert given stress periods
end
% filling in backward implies that if there are duplicates, the first value wins

% fill in the gaps
for iPer=NPER-1:-1:1
    if isnan(PERvals(iPer,1))
        PERvals(iPer,:)=PERvals(iPer+1,:);
    end
end
