package mcmas.core.examples;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import mcmas.core.MCMCommandQueue;
import mcmas.core.MCMContext;
import mcmas.core.MCMEvent;
import mcmas.core.MCMKernel;
import mcmas.core.MCMMem;
import mcmas.core.MCMProgram;

import org.jocl.Pointer;


public class MCMRandom {
	
	private final static int SIZE = 50;
	
	public static void main(String[] args) throws IOException, InterruptedException {
		MCMContext context = new MCMContext();
		MCMCommandQueue queue = context.createCommandQueue();
		MCMProgram program = context.createProgram(
				readFileAsString("/home/glaville/rand.cl"));
		MCMKernel kernel = program.createKernel("randtest");
		
		int buffer[] = new int[SIZE];
		
		for (int i = 0; i < buffer.length; i++) {
			buffer[i] = i;
		}
		
		//OCLMem bufferMem = context.createBuffer(SIZE, OCL.INT, OCL.MEM_RW, Pointer.to(buffer));
		MCMMem bufferMem = context.newBuffer().Using(buffer).b();
		
		kernel.setArguments(bufferMem, SIZE, (new Date()).getTime());
		
		MCMEvent e = queue.enqueue1DKernel(kernel, 1, 1);
		try {
			e.get();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}
		
		queue.blockingReadBuffer(bufferMem, Pointer.to(buffer), 0, bufferMem.getSize());
		
		System.out.println(Arrays.toString(buffer));
		System.out.println(Arrays.toString(buffer));
	}
	
	private static String readFileAsString(String filePath) throws java.io.IOException{
	    byte[] buffer = new byte[(int) new File(filePath).length()];
	    FileInputStream f = null;
	    
	    try {
	    	f = new FileInputStream(filePath);
	    	f.read(buffer);
	    } finally {
	    	f.close();
	    }
	    
	    return new String(buffer);
	}

}
