% QUICK_IR: Compute impulse responses to a VAR: 
% For indentified shock or a shock to a control variable.
%
% usage
% 
% [out, F] = quick_ir(beta,nt,x0,beta2,c0)
%
% where
% 
% beta  = the VAR coeffs
% nt    = periods of IR
% x0    = the initial values of y0
% beta2 = the coeffs of controls (optional)
% c0    = initial values of controls
%
% out   = impulse responses
% F     = companion matrix of VAR

function [out,F] = quick_ir(beta, nt, x0, beta2, c0)

nvar = size(beta,2);
nlag = size(beta,1)/nvar;


ctrls = nargin>3;
if ctrls
    nc = length(c0);
    nl = size(beta2,1)/nc-1;
else
    
end

%***********************
% Get Companion Matrix
%***********************
F = zeros(nvar*nlag);
F(1:nvar,:) = beta';
for j =1:nlag-1
    F(j*nvar+1:(j+1)*nvar,(j-1)*nvar+1:(j)*nvar) = eye(nvar);
end

%***************************
%Compute IR Quickly
%***************************
out = zeros(nvar*nlag, nt);
out(1:nvar,1) = x0';

if ctrls
    out(1:nvar,1) = x0' + beta2(1:nc,:)'*c0';
end

for j = 1:nt-1
    
    if ~isempty(F)
        out(:,j+1) = F*out(:,j);
    end
    if ctrls && j <=nl  %Add in the ctrl impulse
        out(1:nvar,j+1) =out(1:nvar,j+1) + beta2(j*nc+1:(j+1)*nc,:)'*c0';
    end

end
out = out(1:nvar,:)';
