/* nag_search_int (m01nbc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 9, 2009.
 */
/* Pre-processor includes */
#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagm01.h>

int main(void)
{
  /*Logical scalar and array declarations */
  Nag_Boolean validate;
  /*Integer scalar and array declarations */
  Integer     exit_status = 0;
  Integer     i, index, item, leniv, m1, m2;
  Integer     *iv = 0;
  NagError    fail;

  INIT_FAIL(fail);

  printf("%s\n", "nag_search_int (m01nbc) Example Program Results");
  printf("\n");
  scanf("%*[^\n] ");
  scanf("%ld%*[^\n] ", &leniv);
  if (!(iv = NAG_ALLOC(leniv, Integer)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  /* Read in Reference Vector iv*/
  for (i = 0; i < leniv; i++)
    scanf("%ld ", &iv[i]);
  scanf("%*[^\n] ");
  /* Read items sought in the reference vector*/
  validate = Nag_TRUE;
  m1 = 0;
  m2 = leniv-1;
  while (scanf("%ld%*[^\n] ", &item) != EOF)
    {
      /*
       * nag_search_int (m01nbc)
       * Binary search in set of integer numbers
       */
      index = nag_search_int(validate, iv, m1, m2, item, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_search_int (m01nbc).\n%s\n",
                  fail.message);
          exit_status = 1;
          goto END;
        }
      if (validate)
        {
          /* Print the reference vector*/
          printf("%s\n", "Reference Vector is:");
          for (i = 0; i < leniv; i++)
            printf("%5ld%s", iv[i], (i+1)%8?" ":"\n");
          printf("\n");
          validate = Nag_FALSE;
        }
      printf("\n");
      printf("  Search for item %5ld returned index: %4ld\n", item,
              index);
    }

 END:
  NAG_FREE(iv);

  return exit_status;
}