% bsexample Demonstrates use of binary search functions using number guessing game [phys-210]

lower = 0;
upper = 128;
fprintf('\nGreetings user %s.  Please think of a number between %d and %d inclusive.\n', ...
   getenv('USER'), lower, upper);
pause(1);
fprintf('Got it? ... '); pause(1); fprintf('Good.  Let''s begin then.\n\n');
fprintf('But before we start, would you like to see what I''m doing as I try to \nguess your number?\n\n');
resp = input('Enter 1 if you would, anything else if not: ');
if length(resp) == 1 && resp == 1
   verbose = 1;
else
   verbose = 0;
   fprintf('OK, no commentary then.\n');
end
% Initialize the search using default tolerance and suppressing output
% from bsnew.
if verbose
   fprintf('OK, I start by initializing the binary search.\n');
   fprintf('Unless you''re cheating, your number is between  %d and %d.\n', ...
      lower, upper);
   fprintf('So I define the initial search bracket to have:\n');
   fprintf('   A lower limit of %d\n', lower);
   fprintf('   An upper limit of %d\n', upper);
end
bsnew(0, 128, nan, verbose)
if verbose
   fprintf('OK, I''m going to start guessing.\n');
end
while ~ bsdone
   guess = bscurrent;
   resp = input(sprintf('Is your number %g? Enter 1 if it is, 0 if it isn''t: ', ...
      guess));
   if length(resp) ~= 1 || (resp ~= 0  && resp ~= 1)
      continue;
   end
   if resp == 1
      fprintf('And it only took me %d tries to guess it!\n', ...
         length(Bs_progress) + 1);
         if verbose 
            bsstatus;
            fprintf('Here''s a final summary of my search.\n');
         end
         fprintf('\nThanks for playing.\n');
         return;
   else
      while 1 
         resp = input('Enter 0 if my guess it too low, 1 if it''s too high: ');
         if length(resp) ~= 1 || (resp ~= 0  && resp ~= 1)
            continue
         end
         if resp
            bshigh;
         else
            bslo;
         end
         if verbose
            bsstatus
         end
         break
      end
   end
end
