package WeekOne;

/*
	Word Size Aggregator
	(first arg is input, second is output, third is size of word)
*/

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.ArrayList;
	
public class WeekOne {
  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());
	
    String[] sContent = content.split(" ");
    ArrayList wordsOfArg = new ArrayList();
    for(int i=0;i<sContent.length;i++){
    	if(sContent[i].length() == lengthArg){
    		wordsOfArg.add(sContent[i]);
    	}
    }
    
	  // throw arraylist into string
    StringBuffer wordsOfSize = new StringBuffer();
    for (int i = 0; i < wordsOfArg.size(); i++) {
       String word = (String)wordsOfArg.get(i);
       wordsOfSize.append(word + " ");
    }

	  // wrap string into bytearray and send out
    FileOutputStream fos = new FileOutputStream(args[1]);
    FileChannel outfc = fos.getChannel();
	
    String forOutput = new String(wordsOfSize.toString());
    byte[] temp = forOutput.getBytes();
    ByteBuffer bbOut = ByteBuffer.wrap(temp);
    outfc.write(bbOut);
    outfc.close();
    System.out.print(forOutput);
  }
}