
%state_abbr = ( 
'Alaska' => 'ak', 
'Alabama' => 'al', 
'Arkansas' => 'ar',
'Ariz(?:\.|ona)?' => 'az',
'Cal(?:\.|if(?:\.|ornia)?)?' => 'ca',
'Col(?:\.|orado)?' => 'co', 
'Connecticut' => 'ct', 
'Delaware' => 'de', 
'Florida' => 'fl', 
'Georgia' => 'ga', 
'Hawaii' => 'hi', 
'Iowa' => 'ia', 
'Idaho' => 'id',
'Ill?(?:\.|inois)?'  => 'il', 
'Indiana' => 'in', 
'Kansas' => 'ks',
'Kentucky' => 'ky', 
'Louisiana' => 'la', 
'Mass(?:\.|achusetts)?' => 'ma', 
'Maryland' => 'md', 
'Maine' => 'me', 
'Mich(?:\.|igan)?' => 'mi',
'Minn(?:\.|esota)?' => 'mn', 
'Missouri' => 'mo', 
'Miss(?!o)(?:\.|iss?ipp?i)?' => 'ms', 
'Montana' => 'mt', 
'N(?:orth|\.)?\s*Carolina' => 'nc', 
'N(?:orth|\.)?\s*Dakota' => 'nd',
'Nebraska' => 'ne', 
'New\s*Hampshire' => 'nh',
'New\s*Jersey|N\.?\s*J\.?' => 'nj', 
'New\s*Mexico' => 'nm',
'Nevada' => 'nv', 
'New\s*York|N\.?\s*Y\.?' => 'ny', 
'Ohio' => 'oh', 
'Oklahoma' => 'ok', 
'Ore(?:gon|\.)?' => 'or', 
'Penn(?:\.|sylvania)?' => 'pa',
'Rhode\s*Island' => 'ri',
'S(?:outh|\.)?\s*Carolina' => 'sc', 
'S(?:outh|\.)?\s*Dakota' => 'sd',
'Tennessee' => 'tn', 
'Texas' => 'tx', 
'Utah' => 'ut', 
'Virginia' => 'va', 
'Vermont' => 'vt',
'Wash(?:ington|\.)?' => 'wa', 
'Wisc(?:onsin|\.)?' => 'wi',
'W(?:est|\.)?\s*Virginia' => 'wv', 
'Wyo(?:\.|ming)?' => 'wy', 

'(?:American)?\s*Samoa' => 'as', 
'D\.?\s*C\.?|Dist(?:\.|trict)?\s*(?:of\s*)?Colum(?:\.|b(?:\.|ia)?)?'  => 'dc',
'Guam' => 'gu', 
'Puerto\s*Rico' => 'pr',
'(?:U\.?\s*S\.?\s*)?Virgin\s*Islands' => 'vi', 

'Al(?:berta|(?:b|bta|ta)\.?)' => 'ab', 
'British\s*Columbia' => 'bc', 
'Manitoba' => 'mb', 
'New\s*Brunswick' => 'nb',
'Newfoundland' => 'nf', 
'Nova\s*Scotia' => 'ns', 
'(?:North\s*West|N\.?W\.?)Terr(?:\.|itor(?:y|ies))?' => 'nt', 
'Ont(?:\.|ario)?' => 'on',
'Sask(?:\.|atchewan)?' => 'sk',
'Prince\s*Edward\s*Island|P\.?E\.?I\.?' => 'pe', 
'Qu[eé]bec|P\.?Q\.?|QB\.?' => 'qc', 
'Yukon\s*Terr(?:\.|itor(?:y|ies))?' => 'yt',
);

# @state_abbr_list = 
#     qw(ak al ar as az ca co ct dc de fl ga gu hi
#        ia id il in ks ky la ma md me mi mn mo ms mt nc nd
#        ne nh nj nm nv ny oh ok or pa pr ri sc sd tn tx ut
#        va vi vt wa wi wv wy);

@province_abbr_list = 
    qw(ab bc mb nb nf ns nt on pe qc sk yt);

while (($p, $a) = each %state_abbr) {
    $state_pat{$a} = $p;
    $state_RX .= "($p)|";
    push @state_abbr_list, $a;
}
chop $state_RX;
$state_RX = "^\\s*(?:$state_RX)\\s*\$";

# Given a possible state name, turn it into a two-letter abbreviation.
sub resolve_state {
    my $n = $_[0];
#    $n =~ s/^\s+//;
#    $n =~ s/\s+$//;
    my @ml;
    if (@ml = ($n =~ /$state_RX/oi)) {
      my $i = 0;
      ++$i until $ml[$i];
      return $state_abbr_list[$i];
    } else {
      return undef;
    }
}
1;

