% Intermediate function for regularisiations on the
% covariance matrix
%
%Inputs
%   Y: A 3D matrix of dimensions Na x Ta x R.
%   F: scalar for number of hyperparameters
%   Regularization: A structure containing two fields A and Sigma.
%   deltas: A delta hyperparameters in a vector of length Na.
%   realCof: structure with true parameters.
%   target: String for FEVD target.
%   H: A scalar value for the horizon of the FEVD.
%   EstLast: optional last coefficient estimation. Improves speed
%Outputs
%   oraclenorm: A vector of length R.
%   Areg: estimated coeffient output. Potentially needed to carry over to
%       another simulation
%   oracleNormStruct:  Oracle norm to the structural FEVD
%
%Functionality
%   The function computes the two outputs oraclenorm and oracleNormStruct
%   for R realizations of the input matrix Y. The oracle norms are the main
%   output for the simulation table
%   The computation is done in parallel using a parfor loop.
%
% Author: Ruben Hipp, 2021

function [oraclenorm, Areg, oraclenormStruct]=estimationSig(Y,Rule,Regularization,deltas,real,target,H,EstLast)
[Na,Ta,R]=size(Y);
RegA1=Regularization.A;
RegSigma1=Regularization.Sigma;


%%
% reuse the coefficient estimation from another method in order to optimize
% the code, if provided
if nargin < 9
    parfor r=1:R
        Xa=Y(:,2:end,r);
        Za=Y(:,1:end-1,r);
        [oraclenorm(r), Areg(:,:,r),oraclenormStruct(r)] = parforloopSig(Xa,Za,RegSigma1,deltas,Na,Ta,Rule,real,target,H);
    end
else
    parfor r=1:R
        Xa=Y(:,2:end,r);
        Za=Y(:,1:end-1,r);
        [oraclenorm(r), ~, oraclenormStruct(r)] = parforloopSig(Xa,Za,RegSigma1,deltas,Na,Ta,Rule,real,target,H,EstLast(:,:,r));   
    end
    Areg=EstLast;
end


end