function transitionMatrix = drawTransProbAllCountries3StatesWeighted(S,...
    firstObForCountry, lastObForCountry,nCountries,...
    alpha_n,alpha_c,alpha_d,weight)

%{
draw transition probabilities
modelled after Jeremy Pigers' gen_tp

This is complicated by the fact that we are drawing a common parameter
for all the countries and that we need to observe boundaries in the data

weight is weight to apply to each country
Dick Startz
May 2016
modified September 2016
modified March 2017 to use drchrnd.m and allow for three states
modified April 2017
%}

% count switches
switches = zeros(3,3);
switches2 = zeros(3,3);


% do the count both with a weight and without
% and then adjust weighted count to right number of countries

for iCountry = 1:nCountries
    lastOb = lastObForCountry(iCountry);
    firstOb = firstObForCountry(iCountry);
    for from = 1:3
        for to = 1:3
            switches(from,to) = switches(from,to) + ...
               sum((S(firstOb:lastOb-1)==from).*...
               (S(firstOb+1:lastOb)==to)*weight(iCountry));
             switches2(from,to) = switches2(from,to) + ...
               sum((S(firstOb:lastOb-1)==from).*...
               (S(firstOb+1:lastOb)==to));           
        end
    end
end

switches = switches*(sum(sum(switches2))/sum(sum(switches)));
% generate transition probabilities

transitionMatrix(1,:) = drchrnd(alpha_n' + switches(1,:));
transitionMatrix(2,:) = drchrnd(alpha_c' + switches(2,:));
transitionMatrix(3,:) = drchrnd(alpha_d' + switches(3,:));

end