#include <stdio.h>

#define FAIL -1
#define OK 0
#define N ('z'-'a'+1)
#define BOUND 100000

int main(int argc, char **argv){
    FILE *fin;
    int freqs[N]={0};
    char c;
    int r, j, i, len=0, count=0;
    float fs = 1.0/N;
    float fried=0;
    float langFried;
    float eKey;
    if (argc<3) return FAIL;
    
    fin=fopen(argv[1], "r");
    sscanf(argv[2], "%f", &langFried);

    fscanf(fin, "%c", &c);
    while(!feof(fin)){
        len++;
        if (c>='A' && c<='Z') c=c-'A'+'a';
        if (c>='a' && c<='z'){ 
            freqs[c-'a']+=1;
            count++;
        }
        r=fscanf(fin, "%c", &c);
    }
    close(fin);

    for(i=0; i<N; i++){
        float v = freqs[i]/(float)count;
        fried += v*v;
    }

    len=count;
    printf("Ciphertext length: %d\n", len); 
    printf("Friedman Index for ciphertext: %f\n", fried);
    printf("Friedman Index for language: %f\n", langFried);
    printf("Friedman Index for random characters: %f\n", fs);
    printf("Num: %f; Den: %f\n", (langFried-fs)*len, (len-1)*fried + langFried - fs*len); 
    eKey = (langFried - fs)*len / ((len-1)*fried + langFried - fs*len); 

    printf("Estimated Key length: %f\n", eKey);

    return OK;
}

