/* nag_search_char (m01ncc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 9, 2009.
 */
/* Pre-processor includes */
#include <stdio.h>
#include <math.h>
#include <string.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     chlen, i, index, lench, m1, m2;
  /*Character scalar and array declarations */
  char        item[255], chtmp[255];
  char        **ch;
  NagError    fail;

  INIT_FAIL(fail);

  printf("%s\n", "nag_search_char (m01ncc) Example Program Results");
  printf("\n");
  scanf("%*[^\n] ");
  scanf("%ld%*[^\n]", &lench);
  if (!(ch = NAG_ALLOC(lench, char *)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  /* Read in Reference Vector ch*/
  for (i = 0; i < lench; i++)
    {
      scanf("%254s", chtmp);
      chlen = strlen(chtmp);
      if (!(ch[i] = NAG_ALLOC(chlen+1, char)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
      strncpy(ch[i], chtmp, chlen+1);
    }
  scanf("%*[^\n] ");
  /* Read items sought in the reference vector*/
  validate = Nag_TRUE;
  m1 = 0;
  m2 = lench-1;
  while (scanf("%254s%*[^\n] ", item) != EOF)
    {
      /*
       * nag_search_char (m01ncc)
       * Binary search in set of character data
       */
      index = nag_search_char(validate, (const char**)ch, m1, m2, item, &fail);
      if (fail.code != NE_NOERROR)
        {
          printf("Error from nag_search_char (m01ncc).\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 < lench; i++)
            {
              printf("%s%s", ch[i], (i+1)%10?" ":"\n");
            }
          printf("\n");
          validate = Nag_FALSE;
        }
      printf("\n");
      printf("  Search for item %s returned index: %4ld\n", item,
              index);
    }

 END:
  for (i = 0; i < lench; i++)
    {
      NAG_FREE(ch[i]);
    }
  NAG_FREE(ch);

  return exit_status;
}