% THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS 
% OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
% DISCLAIMED.  IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
% INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
% OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
% HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
% OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
% SUCH DAMAGE.

function hyps=mappredict(pitches, likelihoods, conditional, priorweight)
% Performs MAP prediction given a list of pitches, likelihoods of warp factors
% and a conditional distribution of P(alpha | F0) that may be learned using
% learnpdf.m.  The priorweight is adjustable: MAP prediction as
% described in the paper used a weight of 0.5;  ML hypotheses can
% be obtained with a weight of 0; F0-only prediction uses a weight of 1.

pitchaxis=1:1:400;            
hyps = zeros(length(pitches),1);
for speaker = 1:length(pitches),
    pitch = pitches(speaker,1);
    likelihood = transpose(likelihoods(speaker, :));
    likelihood = log(exp(likelihood) / sum(exp(likelihood)));  %Normalized log prob

    priors = zeros(size(likelihood)); 
    posteriors = zeros(size(likelihood)) ;
    
    priors = log(conditional(:,pitch)); % * (pitchpdf(pitch)+realmin));
    
    % Weight the prior and likelihood
    posteriors = (1-priorweight)*likelihood + priors * priorweight;
    		     
    [maxvals, maxindices] = max(posteriors);

    % Convert your output to warp factors
    % These are hardcoded limits, change them with other warp factor ranges
    warprangemin = 0.76;
    warprangestep = 0.04;
    hyps(speaker) = warprangemin + (maxindices-1)*warprangestep;
end
