// © National University of Singapore. All rights reserved.

// Department of Computer Science
// National University of Singapore
// 3, Science Drive 2, Singapore 117543
// Tel: (65) 874 2830 Fax: (65) 779 4580

// SuperPing.java 
// models the Super-Ping simulation
import spades_Java.*;
import java.io.*;

public class SuperPing extends Executive {
   public static int Left = 0;
   public static int Right = 1;
   public static int NumObj = 256;
   Resource LP[];

  // initialization
  public void init()
  {
    int i, ppno, lpno = NumObj;
    Ball ball, ball2;
    
    LP = new Resource[NumObj];

    for (i=0; i<NumObj; i++) 
    {
      LP[i]  = new Resource("PingObject["+i+"]",1);
      
      // initialize each ping object with 2 messages (left and right)
      ball = new Ball("LBall "+i,this);
      ball.direction = Left;
      ball.dest = i;
      mapProcess(ball, LP[i]);
      activate(ball, exponential(0.1));
      
      ball2 = new Ball("RBall "+i,this);
      ball2.direction = Right;
      ball2.dest = i;
      mapProcess(ball2, LP[i]);
      activate(ball2, exponential(0.1));
    }
  }

  // main program
  public static void main(String args[])
  {
    SuperPing sc = new SuperPing();
    sc.initialize(args.length,args);
    sc.startSimulation();
  }
}

// models a Ball process
class Ball extends SProcess {
  int dest;
  int direction;
  SuperPing sc;
  
  public Ball(String name, SuperPing sp)
  {
    super(name, 1);
    sc = sp;
  }

  public void execute()
  {
	switch(getPhase())
	{
		case 1	:
		{
    			int src;
   				src = dest;
    			if (direction == sc.Left) 
   				{
      	 		if (dest == sc.NumObj - 1)
          		dest = 0;
     	 			else
         			{ dest += 1;}
    			}
    			else 
    			{
        			if (dest == 0)
         				dest = sc.NumObj - 1;
         			else
         			{ dest -= 1;}
    			}      
  	  	// display the motion of the current Ball
    		work(sc.LP[dest], 0.1+exponential(1.0), 1);
				break;
    	}
  }
}
}

