#!/usr/local/bin/perl

# COMS3101 Perl Fall 2013
# HW2
# chess_moves.pl

# Empty hash
%squares = ();
# annotated move count
$mvs = $ann = 0;

# Simplify regex
$piece = '[KQRBN]';
$square = '[a-h][1-8]';
$mark = '[?!]';

while (<>) {
  @moves = $_ =~ /\b$piece[a-h1-8]?x?$square\+?$mark?$mark?/g;

  $mvs += scalar(@moves);  # move count
  foreach (@moves) {
     $ann++ if $_ =~ /$mark$mark?$/;   # annotated move count
     $_ =~ /($square)/;
     $squares{$1}++;
  }
}

# Report
$p = sprintf("%.3f", 100*($ann / $mvs));
print "Percent of moves followed by symbols: $p%\n";
print "Unique squares:\n";
foreach (sort {$squares{$b} <=> $squares{$a}} keys %squares) {
    print "$_ $squares{$_}\n";
}