import java.util.*;
import java.rmi.*;
import java.rmi.server.*;
import java.math.*;

public class MergeImpl extends UnicastRemoteObject implements Stream, Runnable{

   IntObject val1, val2, first;
   Stream stream1, stream2;
   Monitor monitor;
   
   public MergeImpl (Stream s1, Stream s2) throws RemoteException {  
      super();  
      stream1 = s1;
      stream2 = s2;
      monitor = new Monitor(this);
   }

   public Object next () throws RemoteException { return monitor.next(); }

   public void run () {
      try {
	 val1 = (IntObject)stream1.next();
	 val2 = (IntObject)stream2.next();
      
	 while (true) {
	    if (val1 == null && val2 == null) monitor.putIt(null);
	    else if (val1 == null) {
	       monitor.putIt(val2);
	       val2 = (IntObject)stream2.next();
	    } else if (val2 == null) {
	       monitor.putIt(val1);
	       val1 = (IntObject)stream1.next();
	    } else if ((((IntObject)(val1)).valueOf()).compareTo( 
		        ((IntObject)(val2)).valueOf()) < 0) {
	       monitor.putIt(val1);
	       val1 = (IntObject)stream1.next();
	    } else {
	       monitor.putIt(val2);
	       val2 = (IntObject)stream2.next();
	    }
	 }
      } catch (Exception e) {
	 System.out.println("Merge Error:"+e.toString());
      }
   }
}

