// Example program for CISC181, fall 2011
// by Christopher Rasmussen
// University of Delaware

import java.io.*;
import java.util.*;

public class mutatefile {

	BufferedReader reader;
	FileWriter writer;
	static final double MUTATION_RATE = 0.1;	
	
	//----------------------------------------------------------------------------

	// generate random lower-case letter
	
	static char rand_letter()
	{
		Random r = new Random();
		char c = (char)('a' + r.nextInt(26));
		return c;
	}

	//----------------------------------------------------------------------------

	// actually read input file and write output file
	
  void do_mutate()
  {
  	int result;
  	int num_chars = 0;
  	int num_chars_changed = 0;
  	char c;
  		
  	try {
  		
  		while (true) {
  			
  			// get a character from the file
  			
  			result = reader.read();
  			
  			// end of file?
  			
  			if (result == -1)
  				break;
  			
  			num_chars++; 
  			
  			 // mutate? (don't touch spaces)

  			c = (char) result;
  			
  			if (!Character.isWhitespace(c) && Math.random() < MUTATION_RATE) {
  	      c = rand_letter();
  	      num_chars_changed++;
  			}
  	 
  			writer.write(c);
  		}

  		reader.close();
  		writer.close();
  		
  		System.out.println(num_chars + " total chars (including whitespace)");
  		System.out.println(num_chars_changed + " total chars CHANGED (mutation rate = " + MUTATION_RATE + ")");
  		
  	} catch (Exception ex) {
  		System.out.println("Error during reading/writing");
  		ex.printStackTrace();
  	}
  	
  }
	
  //----------------------------------------------------------------------------

  // constructor: tries to open files to read from, write to
 
  mutatefile(String in, String out)
  {
  	try {
			
		File inFile = new File(in);
		
		FileReader fileReader = new FileReader(inFile);	
		reader = new BufferedReader(fileReader);
		
		writer = new FileWriter(out);
		
  	} catch (Exception ex) {
  		System.out.println("Error trying to open input/output files");
  		ex.printStackTrace();
  	}
  }
  
  //----------------------------------------------------------------------------

	public static void main(String[] args) {
		
		mutatefile M = new mutatefile("input.txt", "mutated_input.txt");
		M.do_mutate();
	}
}
