
// Caesar.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* The Caesar Cipher is a substitution cipher in which each 
   letter in the plaintext is replaced by a letter some
   fixed number of positions down the alphabet (modulo
   the size of the alphabet). 

   https://en.wikipedia.org/wiki/Caesar_cipher

   Usage:
     > compile Caesar.java
     > run Caesar <message> <shift no>
   e.g.
     > run Caesar "Andrew" 5
*/


public class Caesar
{

  public static void main(String[] args)
  {
    if (args.length != 2) {
      System.out.println("Usage: run Caesar <message> <shift no>");
      return;
    }
    System.out.println("Message: \"" + args[0] + "\"");
    int shift = Math.abs(Nut.parseInt(args[1])) % 26;
    System.out.println("Shift: " + shift);

    String cipher = encode(args[0], shift);
    System.out.println("Encrypted message : \"" + cipher + "\"");

    String decipher = decode(cipher, shift);
    System.out.println("Decrypted message : \"" + decipher + "\"");
  } /* main */



  public static String encode(String msg, int shift)
  // shift every char forward by the shift number
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < msg.length(); i++) {
      char ch = msg.charAt(i);       
      if (Character.isUpperCase(ch)) {
        ch += shift;
        sb.append((char) (ch > 'Z' ? ch - 26 : ch));         
      }
      else if (Character.isLowerCase(ch)) {
        ch += shift;
        sb.append((char) (ch > 'z' ? ch - 26 : ch));         
      }
      else
        sb.append(ch);
    }
    return sb.toString();
  } /* encode */



  public static String decode(String msg, int shift)
  // shift every char back by the shift number
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < msg.length(); i++) {
      char ch = msg.charAt(i);
      if (Character.isUpperCase(ch)) {
        ch -= shift;
        sb.append((char) (ch < 'A' ? ch + 26 : ch)); 
      }
      else if (Character.isLowerCase(ch)) {
        ch -= shift;
        sb.append((char) (ch < 'a' ? ch + 26 : ch)); 
      }
      else
        sb.append(ch);
    }
    return sb.toString();
  } /* decode */


}  // end of Caesar class
