#include "select.h"

/* Ask the user to choose among nopt option strings
 * and return the choice. There is no error check and 
 * asking back
 * Parameters:
 *    options       An array of strings (option names)
 *    nopt          The number of options
 * Result: the index of the selected option
 */
int _select_option_no_error(char options[][N], int nopt){
	int i;
	int res=0;
	int opt_val=-1;
	char buffer[N];
	for(i=0; i<nopt; i++){
		printf("%d) %s\t", i+1, options[i]);
	}
	printf("\nSelect> ");
	res=scanf("%s", buffer);
	if (res<=0) return NOSTRING;  /* No string read */
	opt_val=atoi(buffer)-1; /* Try and convert string to integer */
	if (opt_val>=0) 
		if (opt_val<nopt)	return opt_val; /* User actually entered an integer */
		else return OUTOFRANGE; /* User entered an integer, but out of range */
	/* Else, user entered the option name as a string */
	for(i=0; i<nopt; i++){
		if (strcmp(options[i],buffer)==0) /* Check against each string */
			return i;
	}
	return INVALIDSTRING; /* Invalid string read */
}

/* Ask the user to choose among nopt option strings
 * and return the choice
 * Parameters:
 *    options       An array of strings (option names)
 *    nopt          The number of options
 * Result: the index of the selected option
 */
int select_option(char options[][N], int nopt){
	int result=-1;
	do result=_select_option_no_error(options, nopt);
	while (result<0);
	return result;
}
