/*
 * cc -md lesen; ln +q lesen -lcl
 */

#include	<stdio.h>
#define	MINLANG	3
#define	MAXWORT	65000

#ifdef	GERMAN
char *mess1	= "Es wurden %d Wörter, länger als %d Zeichen, gefunden.\n";
char *mess2	= "Davon finden sich %d verschiedene Wörter im File \"%s\".\n";
char *wordfile	= "Worte";
#else
char *mess1	= "%d words with more than %d characters have been found.\n";
char *mess2	= "There are %d different words in \"%s\".\n";
char *wordfile	= "words";
#endif

char	*worte[MAXWORT];
char	*base,	*ptr,	*mode;
char	buffer[1024];
int	top = 0;

xstrncpy(b,a,n)
char	*a,*b;
int	n;
{   char *h;

    while(*a && n--)
    {	switch(*a)
	{   case 'Ä': *b++ = 'A'; *b++ = 'E';	break;
	    case 'Ö': *b++ = 'O'; *b++ = 'E';	break;
	    case 'Ü': *b++ = 'U'; *b++ = 'E';	break;
	    case 'ß': *b++ = 'S'; *b++ = 'S';	break;
	    default : *b++ = *a;		break;
	} a++;
    }
}

cmp(a, b)
char	**a,**b;
{
    return strcmp(*a,*b);
}

unique()
{   int	test = 0, i;
    int	duplicate = 0;

    for(i=1;i<top;i++)
    {	if(!strcmp(worte[test],worte[i]))
    	{   *worte[i] = 255;
    	    duplicate++;
    	}
    	else	test = i;
    }
    qsort(worte,top,sizeof(char *),cmp);
    for(i=top-duplicate;i<top;i++)	free(worte[i]);
    top = top-duplicate;
}

main(argc,argv)
int	argc;
char	*argv[];
{   int	i = 0,	add = 0;
    FILE	*infile, *outfile;

    if (argc!=2)	{puts("Input-Filename needed!");exit(1);}
    if ((infile = fopen (argv[1], "r")) == NULL) {puts("Wrong Filename");exit(1);}
    do
    {	fgets (buffer,1022,infile);
	ptr = base = buffer;
	while (*ptr)
#ifdef	GERMAN
	{   *ptr = toupper (*ptr);
#else
	{   *ptr = tolower (*ptr);
#endif
	    if(*ptr=='ä')	*ptr = 'Ä';
	    if(*ptr=='ö')	*ptr = 'Ö';
	    if(*ptr=='ü')	*ptr = 'Ü';
#ifdef	GERMAN
	    if ((*ptr<='Z' && *ptr>='A') || *ptr=='Ä' || *ptr=='Ü' || *ptr=='Ö' || *ptr=='ß')
	    {	 if(*ptr=='Ä' || *ptr=='Ü' || *ptr=='Ö' || *ptr=='ß') add++;
#else
	    if ((*ptr<='z' && *ptr>='a'))
	    {	 ;
#endif
	    } else
	    {	if ((ptr-base)>MINLANG)
		{   /* speichern */
		    worte[top] = (char *)malloc (ptr-base+1+add);
		    if (!worte[top]) {puts("memory problems");exit(11);}
		    if(add) xstrncpy (worte[top],base,ptr-base);
		    else strncpy (worte[top],base,ptr-base);
		    worte[top][ptr-base+add] = 0;
#ifdef	DEBUG
		    printf ("|%d>%s\n", top, worte[top]);
#endif
		    top++;
		    if(top>=MAXWORT) goto overflow;
		}
		base = ptr+1;
	        add = 0;
	    }
	    ptr++;
	}
	add = 0;
    }     while (!feof (infile));
overflow:
    fclose (infile);
    qsort (worte, top, sizeof (char *), cmp);
    fprintf (stderr, mess1, top, MINLANG);
    unique ();
    fprintf (stderr, mess2, top, wordfile);
    mode = (strcmp(wordfile,argv[1])) ? "a" : "w";
    if ((outfile = fopen (wordfile, mode)) == NULL) {puts("Filing Problems");exit(1);}
    for(i=0;i<top;i++)
    {	fputs (worte[i], outfile);
	fputc ('\n', outfile);
	free (worte[i]);
    }
    fclose (outfile);
}
