package WeekTwo;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
	
public class WeekTwo {
  public static void main (String[] args) throws IOException {
	
	  // grab input
    FileInputStream fis = new FileInputStream(args[0]);
    FileChannel fc = fis.getChannel();
	
    //Integer iArg = new Integer(args[2]);
    //int lengthArg = iArg.intValue();
                         

    ByteBuffer bb = ByteBuffer.allocate((int)fc.size());
    fc.read(bb);
    fc.close();
	
	  // put in string, route out words of size into arraylist
    String content = new String(bb.array());
	
    // grab any words that somehow appear as R?? A?? B?? one right after another
    ArrayList finds = new ArrayList();
    
    String regex = "\\b(r[a-zA-Z]+)\\b\\s+\\b(a[a-zA-Z]+)\\b\\s+\\b(b[a-zA-Z]+)\\b";               
    Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);   
    
    Matcher m = p.matcher(content);         // Create Matcher
    while (m.find()) {
      //System.out.print(m.group());
      finds.add(m.group());
    }
    
    String wordsOfMerit = "";
    for(int i=0;i<finds.size();i++){
    	wordsOfMerit += (String)finds.get(i);
    	wordsOfMerit += "\n\n";
    }

	  // wrap string into bytearray and send out
    FileOutputStream fos = new FileOutputStream(args[1]);
    FileChannel outfc = fos.getChannel();
	
    //String forOutput = new String(wordsOfMerit.toString());
    byte[] forOutputB = wordsOfMerit.getBytes();
    ByteBuffer bbOut = ByteBuffer.wrap(forOutputB);
    outfc.write(bbOut);
    outfc.close();
    System.out.print(wordsOfMerit);
  }
}