/*
 * Case insensitive natural comparison by Gabor Heja <http://dev.kakaopor.hu/>
 * Use freely for any purpose.
 */

/* macro to increase readability */
#define NATSORT_BETWEEN(a, b, c) (a >= b && a <= c)
int compare_natsort (const char *s1, const char *s2)
{
	unsigned int i = 0, j, k, s1_int, s2_int, tmp1, tmp2;

	while (s1[i] != 0 && s2[i] != 0)
	{
		/*  if we find a digit we should read the whole number
		 *  (the order of '-' in the ASCII table is lower than 0, so negative numbers already solved) */

		if (NATSORT_BETWEEN(s1[i], 48, 57) || NATSORT_BETWEEN(s2[i], 48, 57))
		{
			j = i;
			k = i;
			s1_int = 0;
			s2_int = 0;

			while (NATSORT_BETWEEN(s1[j], 48, 57))
			{
				s1_int = s1_int * 10 + s1[j++] - 48;
			}

			while (NATSORT_BETWEEN(s2[k], 48, 57))
			{
				s2_int = s2_int * 10 + s2[k++] - 48;
			}

			if (s1_int != s2_int)
			{
				return s1_int < s2_int ? -1 : 1;
			}
		}

		/* do case insensivie check */
		tmp1 = NATSORT_BETWEEN(s1[i], 65, 90) ? s1[i] + 32 : s1[i];
		tmp2 = NATSORT_BETWEEN(s2[i], 65, 90) ? s2[i] + 32 : s2[i];

		if (tmp1 != tmp2)
		{
			return tmp1 < tmp2 ? -1 : 1;
		}

		i++;
	}

	return 0;
}

