/* nag_search_int (m01nbc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */
/* 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("%" NAG_IFMT "%*[^\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("%" NAG_IFMT " ", &iv[i]);
  scanf("%*[^\n] ");
  /* Read items sought in the reference vector */
  validate = Nag_TRUE;
  m1 = 0;
  m2 = leniv - 1;
  while (scanf("%" NAG_IFMT "%*[^\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("%5" NAG_IFMT "%s", iv[i], (i + 1) % 8 ? " " : "\n");
      printf("\n");
      validate = Nag_FALSE;
    }
    printf("\n");
    printf("  Search for item %5" NAG_IFMT " returned index: %4" NAG_IFMT
           "\n", item, index);
  }

END:
  NAG_FREE(iv);

  return exit_status;
}