#!/usr/local/bin/perl -w
use strict;
my($addr, $domain, $revdomain, $triple, @triples);

use Getopt::Std;
use Mail::Address;

getopts('ot');

unless ($::opt_o || $::opt_t) {
  print <<"EOF";
Usage $0 [OPTION]... [ADDRESS FILE]

 -o  sOrt the list of addresses
 -t  sTrrip comments from the addresses

 Both sorting and stripping may be specified.
EOF
  exit(0);
}

open(FILE,$ARGV[0]);

while (<FILE>) {
  chomp;
  $addr = Mail::Address::address(parse Mail::Address $_);
  ($domain = $addr) =~ s/(.*@|\[|\])//g;
  $revdomain = uc(join('.',reverse(split /\./,$domain)));
  
  push @triples,[$_, $addr, $revdomain];
}

close FILE;

if ($::opt_o) {
  @triples = sort {$a->[2] cmp $b->[2]} @triples;
}

for $triple (@triples) {
  if ($::opt_t) {
    print "$triple->[1]\n";
  }
  else {
    print "$triple->[0]\n";
  }
}
