#List of people on where right now.
%Where = ();

#List of people on where last time.\
%LastWhere = ();

#Interval between wheres in seconds.
$Interval = 1;

#Boolean variable indcating that cpk guard is activated.
$GuardOn = 0;

#
# Notify listeners of updates.
#
sub notify ($) {
  $cmd = shift;
  run("/chatall emote $cmd");
}


#
# Enable CPK guard and notify all people on chat.
#
sub cmd_cpkon {
  notify("${col_Y}----- ${col_R}CPK GUARD ${col_G}ACTIVATED$col_Y -----");
  $GuardOn = 1;
  make_event(2, "where");
}
  
#
# Disable CPK guard and notify all people on chat.
#
sub cmd_cpkoff {
  if ($GuardOn == 0) {
    return 1;
  }

  # Remove the where event.
  delete_event("where");

  # Turn off the triggers.
  $GuardOn = 0;

  #Notify the listeners.

  notify("${col_Y}----- ${col_R}CPK GUARD DEACTIVATED$col_Y -----");
}


#
# If watching, match text in where listing.
#
sub watch_where {
  if ($GuardOn == 0) {
    return 1;
  }
  $text = $_;
  $text =~ s/(\xEA.|\xEA\n)//g;

  if ($text =~ /Players in your vicinity:/) {
    %Where = ();
  }
  if ($text =~ /\[(\w+)\s+] - (.*)/) {
    $Where{$1} = $2;
  }
}

#
# Once we receive a prompt, compare results to last where.
#
sub where_prompt {
  if ($GuardOn == 0) {
    return 1;
  }
  foreach $person (keys %Where) {
    if ((!exists $LastWhere{$person}) || ($LastWhere{$person} ne $Where{$person})) {
      $LastWhere{$person} = $Where{$person};
      notify("${col_c}$person ${col_B}--> $col_W$Where{$person}");
    }
  }
  foreach (keys %LastWhere) {
    if (!exists $Where{$_}) {
      notify("\n$col_C$_ ${col_B}has LEFT WHERE.");
      delete $LastWhere{$_};
    }
  }
}

sub cmd_cpkwhere {
  $ThisLoc = "";
  notify("Players in the vicinity:");
  notify("------------------------");
  foreach (keys %Where) {
    $ThisLoc = sprintf(
         "${col_B}\[${col_w}%-20s$col_B\] $col_c - %s\n",
         $_, 
         $LastWhere{$_}
    );
    notify($ThisLoc);
  }
}

#
# Hooks.
#
prompt_add(\&where_prompt);
output_add(\&watch_where);
1;
