import java.io.File;
import java.io.IOException;

/**
 * A program to run the Caesar cipher encryptor with
 * command line arguments.
 * @version 1.0
 */
public class Crypt {  
  public static final int DEFAULT_KEY = 3;

  public static void main(String[] args) {  
    boolean decrypt = false;
    int key = DEFAULT_KEY;
    File inFile = null;
    File outFile = null;

    if (args.length < 2 || args.length > 4) {
      usage();
    }

    try {  
      for (int i = 0; i < args.length; i++) {  
	if (args[i].charAt(0) == '-') {  
	  // it is a command line option
	  char option = args[i].charAt(1);
	  if (option == 'd') {
	    decrypt = true;
	  } else if (option == 'k') {
	    key = Integer.parseInt(args[i].substring(2));
	  }
	} else {  
	  // it is a file name
	  if (inFile == null) {
	    inFile = new File(args[i]);
	  } else if (outFile == null) {
	    outFile = new File(args[i]);
	  } else {
	    usage();
	  }
	}
      }
      if (decrypt) {
	key = -key;
      }
      Encryptor crypt = new Encryptor(key);
      crypt.encryptFile(inFile, outFile);
    } catch (NumberFormatException exception) {  
      System.out.println("Key must be an integer: " + exception);
    } catch (IOException exception) {  
      System.out.println("Error processing file: " + exception);
    }
  }

  /**
   * Prints a message describing proper usage and exits.
   */
  public static void usage() {  
    System.out.println("Usage: java Crypt [-d] [-kn] infile outfile");
    System.exit(1);
  }
}
