/* 

SIMPLE ENCRYPTION...

DATE: Fri Mar 22 04:36:34 PM EST 2019
AUTHOR: Matthew William Coan

*/

import java.io.*;

public class encrypt {
   public static void main(String args[]) {
      try {
         String keyfile=null,infile=null,outfile=null;
         boolean flag = false;
         for(int i = 0; i < args.length; i++) {
             if(args[i].equals("-keyfile")) {
                i++;
                if(i < args.length) {
                   keyfile = args[i];
                }
             }
             else if(args[i].equals("-infile")) {
                i++;
                if(i < args.length) {
                   infile = args[i];
                }
             }
             else if(args[i].equals("-outfile")) {
                i++;
                if(i < args.length) {
                   outfile = args[i];
                }
             }
             else if(args[i].equals("-encrypt")) {
                flag = true;
             }
             else if(args[i].equals("-decrypt")) {
                flag = false;
             }
         }
         if(keyfile == null || infile == null || outfile == null) {
            System.err.print("usage: encrypt -encrypt | -decrypt -keyfile <keyfile> -infile <infile> -outfile <outfile>\n");
            System.exit(1);
         }
         if(flag) {
            //srand(time(null));
            FileInputStream in = new FileInputStream(infile);
            PrintStream out = new PrintStream(new FileOutputStream(outfile));  
            PrintStream key = new PrintStream(new FileOutputStream(keyfile));  
            int x;
            long temp1,temp2;
            while((x=in.read()) != -1) {
               temp1 = (long)(Math.random() * 1000000000);
               temp1 -= 255;
               temp2 = x + temp1;
               key.println(temp1);
               key.flush();
               out.println(temp2);
               out.flush();
            }
            key.close();
            out.close();
            in.close();
         }
         else {
            DataInputStream in = new DataInputStream(new FileInputStream(infile));
            PrintStream out = new PrintStream(new FileOutputStream(outfile));
            DataInputStream key = new DataInputStream(new FileInputStream(keyfile));
            String key0,data;
            long temp1,temp2,temp3;
            int ch;
            while((data=in.readLine()) != null && (key0=key.readLine()) != null) {
               temp1 = new Long(key0).longValue();
               temp2 = new Long(data).longValue();
               temp3 = temp2 - temp1;
               ch = (int)temp3;
               out.write(ch);
               out.flush();
            }
            key.close();
            out.close();
            in.close();
         }
      }
      catch(Exception ex) {
         System.err.print("error: " + ex.getMessage() + "\n");
         System.exit(1);
      }
   }
}
