function Q_post=draw_Q_from_SIW_posterior(theta, Q_bar, tau,Gamma)

%   Draw a covariance matrices from the posterior 
%   of a (singular) inverse wishart covariance matrix,
%   when the prior is (S)IW with scale matrix Q_bar and df tau.
%
%   Specification is (RWalk)
%   theta_t = Gamma* theta_{t-1} + v_t,     v_t iid multnormal(0,Q)
%   theta_t is mx1 , Q is mxm
%
%   INPUTS:  theta is mx(T+1) , Q_bar  is mxm , tau is scalar
%   OUTPUTS: Q_post is mxm

[m,T]=size(theta);
if nargin < 4
  Gamma=eye(m);
end

v=theta(:,2:end)-Gamma*theta(:,1:end-1);
S=v*v';
q=rank(S);
qbar=rank(Q_bar);
if abs(qbar-q)>2 && qbar<80
    msgerror=['The ranks of the prior scale matrix q_bar and the S matrix are too much different.' ...
        ' qbar is ' num2str(qbar) ' while q is ' num2str(q) ];
    %error(msgerror)
    warning(msgerror)
end

S_post=S+Q_bar; df_post=tau+T;

if qbar==m 
    Q_post = iwishrnd(S_post,df_post);
elseif qbar<m
    try
        Q_post=  sample_singular_Inv_wishart(S_post,df_post);
    catch
        Q_post=  sample_singular_Inv_wishart(correct_precise_eig( S_post),df_post);
    end
else 
    error('Something strange happened with the rank of matrices')
end


