<?php

function PIE_settings()
  {
    return array('flags'      => ISF_MCI,
                 'maxspeed'   => 0.2,       // metres/second
                 'mindelay'   => 1,         // seconds, float
                 'maxdelay'   => 3,
                 'insimname'  => 'Flip');
  }

function PIE_commands($command, $args, $ucid)
  {
    switch($command)
      {
        case 'reset':
        case 'rescue':
        case 'pieflip':
          $PIE        = PIE::connect();
          
          $plid       = PIE_PLIDfromUCID($ucid);
          $mindelay   = $PIE->get('PIE_settings',  'mindelay');
          $maxdelay   = $PIE->get('PIE_settings',  'maxdelay');
          
          $delayrange = $maxdelay - $mindelay;
          $delay      = $mindelay + ((mt_rand(0,100)/100) * $delayrange);
          $time       = microtime(true) + $delay;
          PIE_setcallback($time, 'flip', $plid);
          
          PIE_sayto($ucid, 'flip (delayed by '.$delay.')');
      }
  }
  
function flip($plid)
  {
    if (empty($plid))
      return false;
    
    $PIE = PIE::connect();
    $MCI = $PIE->get('PIE_MCI',       $plid);
    $max = $PIE->get('PIE_settings',  'maxspeed');
        
    if (empty($MCI))
      return false;
    
    $speed = ($MCI['Speed'] / 327.68);  
    if ($speed > $max)
      return false;   
    
    $x = round($MCI['X'] / 4096);
    $y = round($MCI['Y'] / 4096);
    $z = max(0, round($MCI['Z'] / 16384))+1;
    $heading = (round($MCI['Heading'] / 256) + 128) % 256;
        
    $packet = array('Type'      => ISP_JRR,
                    'PLID'      => $plid,
                    'JRRAction' => JRR_RESET_NO_REPAIR,
                    'X'         => $x,
                    'Y'         => $y,
                    'Zbyte'     => $z,
                    'Flags'     => 0x80,
                    'Heading'   => $heading);
    PIE_sendpacket($packet); 
  }  