/* File: freq2.c
   Counts the frequencies of letters in the input.
   This version uses functions.
*/
#include <stdio.h>
#include "simpio.h"
#include "genlib.h"
#include "strlib.h"

void count_freq(string str, int freq[]) ;
int minimum(int A[], int size) ;
int maximum(int A[], int size) ;
double average(int A[], int size) ;

main() {
   string str ;
   int i, freq[26] ;
   char c ;

   /* Get input */
   printf("Enter a line: ") ;
   str = GetLine() ;

   count_freq(str, freq) ;

   /* Report statistics */
   for (i = 0 ; i < 26 ; i++) {
      c =  'a' + i ;
      printf("The letter %c appeared %d times\n", 
	      c, freq[i]) ;
   }
   printf("Minimum : %d\n", minimum(freq, 26) ) ;
   printf("Maximum : %d\n", maximum(freq, 26) ) ;
   printf("Average : %f\n", average(freq, 26) ) ;
}


/* 
   This function tabulates the number of occurences
   of each letter of the alphabet in the string str.
*/

void count_freq(string str, int freq[]){
   int i, index, length ;
   char c ;

   for (i = 0 ; i < 26 ; i++) {
      freq[i] = 0 ;
   }
   /* Compute frequencies */
   length = StringLength(str) ;
   for (i = 0 ; i < length ; i++) {
      c = IthChar(str, i) ;
      if ( isalpha(c) ) {
	c = tolower(c) ;
	index = c - 'a' ;
	freq[index]++ ;  
      } 
   }
}


/*
   This function returns the smallest value
   in the array A[].
*/

int minimum(int A[], int size) {
   int i, min ;

   min = A[0] ;
   for (i = 1 ; i < size ; i++) {
      if ( A[i] < min ) min = A[i]  ;
   }
   return (min) ;
}


/* 
  This function returns the largest value
  in the array A[].
*/

int maximum(int A[], int size) {
   int i, max ;

   max = A[0] ;
   for (i = 1 ; i < size ; i++) {
      if ( A[i] > max ) max = A[i]  ;
   }
   return (max) ;
}


/*
   This function returns the average value
   in the array A[].  The return value is
   a double.
*/

double average(int A[], int size) {
   int i ;
   double sum ;

   sum = 0.0 ;
   for (i = 0 ; i < size ; i++) {
      sum += (double) A[i] ;
   }
   return(sum/((double) size)) ;
}

