
// Splitter.java
// Michele Loreti and the jSpace Developers, 2017
// Modified by Andrew Davison, ad@coe.psu.ac.th, May 2023

/* A Splitter thread gets a tuple of the form:
      ("SPLITING", arr)

   and puts out two new SPLITING tuples with the
   lower and upper halves of arr.

   However, when the array size == 1, then a 
   (MERGING, arr) is put out which will trigger the Merging
   threads.

   Usage:
    > compile.bat Splitter.java

    Part of the application made up of:
       * SpaceSorter.java
       * Splitter.java
       * Merger.java
*/

import org.jspace.*;

import java.util.*;


public class Splitter implements Runnable
{
  private Space space;
  private PrintAreas pas;
  private String title;


  public Splitter(int id, PrintAreas pas, Space s)
  {
    this.pas = pas;
    space = s;
    title = "Splitter-"+id;
    pas.setTitle(id, title);
  }


  public void run()
  {
    try {
      while (true) {
        // get an array
        Object[] parts = space.get( 
                         new ActualField("SPLITING"),
                         new FormalField(Object.class));
        int[] arr = (int[])parts[1];
        pas.println(title, "Got " +  Arrays.toString(arr));

        if (arr.length == 0)  // should not happen
          continue;
        else if (arr.length == 1)
          // time to start merging the subarrays back together
          space.put("MERGING", arr);
        else { // split into two, and put into the space
          int len = arr.length;
          int[] a = Arrays.copyOfRange(arr, 0, len/2);
          int[] b = Arrays.copyOfRange(arr, (len/2), len);
          space.put("SPLITING", a);
          pas.println(title, "Put " + Arrays.toString(a));
          space.put("SPLITING", b);
          pas.println(title, "Put " + Arrays.toString(b));
        }
      }
    }
    catch (Exception e) 
    {  System.out.println(e);  }
  } /* run */


}  // end of Splitter class
