
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
#include<string.h>

	char l[]={" .,!?(){};\n\t"};
	struct  q {char * w;int count;struct q *p;}n;

int letter(char x)
{       int q=0,i=0;

	while(l[i]!=NULL) {q+=(l[i]==x);i++;}
	x|=32;
	q+=2*((x>='a')&&(x<='z')||(x>159)&&(x<192));
	return q;
}
// leter -------
void mems(char *word)
{	struct q *p=&n;

	while(p->p) p=p->p;
	if((p->p=(struct q *)malloc(sizeof(n)))==NULL) {printf("NO MEMORY");exit(0);}
	p=p->p;
	p->p=0;
	if((p->w=(char *)malloc(strlen(word)+1))==NULL) {printf("NO MEMORY");exit(0);}
	strcpy(p->w,word);p->count=1;
}
//===========
void memfree()
{	struct q *p=0;

	while(p!=&n)
   {	if(n.p==NULL) break;
	p=&n;
	while((p->p)->p) p=p->p;
	free((p->p)->w);
	free(p->p);p->p=NULL;
    }
}
//------------------

int gword(char *word,FILE *fh)
{	char x;int i=0;

	do x=fgetc(fh);
	while (((!feof(fh)))&&(letter(x)==1));
	while (((!feof(fh)))&&(letter(x)!=1)) {word[i]=x|(32*(letter(x)==2));i++;x=fgetc(fh);}
	word[i]=NULL;
	return !feof(fh);
}
// get word -----------
void stick(char *word)
{
	int i=0;struct q *p=n.p;

	while(p&&strcmp(p->w,word)) p=p->p;
	if(p)
	p->count++;
	else mems(word);
}
//---------------
void sorting(FILE *fd)
{ 	int i=0;struct q *p=n.p,*q;int mc=0,wc=0;

	while(p) {wc++;p=p->p;}
	while(wc)
    {
	p=n.p;mc=0;
	while (p) {if (p->count>mc){mc=p->count;q=p;} p=p->p;}
	i++;
	fprintf(fd,"\n%d: %s  - %d",i,q->w,q->count);
	q->count=0;wc--;
     }
}
//-------------------
int main()
{ char word[300],fname[15];
	FILE *fh,*fd;
	struct q *p=&n;
	n.p=NULL;

	printf("\n INPUT SOURCE FILE NAME ");
	scanf("%s",fname);
	if((fh=fopen(fname,"r"))==NULL){printf("s file");exit(0);}
	printf("\n TYPE DESTINATION FILE ");
	scanf("%s",fname);
	if((fd=fopen(fname,"w"))==NULL){printf("d file");exit(0);}

	while (gword(word,fh))	stick(word);
	if(word[0]) stick(word);

	sorting(fd);

	fclose(fh);fclose(fd);
	memfree();
	return(0);
}
//------END