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

int calculateKey(char letter, int key, int start_key)
{
  key = key == 0 ? start_key : (toupper(letter + 1) - 65) % key;
  key %= 26;
  return key;
}

char cntelements(char* element_str)
{
  int elements;

  for(elements = 0; element_str[elements] != '\0'; ++elements)
  {
    elements = elements + 1;
  }

  return elements;
}

char encodeLetter(char letter, int key)
{
  int shiftDirection = (key % 2 == 0) ? key : -key;
  int shifted = letter + shiftDirection;
  int letter_param;

  if (letter > 96 && letter < 123)
  {
    if (shifted < 97)
    {
      letter_param = 122 - (97 - shifted) + 1;
    }

    else if (shifted > 122)
    {
      letter_param = 97 + (shifted - 122) - 1;
    }
    
    else
    {    
      letter_param = shifted;
    }
    return letter_param;
  }

  if (letter > 64 && letter < 91)
  {
    if (shifted < 65)
    {
      letter_param = 90 - (65 - shifted) + 1;
    }

    else if (shifted > 90)
    {
      letter_param = 65 + (shifted - 90) - 1;
    }

    else
    {    
      letter_param = shifted;
    }
    return letter_param;
  }

 
    return letter;
}

unsigned int cipher(char* cipher_str, int start_key)
{
  int cntChars = 0;
  int elements = cntelements(cipher_str);
  int i;
  int key = 0;
 
  for(i = 0; i <= elements; i++)
  {
    
    if((cipher_str[i] < 91 && cipher_str[i] > 64) ||
    (cipher_str[i] < 123 && cipher_str[i] > 96))
    {        
      cntChars++;
    }
    key = calculateKey(cipher_str[i], key, start_key);
    printf("%d\n", key);
    cipher_str[i] = encodeLetter(cipher_str[i], key);
  }

  return cntChars;
}

int main()
{
	char word[] = "GGGG";
	cipher(word, 50);
	printf("%s", word);
}