<?php

function PIE_settings()
  {
    return array('flags'      => 0,
                 'insimname'  => 'RandomLights');
  }
  
function PIE_start()
  {
    $PIE = PIE::connect();
    
    $PIE->set('lightids',     array(2,3,4));
    $PIE->set('lightdelay',   4);
    $PIE->set('lightchanges', 0);
  }
  
function PIE_clock($t)
  {
    $PIE = PIE::connect();
    
    $delay = $PIE->get('lightdelay');
    if (!($t%$delay))
      randomiselights();
  }
  
function randomiselights()
  {
    $PIE = PIE::connect();
    
    $lights = $PIE->get('lightids');
    $debugchat = array();    
    foreach($lights as $light)
      {
        $bulbs = mt_rand(0,15);
        PIE_sendpacket(array( 'Type'        => ISP_OCO,
                              'OCOAction'   => OCO_LIGHTS_SET,
                              'Index'       => AXO_START_LIGHTS,
                              'Identifier'  => $light,
                              'Data'        => $bulbs));
                              
        $debugchat[] = '#'.$light.': '.textbulbs($bulbs);
        $debug = $t.' lights #'.$light.' set to '.$bulbs.' ('.textbulbs($bulbs).')';
        PIE_debugout(PIE_DEBUGUSER1, $debug);
      }    
      
    $count = $PIE->get('lightchanges')+1;
    $PIE->set('lightchanges', $count);
      
    if (PIE_debugcheck(PIE_DEBUGUSER2))
      {
        $debug = 'change '.$count.': '.implode(', ', $debugchat);
        PIE_say($debug);
      }
  }
  
function textbulbs($bulbs)
  {
    $return = '';
    $return .= ($bulbs & 1) ? 'R' : '-';
    $return .= ($bulbs & 2) ? 'Y' : '-';
    $return .= ($bulbs & 8) ? 'G' : '-';
    
    return $return;
  }