function sig=mcsdraw(y,x,b,sdraw)
%function sig=mcsdraw(y,x,b,sdraw)
% draw sig from posterior (assuming flat prior on the log sig's, except for the 
% constraint that sig is monotone increasing in S) conditional 
% on b and sdraw.  This code does not
% assume that b is necessarily the same for all S.
% Note that a proper prior on sig is implemented here.  This is needed
% to avoid an MCMC routine getting stuck when a draw on the sequence of 
% states shows some that never occur.  Results could be sensitive to the
% prior if rarely-occuring states are a priori plausible.
% ------------- prior ----------------------
sbar = .1; % prior harmonic mean of each element of sig.  The prior makes
            % each sbar/sig^2 chi-squared(1)
ns=size(b,2);
T=size(y,1);
sdum=repmat(sdraw,1,ns)==repmat([1:ns],T,1);
scount=sum(sdum);
%ghostindex=find(scount==0);
u=repmat(y,1,ns)-x*b;
rsss=sum(u.^2..*sdum)+sbar;
sig=ns:-1:1;
while any(sig(1:ns-1)>sig(2:ns))
   gv=repmat(randn(T,1).^2,1,ns);
   gv=sum(gv.*sdum)+randn(1,ns).^2; % This is probably not the most efficient way 
                                    % to generate these chi-squared random draws.
                                    % We use the proper prior .01/sig^2~chi-sq(1).
   gv=gv+randn(1,ns).^2;
   %gv(ghostindex)=ones(size(ghostindex));
   sig=sqrt(rsss./gv);
end  % This way of enforcing monotonicity might be very inefficient if the sig values
     % are close together or ill-determined and ns is large.
