import net.jini.core.lease.Lease;
import net.jini.space.JavaSpace;
import net.jini.core.entry.Entry;

public class Partition2D extends Master {

    public static void main(String[] args) {
	Partition2D p2d = new Partition2D(args);
    }

    public Partition2D(String[] args) {

        try {

	    if (args.length < 2) {
	    	System.out.print("Usage: java Partition2D "+
					"axisSize blockfactor [-v]\n");
		System.exit(-1);
	    }

	    int arrSize = Integer.parseInt(args[0]);
	    int blockFactor= Integer.parseInt(args[1]);
	    int axisSize = arrSize / blockFactor;
	    int chunkSize = axisSize * axisSize;
	    int numChunks = blockFactor*blockFactor;

	    // This benchmark fabricates a 2D array, with default values of 
	    // zero for each element, as a series of memory Chunks.  Those 
	    // Chunks are then written into a tuplspace and simply taken back
	    // out.  Each dimension of the fabricated array is determined by
	    // the axisSize input parameter, and the number and size of the 
	    // Chunks is determined by the input blockFactor.

	    int i;
            Task [] tasks = new Task[numChunks];
            task = new Task();
	    init(task);

            System.out.print("Subdividing the "+arrSize+"x"+arrSize+
			" array into "+numChunks+" chunks\n");
            System.out.print("A total of "+arrSize*arrSize*4+
				" bytes will be generated (datatype: float)\n");

	    for (i=0; i < numChunks; i++)
		tasks[i] = new ImagePTask(i+1,i*axisSize+1,i*axisSize+1,
							axisSize,axisSize);

	    System.out.print("\nDone, now writing into space ...\n");
	    System.out.print("\n# Size  Blocking  Chunks   ");
	    System.out.println("Put  Objs/Sec   Get   Objs/Sec"+
						"     Total  Objs/Sec\n");
	    timer.checkp();
	    for (i=0; i< numChunks; i++)
		space.write(tasks[i],null,Lease.FOREVER);

	    double t = timer.checkp() / 1000.0;
	    System.out.print("  "+arrSize+"   "+blockFactor+
				"\t  "+numChunks+"\t "+format(t));
	    System.out.print("   "+format(numChunks/t)+"\n\n");

	    task.done = null;
	    snapshot = space.snapshot(task);
            System.out.print("Done, now retrieving from space ...\n\t\t\t\t\t");
	    for (i = 0; i < numChunks; i++)
		task = (Task)space.take(snapshot,null,Long.MAX_VALUE);
	    t = timer.checkp() / 1000.0;
	    System.out.print("   "+ format(t));
	    System.out.print("   "+format(numChunks/t));

	    t = timer.total() / 1000.0;
	    System.out.print("     "+format(t));
	    System.out.println("   "+format(2*numChunks/t));
	    System.exit(0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
