#!/usr/local/bin/perl

# COMS3101 Perl Fall 2013
# HW2
# mta_extract.pl

# Read input file
open(IN,$ARGV[0]);
@lines = <IN>;
chomp @lines;
close(IN);

# A hash with range limits which we use below
%high = (Bx => 55, BxM => 18, B=>103, BM=>5,
  QM => 25, Q => 113, M => 116, X=> 68 
);

foreach (@lines) {  
  # Special bus numbers  
  while ($_ =~ /Q20(a|b)/g)  {
     print "$&\n";
  }

  print "$&\n" while $_ =~ /Q15a/g;
  print "$&\n" while $_ =~ /(Bx4|M34|X22)A/g;

  # Standard bus numbers
  # Two step process to simplify
  # First match correct letters followed by 1-3 digits
  # Then nail down match   
  
  @buslike = $_ =~ /\b[BMQSX][xM]*[M]*\d{1,3}[abA]?\b/g;

  # Now we can be more precise
  foreach $bus (@buslike) {
    if ($bus =~ /^S([4-9][0-9])$/)  {
       print "$&\n" if $1 < 99; }

    # Using the hash to check the number vs the upper limit
    if ($bus =~ /^(BxM|X|M|QM?|B[xM]?)([1-9]\d*)$/) {
       print "$&\n" if $2 <= $high{$1};
    } 
  }
}