/** CaesarCipher.java implements the Caesar cipher algorithm.
 * @author Joel Adams, for Alice+Java.
 */

import java.util.Scanner;
import java.io.*;           // File, PrintWriter, ...

public class CaesarCipherCoder {	
	public void encodeFile(Scanner fin, int shift, PrintWriter fout) {
		if (fin == null || shift <= 0 || fout == null) {
			throw new IllegalArgumentException("encodeFile(): bad argument");
		}
		while ( fin.hasNextLine() ) {
			String line = fin.nextLine();
			String lineEncoded = encodeString(line, shift);
			fout.println(lineEncoded);
		}
	}

	public String encodeString(String str, int shiftAmount) {
		if (shiftAmount <= 0) {
			throw new IllegalArgumentException("encodeString(): bad argument");
		}
		String codedStr = "";
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			char chEncoded = encodeChar(ch, shiftAmount);
			codedStr += chEncoded;
		}
		return codedStr;
	}

	public char encodeChar(char ch, int shiftAmount) {
		if (shiftAmount <= 0) {
			throw new IllegalArgumentException("encodeChar(): bad argument");
		}
		char chEncoded;
		if ( Character.isUpperCase(ch) ) {
			int chEncodedAsInt = ((ch - 'A' + shiftAmount) % 26) + 'A';
			chEncoded = (char) chEncodedAsInt;
		} else {
			chEncoded = ch;
		}
		
		return chEncoded;
	}

	public static void main(String[] args) {
		System.out.println("Welcome to the Caesar Cipher file encoder");
		Scanner in = FileOps.promptForFileIn("Input file name? ");
		System.out.print("How many positions are chars to be shifted? ");
		int shiftAmount = FileOps.kbd.nextInt();
		PrintWriter out = FileOps.promptForFileOut("Output file name? ");
		CaesarCipherCoder ccCoder = new CaesarCipherCoder();
		ccCoder.encodeFile(in, shiftAmount, out);
		in.close();
		out.close();
		System.out.println("Processing complete.");
	}	
}
