#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>



int main(int argc, char ** argv){

int c=0;
int count=0;
int total=0;
int len=0;
int code=0;
int round=0;
int farray[26]={0};
int temp=0;
double index=0;
double period=0;

	if (argc==2){
		len = strlen(argv[1]);
		for (count=0;count<len;count++){
			
			switch(argv[1][count])
			{
				case 'o': code = code |1;
					break;
				case 'h': code = code |2;
					break;
				case 't': code = code |4;
					break;
				case '-':
					break;
				case 'i': code = code|16;
					break;
				case 'p': code = code|32;
					break;
				case 's': code = code|64;
					break;

				default: 
					printf("bad option %c \n",(char)argv[1][count]);
					code  = code|8;
			};	
		}	
	}


	
	if (argc >2 || ((code|8)==code)){
		printf("Usage: flc [-ohtip]\n\nflc -h <enter> shows help information");
		exit(1);
	}


	if ((code|2)==code) {

		printf("example usage: flc -on <enter>\n\n");
		printf("   -s SUMMARY\n");
		printf("   -t SHOW TOTAL FREQUENCY\n");
		printf("   -o SHOW LIST ORDERED BY FREQ\n");
		printf("   -h THIS HELP\n");
		printf("   -i PRINT INDEX OF COINCIDENCE\n");
		printf("   -p PRINT ESTIMATED PERIOD (based upon index of co-incidence)\n");
		printf("This program retrieves text from standard input\n\n");
		exit(1);
	}

	while((c=getchar())!=-1){
		c=tolower(c) - 'a';
		
		if (c>=0 && c<26){
			farray[c]++;
			total++;
		}

	} 


	// now work out index of coincedence
	if ( ((code|16)==code) || ((code|32)==code) ){

		for (count=0;count<26;count++){
			index+= (  ((double)farray[count]) * ( (double)farray[count]-1));
		}
		index = index  /  (double) ( (double)total   *((double)total-1));
	}
	
	if ((code|64)!=code){
	
		//sort and printout
		if ((code|1)==code){
			for (round=0;round<26;round++){
				for (count=0;count<26;count++){
					if (farray[count]>farray[temp])
						temp=count;
				}
				printf("%c %d\n",((char)(temp+'a')), farray[temp]);
				farray[temp]=-1;
				temp=0; 	
			}
	
		}
		else{	// just regular printout will be faster
			for (count=0;count<26;count++){
				printf("%c %d\n",((char)(count+'a')), farray[count]); 	
			}
		}

	}// end of code 64 if statement block	


	if ((code|4) ==code ) printf("total_Alphabetic_characters %d\n", total);
	
	if ((code|16)==code) printf("ioc %lf\n", index);

	if ((code|32)==code){
	
		period = (0.027*(double)total) /
			 ((double)(index*((double)total-1)) - (0.038*((double)total)) +0.65);	
		
		printf("estimated_period %fl\n",period);
	}
	
	
return 0;
}
