#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <stddef.h>

size_t duplicate_count(const char *text);
char *myStrdup(const char *text);

int main(void)
{
	char input[1023];
	printf("Enter a string of letters and/or numbers "
			"without any space and press ENTER: ");
	if ((fgets(input, 1023, stdin)) != NULL)
	{
	        printf("Total number of duplicates: %zu\n"
	                 		, duplicate_count(input) );
	}

	return 0;
}

size_t duplicate_count(const char *text)
{
	char *input     = NULL;
	char *distincts = NULL;
	size_t lengthOfInput= 0;
	size_t lengthOfDistincts = 1;
	size_t count = 0;
	size_t dups = 0;

        input = myStrdup(text);
        input[strlen(input) - 1] = '\0';
        lengthOfInput = strlen(input);
        for (size_t i = 0; i  < lengthOfInput; i++)
        {
                if (isalpha(input[i]) && isupper(input[i]))
                {
                        input[i] = tolower(input[i]);
                }
        }
        distincts = realloc(distincts, lengthOfDistincts);
        assert(distincts);
        distincts[0] = input[0];
        distincts[lengthOfDistincts++] = '\0';

	for (size_t i = 1; i <= lengthOfInput; i++)
	{
		if (distincts[0] == input[i])
		{
			count = 1;
		}
		else
		{
			size_t found = 0;
			for (size_t j = 0; j < lengthOfDistincts - 1; j++)
			{
			    if (input[i] == distincts[j])
			    {
				found++;
			    }
			}
			if (!found)
			  {
			    distincts = realloc(distincts, lengthOfDistincts + 1);
			    distincts[lengthOfDistincts - 1] = input[i];
			    distincts[lengthOfDistincts++  ] = '\0';
			  }
		}
	}
	if (count) { dups++; }


	for (size_t i = 1; i < lengthOfDistincts; i++)
	  {
	    size_t occurance = 0;
	    for (size_t j = 0; j < lengthOfInput; j++)
	      {
		if (distincts[i] == input[j])
		  {
		    occurance++;
		  }
	      }
	    if (occurance > 1) { dups++; }
	  }
	free(input);
	free(distincts);

	return dups;
}

char *myStrdup(const char *text)
{
	static char *replicate = NULL;
	size_t lengthOfText = strlen(text) + 1;
	replicate = realloc(replicate, lengthOfText);
	if (replicate == NULL)
	{
		return (char *) NULL;
	}

	return (char *)memcpy(replicate, text, lengthOfText);
}
