/*
 * **********************************************************************
 * *	                                                               *
 * *             Lookup a Command From a List of Commands               * 
 * *                                                                    *
 * ********************************************************************** 
 * File: libs/user/c_cmd_lookup.c
 *
 *                    COPYRIGHT (c) 1992, 1999  BY
 *         SIGMET INCORPORATED, WESTFORD MASSACHUSETTS, U.S.A. 
 * 
 * THIS SOFTWARE IS FURNISHED UNDER A LICENSE AND MAY BE USED AND  COPIED
 * ONLY  IN  ACCORDANCE WITH  THE  TERMS  OF  SUCH  LICENSE  AND WITH THE
 * INCLUSION OF THE ABOVE COPYRIGHT NOTICE.  THIS SOFTWARE  OR  ANY OTHER
 * COPIES  THEREOF MAY NOT BE PROVIDED OR OTHERWISE MADE AVAILABLE TO ANY
 * OTHER PERSON.  NO TITLE TO AND OWNERSHIP OF  THE  SOFTWARE  IS  HEREBY
 * TRANSFERED. 
 */
#include <stdio.h>
#include <string.h>
#include "sigtypes.h"
#include "user_lib.h"
/*
 * Lookup a command from a list of commands, dealing with the cases of the
 * command not being there, or being ambiguous.  Note that only the first 80
 * characters will be compared.
 *
 */
SINT4 c_cmd_lookup
  (char* scmd_a,      /* Character string to lookup */
   char* slist_a[],   /* Array of strings to compare against */
   SINT4 ilistn_a,    /* Number of strings in the list */
   UINT2* lamb_a      /* Set to non-zero if ambiguous */
   )
{
#define MAX_CHECK (80)

  SINT4 icmd_len, ilist_len, icompare_len, ihits, index, icommand;
  UINT2 lexact, llexact;
  /*
   * ----------------------------------------------------------------------
   * Check for various problems:
   */

  /* No command list */
  if( ilistn_a <= 0 )
    {
      *lamb_a = 0;
      return 0;
    }

  icmd_len = strlen( scmd_a );
  if (icmd_len > MAX_CHECK) icmd_len=MAX_CHECK;

  /* Zero length command matches all choices */
  if( icmd_len <= 0 )
    {
      *lamb_a  = ilistn_a != 1;
      return 1;
    }

  /*
   * Scan through table.  Note that an exact match will override the ambiguous
   * flag.
   */
  ihits    = 0;
  icommand = 0;
  llexact  = 0;  /* This is a latched version of lexact */

  for (index=0; index<ilistn_a; index++)
    {
      ilist_len = strlen( slist_a[index] );
      if (ilist_len<icmd_len) icompare_len=ilist_len; else icompare_len=icmd_len;
      
      if (0==strncmp( scmd_a, slist_a[index], icompare_len ))
	{
	  ihits += 1;
	  lexact  = (0==strncmp( scmd_a, slist_a[index], MAX_CHECK ));
	  llexact = llexact|lexact;

	  if( (1==ihits) | lexact ) icommand = index+1;
	}
    }
  
  *lamb_a = (ihits > 1) & (!llexact);

  return icommand;
}
