function betaDraw = drawSingleParamUPriorAllCountriesWeighted(gap,...
    firstObForCountry, lastObForCountry,nCountries,...
    S,desiredState,h,cLower,cUpper,weight)
    

%{
draw a single regression parameter with normal likelihood and
uniform(cLower,cUpper) prior

h is inverse error variance
    we will need to control for heteroskedasticity
    
desiredState tells us which state we are looking for

weight tells what weight to apply to the country
   
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

Dick Startz
May 2016
modified September 2016
modified April 2017
%}
n = 0; %check that we actually have observations for this state

for iCountry = 1:nCountries
    lastOb = lastObForCountry(iCountry);
    firstOb = firstObForCountry(iCountry);
    n = sum(S(firstOb+1:lastOb)==desiredState);
end
if n <= 1
    %draw from prior
    betaDraw = cLower + (cUpper-cLower)*rand;
    return;
end

% It's too hard to patch together relevant pieces for each country
% So we'll just accumulate sum(x.*y) and sum(x.^2), deflating 
% for heteroskedasticity as we go along
% We also effectively multiply each y and x by the country's weight.
numerator = 0;
denominator = 0;
varDenom = 0;
for iCountry = 1:nCountries
    lastOb = lastObForCountry(iCountry);
    firstOb = firstObForCountry(iCountry);
    y_iCountry = gap(firstOb+1:lastOb);
    y_Relevant = y_iCountry(S(firstOb+1:lastOb)==desiredState);
    x_iCountry = gap(firstOb:lastOb-1);
    x_Relevant = x_iCountry(S(firstOb+1:lastOb)==desiredState);
                    % note here that the relevant state is the y state
    numerator = numerator + sum(y_Relevant.*x_Relevant...
        *h(iCountry)*(weight(iCountry).^2));
    denominator = denominator + sum((x_Relevant.^2)...
        *h(iCountry)*(weight(iCountry).^2));
    varDenom = varDenom + sum((x_Relevant.^2)...
        *(h(iCountry).^2)*(weight(iCountry).^2));
end

betaHat = numerator/denominator;
V = denominator/(varDenom.^2);
betaDraw = truncatedNormalDraw(cLower,cUpper,betaHat,V);

end

