/*---------------------------------------------------------------------------------
 * General string routines that are sometimes missing.
 *
 * Filename:    missing.c 
 * Author:      Randall Gellens.
 * Version:     
 * Last edited: 2 November 1998
 *---------------------------------------------------------------------------------
 */

#include <ctype.h>

#include "missing.h"


/*---------------------------------------------------------------------------------
 * mem_cmp() compares two buffers, ignoring case; compares -n- bytes, ignoring nulls.
 *
 * Returns: < 0 if s1 is less than s2,
 *            0 if s1 is identical to s2,
 *          > 0 if s1 is greater than s2.
 */
int mem_cmp(const char *s1, const char *s2, int n)
{
    int i;
    char c1, c2;

	if ( s1 == 0 || s2 == 0 )
		return 0;

    for (i=0; i<n; i++)
    {
        c1 = tolower(*s1++);
        c2 = tolower(*s2++);
        if (c1 < c2) return -1;
        if (c1 > c2) return  1;
    }
    return 0;
}

/*----------------------------------------------------------------------------------
 *
 * str_cmp() compares two strings, ignoring case.
 *
 * Returns: < 0 if s1 is less than s2,
 *            0 if s1 is identical to s2,
 *          > 0 if s1 is greater than s2.
 */
int str_comp(const char *s1, const char *s2)
{
    char c1, c2;

	if ( s1 == NULL && s2 == NULL )
		return 0;

    while ( *s1 != 0 && *s2 != 0 )
    {
        c1 = tolower(*s1++);
        c2 = tolower(*s2++);
        if (c1 < c2) return -1;
        if (c1 > c2) return  1;
    }

	if ( *s1 == 0 && *s2 == 0 )
		return 0;
	else if ( *s1 == 0 )
		return -1;
    else return 1;
}


/*----------------------------------------------------------------------------------
 *
 * str_cmp_len() compares two strings, ignoring case, stopping when specified
 *    number of characters examined, or null byte found in either string.
 *
 * Returns: < 0 if s1 is less than s2,
 *            0 if s1 is identical to s2,
 *          > 0 if s1 is greater than s2.
 */
int str_comp_len(const char *s1, const char *s2, size_t count)
{
	char c1, c2;

	if ( s1 == NULL && s2 == NULL )
		return 0;

    while ( count > 0 && *s1 != 0 && *s2 != 0 )
    {
        c1 = tolower(*s1++);
        c2 = tolower(*s2++);
        if (c1 < c2) return -1;
        if (c1 > c2) return  1;
		count--;
    }

	if ( count == 0 || ( *s1 == 0 && *s2 == 0 ) )
		return 0;
	else if ( *s1 == 0 )
		return -1;
    else return 1;
}

