%
% @file stencil_mat.m
%
% @brief
%
% @copyright
% Copyright (©) 2021 EPFL (Ecole Polytechnique Fédérale de Lausanne)
% SPC (Swiss Plasma Center)
%
% SPClibs is free software: you can redistribute it and/or modify it under
% the terms of the GNU Lesser General Public License as published by the Free
% Software Foundation, either version 3 of the License, or (at your option)
% any later version.
%
% SPClibs is distributed in the hope that it will be useful, but WITHOUT ANY
% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with this program. If not, see .
%
% @author
% (in alphabetical order)
% @author Trach-Minh Tran
%
function [mata, diag] = stencil_mat(file, dset)
id = double(h5read(file, strcat(dset,'/dists')));
val = h5read(file, strcat(dset,'/val'));
n1 = size(val,1);
n2 = size(val,2);
n = n1*n2;
ndiag = size(val,3);
dists = id(:,1) + n1*id(:,2);
val = reshape(val,n,ndiag);
%% Shift the off-diagonals %%
for k=1:length(dists)
d=dists(k);
if d < 0
val(1:n+d,k) = val(1-d:n,k);
elseif d > 0
val(n:-1:d+1,k) = val(n-d:-1:1,k);
end
end
mata = spdiags(val, dists, n,n);
if nargout == 2
idiag = find(dists==0);
diag = val(:,idiag);
end