/* nag_search_double (m01nac) 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, lenrv, m1, m2;
  /*Double scalar and array declarations */
  double      item;
  double      *rv = 0;
  NagError    fail;

  INIT_FAIL(fail);

  printf("%s\n", "nag_search_double (m01nac) Example Program Results");
  printf("\n");
  scanf("%*[^\n] ");
  scanf("%ld%*[^\n] ", &lenrv);
  if (!(rv = NAG_ALLOC(lenrv, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  /* Read in Reference Vector rv*/
  for (i = 0; i < lenrv; i++)
    scanf("%lf ", &rv[i]);
  scanf("%*[^\n] ");
  /* Read items sought in the reference vector*/
  validate = Nag_TRUE;
  while (scanf("%lf%*[^\n] ", &item) != EOF)
    {
      m1 = 0;
      m2 = lenrv-1;
      /*
       * nag_search_double (m01nac)
       * Binary search in set of double precision numbers
       */
      index = nag_search_double(validate, rv, m1, m2, item, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_search_double (m01nac).\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 < lenrv; i++)
            printf("%7.1f%s", rv[i], (i+1)%8?" ":"\n");
          printf("\n");
          validate = Nag_FALSE;
        }
      printf("\n");
      printf("  Search for item  %7.1f returned index: %4ld\n", item,
              index);
    }

 END:
  NAG_FREE(rv);

  return exit_status;
}