import java.lang.*;
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;

public class DynMcufClientRecv extends Thread
{
  private DatagramSocket sock;
  private InetAddress host;
  private int port;
  private FrameReceiver receiver;
  private boolean termReq = false;

  DynMcufClientRecv( DatagramSocket sock, InetAddress host, int port, FrameReceiver receiver )
  {
    this.sock = sock;
    this.host = host;
    this.port = port;
    this.receiver = receiver;
  }

  public void run( )
  {
    while( ! termReq )
    {
      try
      {
        byte[] data = new byte[8192];
        DatagramPacket framePacket = new DatagramPacket( data, 8192 );
        sock.receive( framePacket );
        if( framePacket.getAddress( ).equals( host ) && framePacket.getPort( ) == port )
        {
          int length = framePacket.getLength( );
          data = framePacket.getData( );
          if( length >= 12 && data[0] == 0x23 && data[1] == 0x54
                           && data[2] == 0x26 && data[3] == 0x66 )
          {
            int height = (data[4] & 0xFF) << 8 | (data[5] & 0xFF);
            int width = (data[6] & 0xFF) << 8 | (data[7] & 0xFF);
            int channels = (data[8] & 0xFF) << 8 | (data[9] & 0xFF);
            int maxval = (data[10] & 0xFF) << 8 | (data[11] & 0xFF);
            if( height >= 1 && height <= 100 && width >= 1 && width <= 100
             && channels >= 1 && channels <= 3 && maxval >= 1 && maxval <= 255
             && length >= 12 + height * width * channels )
            {
              Frame frame = new Frame( height, width, channels );
              frame.setData( maxval, data, 12 );
              receiver.newFrame( frame );
            }
          }
        }
      }
      catch( IOException e ) { }
    }
  }

  public void terminate( )
  {
    termReq = true;
    this.interrupt( );
  }
}
