function [valueFunction,policy] = solvePOMDP(pomdp, nBelStates, nIterations)
% function [valueFunction,policy] = solvePOMDP(pomdp, nBelStates, nIterations)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Inputs:
%
% pomdp: pomdp problem
% nBelStates: number of belief points
% nIterations: number of iterations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Outputs:
%
% valueFunction: set of alphaVectors
% policy: vector of actions for each alphaVector
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Comments:
%
% The function first parses a pomdp problem, then samples a set of belief points 
% and then executes a bounded, symbolic version of the Perseus algorithm.  
% "Symbolic" refers to the fact that ADDs are used and "bounded" refers to the 
% fact that the number of alphaVectors is bounded. 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if isstruct(pomdp)
  ddPOMDP = pomdp;
  name = [];
else
  ddPOMDP = parsePOMDP(pomdp);
  nameEnd = strfind(pomdp,'.');
  if isempty(nameEnd)
    nameEnd = length(pomdp);
  else
    nameEnd = nameEnd(1)-1;
  end
  name = pomdp(1:nameEnd);
end

if ~exist('nBelStates','var') | isempty(nBelStates)
  nBelStates = 1000;
end

if ~exist('nIterations','var') | isempty(nIterations)
  nIterations = 30;
end

startTime = cputime;

fprintf('\nsampling reachable belief states\n');
belRegion = dd_reachableBelRegion(ddPOMDP.initialBelState,ddPOMDP,nBelStates);
%belRegion = dd_reachableBelRegionTrueModel18(ddPOMDP.initialBelState,ddPOMDP,nBelStates);
%belRegion = dd_enumerateKeyBelStates(ddPOMDP.initialBelState,ddPOMDP,nBelStates);

fprintf('\nrunning symbolic Perseus\n');
[valueFunction,policy] = dd_boundedPerseus(ddPOMDP, belRegion, DD.zero, 1:nIterations,[],name);
runTime = cputime - startTime;

if ~isstruct(pomdp)
  fileName = sprintf('%s_%ibel_%iiter.mat',name,nBelStates,nIterations);
  save(fileName,'valueFunction','policy','ddPOMDP','runTime','belRegion');
  fprintf('\nValue function and policy saved in %s\n',fileName);
end

