// GESTALT.C : A fuzzy compare.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


// Performs a 'fuzzy' comparison between two strings.  Returns how
// 'alike' they are expressed as a percentage match.
//
// Written originally by John W. Ratcliff for Dr. Dobbs Journal
// of Software Tools Volume 13, 7, July 1988
//
// Pages 46, 47, 59-51, 68-72
// http://www.ddj.com/184407970?pgno=5
//
// http://www.codesuppository.blogspot.com/
//
// If you appreciate my little snippets of source code
// please donate a few bucks to my kids youth group fundraising
// website located at http://www.amillionpixels.us/


#include "gestalt.h"
#include <string.h>

#ifdef  __cplusplus
extern "C" {
#endif

static int GCsubstr(const char *st1,const char *end1,const char *st2,const char *end2)
{
  const char *s1;
  const char *s2;
  int max = 0;
  const char *b1 = end1;
  const char *b2 = end2;
  int i;
	const char *a1;
	const char *a2;


  if (end1 <= st1) return 0;
  if (end2 <= st2) return 0;
  if (end1 == (st1+1) && end2 == (st2+1) ) return 0;


  for (a1 = st1; a1 < b1; a1++)
  {
    for (a2 = st2; a2 < b2; a2++)
    {
      if (*a1 == *a2)
			{

				for (i=1; a1[i] && (a1[i] == a2[i]); i++);

        if (i > max)
				{
					max = i; s1 = a1; s2 = a2;
					b1 = end1 - max; b2 = end2 - max;
				}

			}
    }
  }

  if (!max) return 0;

  max += GCsubstr(s1+max, end1, s2+max, end2);
  max += GCsubstr(st1, s1, st2, s2);

  return max;
}


int FuzzyCompare(const char *s1,const char *s2)
{
	int l1,l2;

  if ( strcmp(s1,s2) == 0 ) return 100;

	l1 = (int)strlen(s1);
	l2 = (int)strlen(s2);

  if (l1 == 1)
    if (l2 == 1)
      if (*s1 == *s2)
        return(100);

  return(200 * GCsubstr(s1, s1+l1, s2, s2+l2)/ (l1+l2));
}


#ifdef  __cplusplus
}
#endif

