/*
  Caesar Decrypting-Cipher
  
  By haxpor, haxpor@gmail.com, http://haxpor.org
  Usage: caesar-d <inputfile> <k>
  
  Version 0.01
  
  Note: Only takes the input text as the lower case, and the possible chracters are only plaintext.
*/

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    //check parameter count
    if(argc != 3)
    {
            printf("Usage: caesar-d <inputfile> <k>\n");
            exit(-1);
    }
    
    //input file
    FILE *fp;
    fp = fopen(argv[1], "r");
    if(fp == NULL)
    {
          printf("Error reading file.\n");
          exit(-1);
    }
    
    //reuse buff as out array too
    char buff[1024+1];
    int len = fread(buff, sizeof(char), 1024, fp);
    fclose(fp);
    buff[len] = '\0';
    
    //k
    int k = atoi(argv[2]);
    
    //char table
    char ctable[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
         'w', 'x', 'y','z'};
    
    //decrypt (to lower case only)
    int i;
    for(i=0; i<len; i++)
    {
             //only in 'a'-'z' range
             if(buff[i] >= 'a' && buff[i] <= 'z')
             {
                 //lower case
                 int c = tolower(buff[i]) - (int)'a';
                 //print
                 int index = (c-k) % 26;
                 if(index < 0)
                          index += 26;
                 buff[i] = ctable[index];
             }
    }
    printf("%s\n", buff);
    
    return 0;
}
