/* Solution: A Coincidental Note (con't) */
/* E. Jason Riedy, ejr@cise.ufl.edu */
/*
  This is simply trivial.  There are quite a few C-isms, but
  that's just because there's no incredibly uniform way for dealing
  with characters.  I love the Pascal/Modula family's Ord() operators,
  but C makes everything so easy to type...
*/

#include<stdlib.h>
#include<stdio.h>
#include<ctype.h>

enum { MAX_LEN = 1000 };

void translate( int len, char* ctext, char* out_text, char diff )
{
  int i;

  for (i = 0; i < len; i++) 
    out_text[i] = (((ctext[i]-'a') + diff + 26)%26) + 'a';
  out_text[i] = '\000';
}

void main(void) 
{
  char ctext[MAX_LEN + 1];
  char out_text[MAX_LEN + 1];
  int len;

  int occurance[26];
  char most_common, diff, in;

  int i;

  printf("Ciphertext: ");
  len = 0;
  while (len < MAX_LEN) {
    ctext[len] = getchar();
    if (isalpha(ctext[len])) {
      ctext[len] = tolower(ctext[len]);
      len++;
    }
    else if ('\n' == ctext[len]) {
      ctext[len] = '\000';
      break;
    }
  }

  for (i = 0; i < 26; i++)
    occurance[i] = 0;
  
  for (i = 0; i < len; i++)
    occurance[ctext[i] - 'a']++;

  most_common = ctext[0] - 'a';
  for (i = 1; i < len; i++)
    if (occurance[ctext[i] - 'a'] > occurance[most_common])
      most_common = ctext[i] - 'a';
  most_common += 'a';
  diff = 'e' - most_common;

  translate (len, ctext, out_text, diff);
  printf("Attempt: %s\n", out_text);

  printf("Rotate `%c' to: ", most_common);
  scanf(" %c", &in);
  while (isalpha(in)) {
    diff = in - most_common;
    translate (len, ctext, out_text, diff);
    printf("Decoded: %s\n", out_text);
    printf("Rotate `%c' to: ", most_common);
    scanf(" %c", &in);
  }
}

