/*
 * Aleph Toolkit
 *
 * Copyright 1999, Brown University, Providence, RI.
 * 
 *                         All Rights Reserved
 * 
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose other than its incorporation into a
 * commercial product is hereby granted without fee, provided that the
 * above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Brown University not be used in
 * advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission.
 * 
 * BROWN UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY
 * PARTICULAR PURPOSE.  IN NO EVENT SHALL BROWN UNIVERSITY BE LIABLE FOR
 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package aleph;

import aleph.comm.Address;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.NoSuchElementException;

/**
 * A PE group is a colleciton of PEs that run together and know about each
 * other.
 *
 * @author Maurice Herlihy
 * @date August 1998
 **/

public final class PEGroup {
  private static final boolean DEBUG = false;

  private PE[] group;
  private String label;

  /**
   * Construct a PE Group, round-robin through hosts.
   * @param hosts enumerates hosts
   * @param label group-wide label
   * @param numPEs how many PEs in group?
   * @param args user-supplied args
   **/
  public PEGroup (Enumeration hosts, String label, int numPEs, String[] args) {
    this.label = label;
    this.group = PE.makeGroup(hosts, label, numPEs, args);
    if (DEBUG)
      AlephDebug.println("new PEGroup[" + label + ", size " + group.length +"]");
  }

  public Enumeration elements() {
    return new Enumeration() {	// Anonymous enumerator class
      int i = 0;
      public boolean hasMoreElements() {
	return i < group.length;
      }
      public Object nextElement() throws NoSuchElementException {
	if (i == group.length) // got milk?
	  throw new NoSuchElementException();
	return group[i++];
      }
    };
  }

  /**
   * @return how many PEs in this group
   **/
  public int size() {
    return group.length;
  }

  public String toString() {
    StringBuffer s = new StringBuffer(label);
    s.append("[");
    s.append(group[0]);
    for (int i = 1; i < group.length; i++) {
      s.append(", ");
      s.append(group[i]);
    }
    s.append("]");
    return s.toString();
  }

  public void stop() {
    PE.stopGroup(group);
  }


}
