//
//  osxtads_string_mem.m
//  XTads
//
//  Created by Rune Berg on 12/07/2020.
//  Copyright © 2020 Rune Berg. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "osxtads_support.h"


int impl_memicmp(const char* s1, const char* s2, size_t len );


/*
 *   Provide memicmp, since it's not a standard libc routine.
 *   (from tads2/msdos/osdosc.c)
 */
int memicmp( const void* s1, const void* s2, size_t len )
{
	return impl_memicmp((const char*)s1, (const char*)s2, len);
}

int impl_memicmp(const char* s1, const char* s2, size_t len )
{
	int i;
	
	for (i = 0; i < len; i++)
	{
		if (tolower(s1[i]) != tolower(s2[i]))
			return (int)tolower(s1[i]) - (int)tolower(s2[i]);
	}
	return 0;
}

/* Convert string to all-lowercase.
 */
char* os_strlwr( char* s )
{
	//  assert(s != 0);
	for (int i = 0; s[i] != '\0'; ++i) {
		s[i] = tolower(s[i]);
	}
	return s;
}

int stricmp(const char* str1, const char* str2)
{
	const unsigned char *p1 = (const unsigned char *) str1;
	const unsigned char *p2 = (const unsigned char *) str2;
	int res = 0;
	
	if (p1 == p2) {
		return res;
	}
	
	while (! res) {
		res = tolower(*p1) - tolower(*p2);
		if (*p1++ == '\0') {
			break;
		}
		p2 ++;
	}
	
	return res;
}

int strnicmp (const char *str1, const char *str2, size_t n)
{
	int i, j;
	
	if (! n) {
		return 0;
	}
	
	do
	{
		i = *str1++, j = *str2++;
		i = toupper (i);
		j = toupper (j);
	}
	while (i && i == j && --n);
	
	return (i - j);
}
