/*
 * $Id: gen_str.c,v 1.5 1993/11/30 22:43:32 mintha Exp $
 *
 * Set of general routines for use in C programs.
 * These routines provide string conversion, etc. routines.
 *
 * $Log: gen_str.c,v $
 * Revision 1.5  1993/11/30  22:43:32  mintha
 * Added upper_case
 *
 * Revision 1.4  1993/11/23  08:21:04  mintha
 * Added strcmp_nc
 *
 * Revision 1.3  1993/10/20  09:54:37  mintha
 * include gen_utils_x.h now
 *
 * Revision 1.2  1993/10/05  09:30:24  mintha
 * Minor fixes - moved out test stuff
 *
 * Revision 1.1  1993/09/23  09:18:35  mintha
 * Initial revision
 *
 */

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "gen_utils_x.h"

/*
 * strncmp_nc - Compare two strings without case problems.  Limited by len.
 */

int
strcmp_nc(char *str1, char *str2)
{
  int ctr;
  
  for(ctr = 0; tolower(str1[ctr]) == tolower(str2[ctr]); ctr++)
    if(str1[ctr] == '\0')
      return 0;

  return str1[ctr] - str2[ctr];
}

/*
 * strncmp_nc - Compare two strings without case problems.
 */

int
strncmp_nc(char *str1, char *str2, int len)
{
  int ctr;
  
  for(ctr = 0; tolower(str1[ctr]) == tolower(str2[ctr]) || ctr >= len; ctr++)
    if(str1[ctr] == '\0')
      return 0;
  return str1[ctr] - str2[ctr];
}

/*
 * lower_case - Lower case a string
 */

void 
lower_case(char *str)
{
  while(*str = tolower(*str))
    str++;
}

/*
 * upper_case - Upper case a string
 */

void
upper_case(char *str)
{
  while(*str = toupper(*str))
    str++;
}

/*
 *  conv_yesno - Convert Yes/No response to TRUE/FALSE.  Accepts
 *               Yes/yes/YES/Y/y for TRUE and NO/no/No/N/n for
 *               FALSE.  Returns the status - TRUE and it was
 *               a valid response.  
 */

boolean
conv_yesno(char *str, boolean *ans)
{
  *ans = FALSE;
  
  if(str == NULL)
    return FALSE;
  
  if(strstr("Yesyes", str) != NULL && 
     toupper(str[0]) == 'Y' &&
     strlen(str) <= 3)
    *ans = TRUE;
  else if(strstr("Nono", str) != NULL && 
	  toupper(str[0]) == 'N' &&
	  strlen(str) <= 2)
    *ans = FALSE;
  else
    return FALSE;
  
  return TRUE;
}

/*
 *  strip_space - Removes leading and/or trailing space.  Type can by
 *                LEAD, TRAIL. or LEAD | TRAIL.  The return string must
 *                have already been allocated by the calling routine.
 */

void
strip_space(char *str, char *new, int type)
{
  int pos;
  char *p = str;
  
  /* get rid of leading space */
  if(type & LEAD)
    while(isspace(*p) && *p != '\0')
      p++;
  
  /* get rid of trailing space */
  pos = strlen(p) - 1;
  
  if(type & TRAIL)
    while(pos >= 0 && isspace(p[pos]))
      pos--;

  strncpy(new, p, pos + 1);
  new[pos + 1] = '\0';
}
