eval '(exit $?0)' && eval 'exec perl -w -S $0 ${1+"$@"}'
                  && eval 'exec perl -w -S $0 $argv:q'
                  if 0;

use strict;

use File::Basename;

use vars qw($script_top_dir);

BEGIN {
  # Make a spirited attempt to find where our libraries, etc are.
  if (-l $0) {
    $script_top_dir = dirname(readlink($0));
  } else {
    $script_top_dir = dirname $0;
  }
}

use lib "$script_top_dir";

use FileHandle;

use DBI();

use IPC::Run; # Available from CPAN / DAG repo.

use GratiaReporting::Data;
use GratiaReporting::JobInfo;
use GratiaReporting::JobInfoBranch;

use Getopt::Long;
use Pod::Usage;

use Text::Table; # Available from CPAN / DAG repo.
use Text::Wrap; # Standard in perl.

use Date::Calc ':all'; # Available from CPAN / DAG repo.

sub wrapped_report(\@\&;$$);
sub vo_report(\@$$);
sub old_report(\@$$);
sub site_report(\@$$);
sub single_user_report (\@$$$$$$);
sub reporting_name_summary ($);
sub sites_report ($);
sub translation_report ($);
sub print_anded_list($\@);

my $seen_people = {};
my $userid = 0;
my $column_separator = { title => ' | ', is_sep => '1' };


Getopt::Long::Configure(qw(no_ignore_case bundling require_order));

=pod

=head1 NAME

osg-users - Provide a CSV-format usage report by User from VOMRS/VOMS and Gratia.

=head1 SYNOPSIS

B<osg-users> B<-h>|B<--help>|B<-?>

B<osg-users> B<--man>

B<osg-users> [B<-u>|B<--user-regex> I<regex>]+
[B<-V>|B<--vo-report>]
[B<-S>|B<--site-report>]
[B<-v>|B<--vo> I<vo>]
[B<--site-name> I<site>]
[B<-r>|B<--reporting>|B<--reporting-name> I<name>]
[B<-k>|B<--metric-key> I<Njobs|CPU|Wall>]
[B<--no-totals>]
[B<-M>|B<mail-admins>]
[B<-t>|B<--timeperiod> I<week|month>]
[B<--aux-db-type> I<voms|vomrs|none>]
[B<--aux-db-connect> I<db-connect-command>]
[B<-m>|B<--mail> I<recipient>]+
[B<--history> I<# months>]
[B<--target-period> I<target-date>]
[B<--compare-period>|B<--comparison-period> I<compare-date>]
[B<-s>|B<--suppress-idle-users>]

Options marked with B<+> are repeatable and cumulative.

=head1 DESCRIPTION

I<osg-users> will produce a CSV format per-user report using VOMS/VOMRS and Gratia.



=head1 OPTIONS

=head2 Help Options

=over 4

=item B<--help>

=item B<-h>

=item B<-?>

Short help.


=item B<--man>

Full man page information.

=back

=cut

my %options = ();

GetOptions(\%options,
           "help|h|?",
           "man",
           "user-regex|u=s@",
           "vo|v=s",
           "vo-report|V",
           "data-source|D=s@",
           "metric-key|k=s@",
           "no-totals",
           "mail-admins|M",
           "timeperiod|t=s",
           "history=i",
           "aux-db-type=s",
           "aux-db-connect=s",
           "compare-period|comparison-period=s",
           "target-period=s",
           "suppress-idle-users|s",
           "reporting-name|reporting|r=s@",
           "print-queries|print-query",
           "verbose",
           "site-report|S",
           "site-name=s@",
           "mail|m=s@") or pod2usage(-exitval => 2);

$options{"help"} and pod2usage(1);

# Compile reporting_names required.
my $using_reporting_names = ($options{"reporting-name"} and scalar @{$options{"reporting-name"}});

# Medium usage (options explanation)
pod2usage(-verbose => 1) if exists $options{help};

# Full man page (requires working pod2man)
pod2usage(-verbose => 2) if exists $options{man};

$options{"data-source"} = ["/etc/gratia/gratia-reporting/user-reports.dat"]
  unless $options{"data-source"};

my $reporting_data =
  new GratiaReporting::Data( verbose => $options{verbose},
                             data_source => $options{"data-source"}
                   );

my $history = $options{history} || 6;

my $old_report;
if ($options{"vo-report"} or $options{"site-report"}) {
  $options{"aux-db-type"} = 'none';
} else {
  $old_report = 1;
}

if ($options{"aux-db-type"}) {
  if ($options{"aux-db-type"} !~ m&(?:voms|vomrs|none)&i) {
    print STDERR "ERROR: unrecognized aux-db-type", $options{"aux-db-type"}, "\n";
    print STDERR "       valid values are: vomrs, voms, none.\n";
    exit(1);
  }
} else {
  $options{"aux-db-type"} = "vomrs";
}

my $vo = actual_vo_name($options{vo} || ($options{"vo-report"} and "osg") || "");
my $alt_vo_list = $vo_data->{$vo}->{alt_vos} if ($vo and $vo_data->{$vo}->{alt_vos});
my $vo_list = sprintf("(%s)", join(", ", map { sprintf("'%s'", uc) } ($vo, @$alt_vo_list))) if $vo;
my $site_list = (exists $options{"site-name"} and scalar @{$options{"site-name"}})?
  sprintf("(%s)", join(", ", map { sprintf("'%s'", uc) } @{$options{"site-name"}})):
  "";

if ($options{"aux-db-type"} and lc $options{"aux-db-type"} ne "none") {
  if (exists $options{"aux-db-connect"}) {
    $options{"aux-db-connect"} = [ split /,/, $options{"aux-db-connect"} ]
  } else {
    $options{"aux-db-connect"} =
      [ "ssh",
        "fermigrid2.fnal.gov",
        ". /usr/local/vdt/setup.sh ; mysql -N -B -q -u root -h localhost vomrs13_$vo" ];
  }
}

my @keys = process_key_options();

my %available_timeperiods =
  (
   week => { # Display the first day of each week (Monday) but sort correctly.
            select => q{DATE(str_to_date(date_format(EndTime, '%x-%v Monday'), '%x-%v %W'))},
            sort => q{date_format(EndTime, '%x-%v')},
            interval_clause => qq{and DATE(EndTime) >= DATE(str_to_date(date_format(utc_timestamp() - interval $history month, '\%x-\%v Monday'), '\%x-\%v \%W'))}
           },
   month => {
             select => q{date_format(EndTime, '%Y-%m-01')},
             sort => q{date_format(EndTime, '%Y-%m')},
             interval_clause => qq{and DATE(EndTime) >= str_to_date(date_format(utc_timestamp() - interval $history month, '\%Y-\%m-01'), '\%Y-\%m-\%d')}
            },
   year => {
            select => q{date_format(EndTime, '%Y-01-01')},
            sort => q{date_format(EndTime, '%Y')},
            interval_clause => qq{and DATE(EndTime) >= str_to_date(date_format(utc_timestamp() - interval $history month, '\%Y-01-01'), '\%Y-\%m-\%d')}
           }
  );

my $timeperiod;

if ($options{timeperiod}) {
  if ($options{timeperiod} =~ m&^m&i) {
    $timeperiod = "month";
  } elsif ($options{timeperiod} =~ m&^y&i and $options{"vo-report"}) {
    $timeperiod = "year";
  }
}

$timeperiod = "week" unless $timeperiod;

my %mail_list = ();

my @command;
if ($options{"aux-db-connect"} and $options{"mail-admins"}) {
  @command = @{$options{"aux-db-connect"}};
  # Initial email list, including exclusions.
  %mail_list =
    (
     q/yocum@fnal.gov/ => { exclude => 1 },
     q/chadwick@fnal.gov/ => { exclude => 1 },
     q/neha@fnal.gov/ => { exclude => 1 }
    );

  my ($mail_out, $mail_error, $mail_select);

  $mail_select = <<'EOF';
select firstname,
       lastname,
       notification_params as email_address
from notification_methods N
join (select distinct
       md.member_id,
       mi1.personal_value as firstname,
       mi2.personal_value as lastname
      from member_dns md
      join member_identities mi1 on (md.member_id = mi1.member_id)
      join personal_data pd1 on (mi1.pd_id = pd1.pd_id)
      join member_identities mi2 on (md.member_id = mi2.member_id)
      join personal_data pd2 on (mi2.pd_id = pd2.pd_id)
      where pd1.personal_name = 'First name'
        and pd2.personal_name = 'Last name') PD on (N.member_id = PD.member_id)
join member_roles MR on (N.member_id = MR.member_id)
join roles R on (MR.r_id = R.r_id)
where N.notification_method = 'email'
  and N.notification_status = 'Confirmed'
  and R.role_name = 'VOAdmin'
  and N.member_id not in (select mr.member_id
                          from member_roles mr
                          join roles r on (mr.r_id = r.r_id)
                          where r.role_name = 'SiteAdmin')
order by lastname
EOF

  my $h = IPC::Run::harness \@command, \$mail_select, \$mail_out, \$mail_error;
  $h->run();
  for (split /\n/, $mail_out) {
    chomp;
    my ($firstname, $lastname, $email) = split /\t/;
    $mail_list{$email}->{firstname} = $firstname;
    $mail_list{$email}->{lastname} = $lastname;
  }
}

if (exists $options{mail}) {
  foreach my $email (@{$options{mail}}) {
    $mail_list{$email}->{exclude} = 0;
  }
}

my @email_addresses = map { $mail_list{$_}->{lastname}?
                              "$mail_list{$_}->{firstname} $mail_list{$_}->{lastname} <$_>":"$_" }
  grep { not $mail_list{$_}->{exclude} } sort keys %mail_list;

my $tmpdir;

my $nesting_level = -1;

my ($out, $error, $select);

$out = '';

if ($options{"aux-db-type"} =~ m&vomrs&i) {
  $select = <<'EOF';
select firstname,
       lastname,
       GR.member_id,
       SUBSTRING(distinguished_name FROM POSITION('/CN=' IN distinguished_name) + 4) as CN,
       GR.group_name,
       GR.role_name
from member_dns MD
     join (select distinct
            md.member_id,
            mi1.personal_value as firstname,
            mi2.personal_value as lastname
           from member_dns md
           join member_identities mi1 on (md.member_id = mi1.member_id)
           join personal_data pd1 on (mi1.pd_id = pd1.pd_id)
           join member_identities mi2 on (md.member_id = mi2.member_id)
           join personal_data pd2 on (mi2.pd_id = pd2.pd_id)
           where pd1.personal_name = 'First name'
             and pd2.personal_name = 'Last name') PD on (MD.member_id = PD.member_id)
     join (select distinct
            mg.member_id,
            groups.group_name,
            mg.g_id,
            ifnull(gnr.role_name,'') as role_name
           from member_groups mg
           join groups on (mg.g_id = groups.g_id)
           join roles on (mg.r_id = roles.r_id)
           left join (select r.r_id, role_name
                      from roles r
                      join groups_grouproles ggr on (ggr.r_id = r.r_id)) gnr on mg.r_id = gnr.r_id) GR on (MD.member_id = GR.member_id)
order by lastname, firstname, distinguished_name, group_name, role_name;
EOF
} elsif ($options{"aux-db-type"} =~ m&voms&i) {
  $select = <<'EOF';
select '' as firstname,
       u.cn as lastname,
       m.userid as member_id,
       SUBSTRING(u.dn FROM POSITION('/CN=' IN u.dn) + 4) as cn,
       g.dn as group_name,
       ifnull(r.role, '') as role_name
from m
join usr u on (m.userid = u.userid)
join groups g on (m.gid = g.gid)
left join roles r on (m.rid = r.rid)
order by lastname, cn, group_name, role_name;
EOF
}

my $dbh = DBI->connect("DBI:mysql:database=gratia;host=gr-osg-mysql-reports.opensciencegrid.org;port=3306",
                       "reader", "reader",
                       { 'RaiseError' => 1,
                         'AutoCommit' => 1 });

my $vomrs_user_info = {};
my $all_info = new GratiaReporting::JobInfoBranch("ByTimePeriod");

# Obtain optional external user information
if (scalar @command) {
  my $h = IPC::Run::harness \@command, \$select, \$out, \$error;
  $h->run();
}

# Add unattribute use user this way to allow the regex search to get its teeth into it.
$out = <<"EOF";
Unattributed	Use	0
$out
EOF

for (split /\n/, $out) {
  chomp;
  my ($firstname, $lastname, $id, $cn, $group, $role) = split /\t/;
  next unless defined $id;
  next if ($role and $role eq 'VO-Admin'); # If we're using VOMS DB instead of VOMRS.
  if (exists $options{"user-regex"} and scalar @{$options{"user-regex"}}) {
    my $user_wanted = 0;
    foreach my $regex (@{$options{"user-regex"}}) {
      $user_wanted = 1 if "$firstname $lastname" =~ m&$regex&i;
    }
    next unless $user_wanted;
  }
  unless (exists $vomrs_user_info->{$id}) {
    $vomrs_user_info->{$id} =
      { firstname => $firstname,
        lastname => $lastname,
      };
  }
  $vomrs_user_info->{$id}->{CN}->{$cn}->{FQAN} =
    sprintf("%s%s", $group, $role?"/Role=$role":"") if $cn;
  $userid = $id if $id > $userid; # Keep count
}

my $sites = {};

my %dates = ();

my $default_target = subtract_period(Today(1), 1);

# Process date options.
my ($previous_date, $previous_date_end) =
  convert_to_date($options{"compare-period"});
my ($current_date, $current_date_end, $next_date) =
  convert_to_date($options{"target-period"});

unless ($current_date) {
  ($current_date, $current_date_end, $next_date) =
    convert_to_date($default_target);
}

unless ($previous_date) {
  ($previous_date, $previous_date_end) =
    convert_to_date(subtract_period(process_date($current_date), 1));
}

my $interval_clause = $old_report?
  $available_timeperiods{$timeperiod}->{interval_clause}:
  sprintf("AND EndTime >= '%s' AND EndTime < '%s'",
          $previous_date, $next_date);

my $vo_query = $vo_list?sprintf("(UPPER(%s) IN %s)", RealVOName(), $vo_list):"";
my $site_query = $site_list?"(SiteName in $site_list)":"";
my $where_clause = "$vo_query$site_query"?sprintf("(%s%s%s)",
                                                  $vo_query,
                                                  ($vo_query and $site_query)?" AND ":"",
                                                  $site_query):"";
#foreach my $id (sort { $a <=> $b } grep /^\d+$/, keys %{$vomrs_user_info}) {
#  my $user_info = $vomrs_user_info->{$id};
#  my @cn_list = keys %{$user_info->{CN}};
#  my $flat_cn_list = join(", ", map {s&\'&\'\'&g; "'$_'"} @cn_list);
my $query =
  queryString($where_clause,
              $available_timeperiods{$timeperiod}->{select},
              $available_timeperiods{$timeperiod}->{sort}?
              $available_timeperiods{$timeperiod}->{sort}:
              $available_timeperiods{$timeperiod}->{select},
              $interval_clause
             );
# print STDERR $query, "\n";
my $sth = $dbh->prepare($query);
# print STDERR $sth->{Statement}, "\n";
$sth->execute();
while (my $row = $sth->fetchrow_hashref()) {
  my $id = process_cn($row->{CommonName});
  next unless defined $id;
#  print STDERR join("\t", map { $row->{$_} } sort keys %$row), "\n";
  my $user_info = $vomrs_user_info->{$id};
  my @cn_list = keys %{$user_info->{CN}};
  my $flat_cn_list = join(", ", map {s&\'&\'\'&g; "'$_'"} @cn_list);
  $sites->{$row->{SiteName}} = 1;
  $dates{$row->{TimePeriod}} = $row->{SortTimePeriod};
  my $timeperiod_info = $all_info->get_alt_branch($timeperiod)->get_alt_branch($row->{TimePeriod});
  my $new_user_info = $timeperiod_info->get_summed_branch("ByUser")->get_summed_branch($id);
  my $real_vo_name = actual_vo_name($row->{RealVOName});
  if ($options{verbose} and $real_vo_name ne $row->{RealVOName}) {
    print STDERR "Translated $row->{RealVOName} -> $real_vo_name\n";
  }
  my $reporting_name = "$real_vo_name:$row->{ReportingVOName}";
  next if ($using_reporting_names and not grep m&^\Q$reporting_name\E$&i, @{$options{"reporting-name"}});
  my $success = $row->{Success};
  foreach my $key (@keys) {
    ########################################################################
    # New, "Organized" data format.
    #
    # vomrs_user_info
    # ->{$id}
    #   ->
    #   ->
    #   ->
    # ->{"new_totals"}
    #   ->{"total"}
    #   ->{"by-user"}
    #     ->{"total"}
    #     ->{"by-site"}
    #   ->{"by-reporting_name"}
    #   ->{"site"}
    #########################################################################
    # New format: intermediate steps have totals done automatically for
    # summed branches.
    ####################################
    # Per user per CN per site per reporting name
    $new_user_info->get_summed_branch($row->{CommonName})->
      get_summed_branch("BySite")->get_summed_branch($row->{SiteName})->
        get_summed_branch("ByReportingName")->get_summed_branch($reporting_name)->
          get_leaf()->add_to_key($key, $success, $row->{$key});
    # Per reporting name per site per user per CN
    $timeperiod_info->get_alt_branch("ByReportingName")->get_summed_branch($reporting_name)->
      get_summed_branch("BySite")->get_summed_branch($row->{SiteName})->
        get_summed_branch("ByUser")->get_summed_branch($id)->get_summed_branch($row->{CommonName})->
          get_leaf()->add_to_key($key, $success, $row->{$key});
    # Per site per user per CN per reporting name
    $timeperiod_info->get_alt_branch("BySite")->get_summed_branch($row->{SiteName})->
      get_summed_branch("ByUser")->get_summed_branch($id)->get_summed_branch($row->{CommonName})->
        get_summed_branch("ByReportingName")->get_summed_branch($reporting_name)->
          get_leaf()->add_to_key($key, $success, $row->{$key});
    ########################################################################
    # Old format
    ####################################
    # Totals
    $user_info->{"totals"}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{$key} += $row->{$key};
    # Per time period
    $user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{$key} += $row->{$key};
    # Per site
    $user_info->{"totals"}->{Site}->{$row->{SiteName}}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{Site}->{$row->{SiteName}}->{$key} += $row->{$key};
    # Per time period per site
    $user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{Site}->{$row->{SiteName}}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{Site}->{$row->{SiteName}}->{$key} += $row->{$key};
    # Per user
    $user_info->{"totals"}->{CN}->{$row->{CommonName}}->{$timeperiod}->{$row->{TimePeriod}}->{$key} += $row->{$key};
    # Per reporting name
    $vomrs_user_info->{"totals"}->{"Reporting Name"}->{"$reporting_name"}->{$timeperiod}->{$row->{TimePeriod}}->{$key} += $row->{$key};
    # Totals ->{$success}
    $user_info->{"totals"}->{$success}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{$success}->{$key} += $row->{$key};
    # Per time period
    $user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{$success}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{$success}->{$key} += $row->{$key};
    # Per site
    $user_info->{"totals"}->{Site}->{$row->{SiteName}}->{$success}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{Site}->{$row->{SiteName}}->{$success}->{$key} += $row->{$key};
    # Per time period per site
    $user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{Site}->{$row->{SiteName}}->{$success}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{Site}->{$row->{SiteName}}->{$success}->{$key} += $row->{$key};
    # Per time period per site per user
    $vomrs_user_info->{"totals"}->{$timeperiod}->{$row->{TimePeriod}}->{Site}->{$row->{SiteName}}->{USER}->{$id}->{$success}->{$key} += $row->{$key};
    # Per reporting name
    $vomrs_user_info->{"totals"}->{"Reporting Name"}->{"$reporting_name"}->{$timeperiod}->{$row->{TimePeriod}}->{$success}->{$key} += $row->{$key};
    # Per reporting name per site
    $vomrs_user_info->{"totals"}->{"Reporting Name"}->{"$reporting_name"}->{Site}->{$row->{SiteName}}->{$timeperiod}->{$row->{TimePeriod}}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{"Reporting Name"}->{"$reporting_name"}->{Site}->{$row->{SiteName}}->{$timeperiod}->{$row->{TimePeriod}}->{$success}->{$key} += $row->{$key};
    # Per reporting name per site per user
    $vomrs_user_info->{"totals"}->{"Reporting Name"}->{"$reporting_name"}->{Site}->{$row->{SiteName}}->{$timeperiod}->{$row->{TimePeriod}}->{USER}->{$id}->{$key} += $row->{$key};
    $vomrs_user_info->{"totals"}->{"Reporting Name"}->{"$reporting_name"}->{Site}->{$row->{SiteName}}->{$timeperiod}->{$row->{TimePeriod}}->{USER}->{$id}->{$success}->{$key} += $row->{$key};
    # Per user per time period per site
    $user_info->{CN}->{$row->{CommonName}}->{$timeperiod}->{$row->{TimePeriod}}->{Site}->{$row->{SiteName}}->{$success}->{$key} += $row->{$key};
    # Per user per time period per site per reporting name
    $user_info->{CN}->{$row->{CommonName}}->{$timeperiod}->{$row->{TimePeriod}}->{Site}->{$row->{SiteName}}->{VO}->{"$reporting_name"}->{$success}->{$key} += $row->{$key};
    #      print STDERR
    #        "\$user_info->{CN}->{$row->{CommonName}}->{$timeperiod}->{$row->{TimePeriod}}->{Site}->{$row->{SiteName}}->{$success}->{$key} += $row->{$key}\n";
  }
}

if ($options{"vo-report"}) {
  wrapped_report(@email_addresses, &vo_report, $ARGV[0], ".txt")
} elsif ($options{"site-report"}) {
  wrapped_report(@email_addresses, &site_report, $ARGV[0], ".txt")
} else {
  wrapped_report(@email_addresses, &old_report, $ARGV[0])
}

END { # Things to do at the end of the program
  system("rmdir \"$tmpdir\"") if $tmpdir;
}

1;

sub subtract_period {
  my @args = @_;
  $args[3] = -$args[3] if $args[3];
  return add_period(@args);
}

sub add_period {
  if ($#_ < 2) {
    print STDERR "INTERNAL ERROR: not enough arguments to add_period\n";
    exit 1;
  }
  my ($year, $month, $day, $num_periods) = @_;
  $num_periods = $num_periods || 0;
  my $result;
  if ($timeperiod eq "month") {
    $result = convert_to_date(sprintf "%4d-%02d-%02d\n", Add_Delta_YM($year, $month, $day, 0, $num_periods));
  } elsif ($timeperiod eq "week") {
    $result = convert_to_date(sprintf "%4d-%02d-%02d\n", Add_Delta_Days($year, $month, $day, $num_periods * 7));
  } elsif ($timeperiod eq "year") {
    $result = convert_to_date(sprintf "%4d-%02d-%02d\n", Add_Delta_YM($year, $month, $day, $num_periods, 0));
  } else {
    print STDERR "INTERNAL ERROR: unknown timeperiod \"$timeperiod\"\n;";
    exit 1;
  }
}

sub wrapped_report(\@\&;$$) {
  my ($email_addresses, $func, $output_filename, $extension) = @_;
  my $output_filename_is_temporary;
  my $output_filehandle;
  if ($extension) {
    $extension = ".$extension" unless $extension =~ m&^\.&;
  } else {
    $extension = ".csv";
  }
  if ($ARGV[0]) {
    $output_filename = $ARGV[0];
    $output_filehandle = new FileHandle(">$ARGV[0]");
    $output_filehandle or die "Unable to open output file $ARGV[0]";
  } else {
    $output_filehandle = \*STDOUT;
  }

  if (scalar @$email_addresses and $output_filehandle == \*STDOUT) {
    # Need to put in a temporary file first.
    $output_filename_is_temporary = 1;
    my $tmpdir = `mktemp -d /tmp/osg-users-$vo.XXXXXXXXXX`;
    chomp $tmpdir;
    $output_filename = "$tmpdir/osg-users-$vo$extension";
    $output_filehandle = FileHandle->new(">$output_filename") or die "Unable to open temporary output file";
  }

  &$func($email_addresses, $output_filehandle, $output_filename);

  # Close the filehandle if appropriate
  $output_filehandle->close() if $output_filehandle and $output_filehandle != \*STDOUT;
  # Cat the temporary file to screen and remove it if appropriate
  if ($output_filename and $output_filename_is_temporary) {
    system(qq/cat "$output_filename"; rm -f "$output_filename"/);
  }

}

sub old_report(\@$$) {
  my ($email_addresses, $output_filehandle, $output_filename) = @_;

  # Totals per user per site (not per CN):
  foreach my $key (@keys) {
    print $output_filehandle csv_field("KEY: $key"), "\n";
    foreach my $id (sort by_name grep /^\d+$/, keys %{$vomrs_user_info}) {
      my $user_info = $vomrs_user_info->{$id};
      print $output_filehandle csv_field(sprintf("USER: $user_info->{firstname} $user_info->{lastname}%s",
                                                 ($user_info->{"totals"}->{"Njobs"})?"":" (no usage this period)")), "\n";
      foreach my $cn (sort keys %{$user_info->{CN}}) {
        print $output_filehandle csv_field("CN: $cn"), "\n";
      }
      next unless $user_info->{"totals"}->{"Njobs"};
      my @sites = sort keys %{$user_info->{"totals"}->{Site}};
      my @columns = ("Date", @sites, "Total");
      print $output_filehandle join(",", map { csv_field($_) } @columns), "\n";
      foreach my $date (sort by_date keys %{$user_info->{"totals"}->{$timeperiod}}) {
        print $output_filehandle csv_field($date);
        foreach my $site (@sites) {
          print $output_filehandle ",";
          if (exists $user_info->{"totals"}->{$timeperiod}->{$date}->{Site}->{$site}) {
            print $output_filehandle csv_field(convert_num($user_info->{"totals"}->{$timeperiod}->{$date}->{Site}->{$site}->{$key}, $key));
          }
        }
        print $output_filehandle ",", csv_field(convert_num($user_info->{"totals"}->{$timeperiod}->{$date}->{$key}, $key)), "\n";
      }
      print $output_filehandle csv_field("Totals");
      print $output_filehandle map
        { sprintf(",%s",
                  exists($user_info->{"totals"}->{Site}->{$_})?
                  csv_field(convert_num($user_info->{"totals"}->{Site}->{$_}->{$key}, $key)):"") } @sites;
      print $output_filehandle ", ", csv_field(convert_num($user_info->{"totals"}->{$key}, $key)), "\n";
    }

    # Totals for all users
    next if $options{"no-totals"};
    my @sites = sort keys %$sites;
    my @columns = ("Date", @sites, "Total");
    my $user_info = $vomrs_user_info;
    print $output_filehandle csv_field(sprintf("Totals%s", ($user_info->{"totals"}->{$key})?"":" (no usage)")), "\n";
    next unless $user_info->{"totals"}->{$key};
    print $output_filehandle join(",", map { csv_field($_) } @columns), "\n";
    foreach my $date (sort by_date keys %{$user_info->{"totals"}->{$timeperiod}}) {
      print $output_filehandle csv_field($date);
      foreach my $site (@sites) {
        print $output_filehandle ",";
        #        all_keys($user_info->{"totals"}->{$timeperiod}->{$date}->{Site});
        if (exists $user_info->{"totals"}->{$timeperiod}->{$date}->{Site}->{$site}) {
          print $output_filehandle csv_field(convert_num($user_info->{"totals"}->{$timeperiod}->{$date}->{Site}->{$site}->{$key}, $key));
        }
      }
      print $output_filehandle ",", csv_field(convert_num($user_info->{"totals"}->{$timeperiod}->{$date}->{$key}, $key)), "\n";
    }
    print $output_filehandle csv_field("Totals");
    print $output_filehandle map
      { sprintf(",%s",
                exists($user_info->{"totals"}->{Site}->{$_})?
                csv_field(convert_num($user_info->{"totals"}->{Site}->{$_}->{$key}, $key)):"") } @sites;
    print $output_filehandle ", ", csv_field(convert_num($user_info->{"totals"}->{$key}, $key)), "\n";
  }

  if (scalar @$email_addresses) {
    print "Mailing output to: \n";
    print join(", ", @$email_addresses), "\n\n";
    my $cmd = sprintf(qq&mutt -F "/etc/gratia/gratia-reporting/muttrc" -a "$output_filename" -s "OSG metrics for VO $vo by $timeperiod" %s&,
                      join(" ", map { qq/"$_"/ } @$email_addresses));
    open(MUTT, "|$cmd") or die "Unable to open mail command for input";
    print MUTT <<EOF;
Please find below the Gratia statistics for OSG usage for the $vo VO by $timeperiod for the last $history months. Some

Notes:

* The Njobs metric includes forwarding jobs, so there is some
  double-counting involved.

* The statistics do not include Glexec information currently.

* The TotalCPU metric may not be completely accurate due to limitations
  on accuracy of CPU time measurement for certain application and/or
  batch system types. These are limitations of the batch system, not the
  Gratia accounting system per se.
EOF
    close(MUTT);
  }
}

sub convert_num {
  my ($num, $key, $is_delta) = @_;
  defined $num or return "";
  my ($int_format, $float_format) = $is_delta?("%+d", "%+.1f"):("%d", "%.1f");
  if ($key eq "Njobs" or $key eq "Sites" or $key eq "Users") {
    return $num?sprintf($int_format, $num):0;
  } else {
    return $num?sprintf($float_format, $num / 3600):0;
  }
}

sub all_keys {
  my $hashref = shift;
  ++$nesting_level;
  foreach my $key (sort keys %$hashref) {
    print '  ' x $nesting_level if $nesting_level > 0;
    print $key, ": ", ref($hashref->{$key})?ref $hashref->{$key}:$hashref->{$key}, "\n";
    if (ref $hashref->{$key} eq "HASH") {
      all_keys($hashref->{$key});
    }
  }
  --$nesting_level;
}

sub RealVOName {
#  return "IF(VC.VOName LIKE '/%',VC.ReportableVOName, VC.VOName)";
  return "IFNULL(VC.ReportableVOName, IF(VC.VOName LIKE '/%', SUBSTRING(SUBSTRING_INDEX(VC.VOName, '/', 2), 2), VC.VOName))"
}

sub FQAN {
  return "IF(VC.VOName LIKE '/%', VC.VOName, 'Unknown')";
}

sub queryString {
  my ($whereclause,
      $timeperiod_format,
      $sorttimeperiod_format,
      $interval_clause) = @_;
  $whereclause="AND $whereclause" if $whereclause;
  my $RealVOName = RealVOName();
  my $FQAN = FQAN();
  my $query_string = <<EOF;
SELECT CommonName,
       VO.VOName AS ReportingVOName,
       $RealVOName AS RealVOName,
       $FQAN as FQAN,
       SiteName,
       $timeperiod_format AS TimePeriod,
       $sorttimeperiod_format AS SortTimePeriod,
       IF(ApplicationExitCode = 0, 1, 0) AS Success,
       SUM(Njobs) AS Njobs,
       SUM(WallDuration) AS WallDuration,
       SUM(CpuUserDuration + CpuSystemDuration) AS TotalCPU
FROM MasterSummaryData MSD
JOIN VONameCorrection VC on (MSD.VOcorrid = VC.corrid)
JOIN VO on (VC.void = VO.void)
JOIN Probe P ON (MSD.ProbeName = P.probename)
JOIN Site S ON (P.siteid = S.siteid)
WHERE ResourceType IN ( 'Batch' )
$interval_clause
$whereclause
GROUP BY CommonName, RealVOName, VO.VOName, SiteName, Success, TimePeriod
ORDER BY CommonName, RealVOName, VO.VOName, SiteName, Success, SortTimePeriod
EOF
  print STDERR "INFO: query string = \n", $query_string, "\n" if $options{"print-queries"};
  return $query_string;
}

sub by_name {
  return $vomrs_user_info->{$a}->{lastname} cmp $vomrs_user_info->{$b}->{lastname} or
    $vomrs_user_info->{$a}->{firstname} cmp $vomrs_user_info->{$b}->{firstname};
}

sub by_date {
  return $dates{$a} cmp $dates{$b};
}

sub csv_field {
	my $string = shift;
        chomp $string;
	my $needs_quoting = $string =~ m&[,"\n]&;
	if ($needs_quoting) {
		$string =~ s&\"&\"\"&g;
		$string="\"$string\"";
	}
	return $string;
}

sub process_key_options {
  return qw(Njobs TotalCPU WallDuration) unless exists $options{"metric-key"};
  my @keys = ();
  foreach my $key (@{$options{"metric-key"}}) {
    push @keys, "Njobs" if $key =~ m&^(?:Njobs|N|jobs|j)$&i;
    push @keys, "TotalCPU" if $key =~ m&CPU&i;
    push @keys, "WallDuration" if $key =~ m&Wall&i;
  }
  return @keys;
}

sub vo_report(\@$$) {
  my ($email_addresses, $output_filehandle, $output_filename) = @_;

  my @lines = ();

  my @dates = sort by_date keys %dates;

  my ($max_length_site, $num_sites) = site_info($previous_date, $current_date);
  my $max_length_cn = max_length_cn($previous_date, $current_date);
  my ($max_length_rep_name, $num_rep_names) = rep_name_info($previous_date, $current_date);

  print $output_filehandle <<EOF;
Comparing current data for $timeperiod $current_date - $current_date_end (inclusive)
to previous $timeperiod $previous_date - $previous_date_end (inclusive).

Days start and end at midnight UTC.

EOF

  if ($options{"reporting-name"} and scalar @{$options{"reporting-name"}}) {
    print $output_filehandle "Report for selected reporting names: ";
    print_anded_list($output_filehandle, @{$options{"reporting-name"}});
  }

  # Only if we're not doing a report restricted to certain reporting names.
  my @label = (" Current", "Previous");
  for my $date ($current_date, $previous_date) {
    my $label = shift @label;
    if ($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{"Njobs"}) {
      my $string = "$label ${timeperiod}'s total usage: ";
      print $output_filehandle $string,
        num_users($date), " users utilized ",
          num_sites($date), " sites;\n";
      my ($total, $success, $fail) =
        ( $vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{"Njobs"},
          $vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{1}->{"Njobs"} || 0,
          $vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{0}->{"Njobs"} || 0 );
      my $efficiency = $total?(100.0*$success/$total):0;
      print $output_filehandle ' ' x length($string),
        $total, " jobs total (",
          $success, " / ",
            $fail, " = ",
              sprintf("%.1f%%", $efficiency),
                " success);\n";
      ($total, $success, $fail) =
        ( convert_num($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{"WallDuration"},
                      "WallDuration"),
          convert_num($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{1}->{"WallDuration"} || 0,
                      "WallDuration"),
          convert_num($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{0}->{"WallDuration"} || 0,
                      "WallDuration") );
      $efficiency = ($total and $total > 0)?(100.0*$success/$total):0;
      print $output_filehandle ' ' x length($string),
        $total, " wall clock hours total (",
          $success, " / ",
            $fail, " = ",
              sprintf("%.1f%%", $efficiency),
                " success);\n";
    } else {
      print $output_filehandle
        "$label ${timeperiod}'s total usage: zero.\n";
    }
  }
  print $output_filehandle "\n" if ($#label < 1);

  if ($timeperiod eq "month") {
    print $output_filehandle "Monthly summary of FQAN / voi:VOc to Reporting Name translations:\n";
    translation_report($output_filehandle);
  }
  # Reporting name summary
  if ($num_rep_names) {
    my @reporting_names = keys %{$vomrs_user_info->{"totals"}->{"Reporting Name"}};
    if ($num_rep_names == 1) {
      print $output_filehandle "Active reporting name: ",
        $reporting_names[0], "\n\n";
    } else {
      reporting_name_summary($output_filehandle);
    }
  }

  # Site summary
  if (num_sites($current_date) > 1) {
    sites_report($output_filehandle);
  }

  # Per user report
  foreach my $id (sort by_usage grep /^\d+$/, keys %{$vomrs_user_info}) {
    single_user_report(@lines,
                       $id,
                       $max_length_site, $num_sites,
                       $max_length_cn,
                       $max_length_rep_name,
                       $num_rep_names);
  }

  print $output_filehandle
    join ("", @lines);

  print $output_filehandle <<EOF;

------------------------------------------------------------------------
Notes:

* Data are only included for jobs that *completed* in the period in question.

* Durations are expressed in hours, to 1 decimal place.

* The Njobs metric may include intermediate jobs (when a job is
  forwarded from one gatekeeper to another), so there is the possibility
  of some double-counting.

* The statistics do not include Glexec information currently.

* The "Job Success?" column indicates whether the data in that row
  concern jobs where the *application* was successful. Gratia is unable
  to detect subsequent failures in middleware after the successful
  completion of the batch job.
EOF

  $output_filehandle->close();

  # Send the report if necessary
  if (scalar @$email_addresses) {
    print "Mailing output to: \n";
    print join(", ", @$email_addresses), "\n\n";

    # Fake html for broken browsers
    open (IN, $output_filename);
    my $text = join("", <IN>);
    close(IN);
    my $html_filename = $output_filename;
    $html_filename =~ s&\.txt$&.html&;
    open(OUT, ">$html_filename") or die "Unable to open temporary file $html_filename";
    print OUT <<EOF;
<html>
<body>
<pre>
$text
</pre>
</body>
<html>
EOF
    close(OUT);
    my $cmd = sprintf(qq&mutt -F "/etc/gratia/gratia-reporting/muttrc" -a "$html_filename" -s "OSG metrics for VO $vo for $timeperiod $current_date to $current_date_end" %s&,
                      join(" ", map { qq/"$_"/ } @$email_addresses));

    open(MUTT, "|$cmd") or die "Unable to open mail command for input";
    print MUTT <<EOF;
Please find below the Gratia statistics for OSG usage for the $vo VO
for the $timeperiod $current_date - $current_date_end (inclusive).

Deltas are with respect to the $timeperiod $previous_date - $previous_date_end (inclusive).

Notes follow below the tables.

------------------------------------------------------------------------
EOF
    print MUTT $text;
    close(MUTT);
  }

}

sub by_usage {
  return ($vomrs_user_info->{$b}->{"totals"}->{$timeperiod}->{$current_date}->{"WallDuration"} || 0) <=>
    ($vomrs_user_info->{$a}->{"totals"}->{$timeperiod}->{$current_date}->{"WallDuration"} || 0);
}

sub process_date {
  my $date = shift;
  return unless $date;
  my $result;
  my ($year, $month, $day, $week);
  if ($timeperiod eq "week") {
    if ($date =~ m&(\d{4})(?:[-\D])?(\d+)$&) { # Year, week #
      ($year, $month, $day) = Monday_of_Week($2, $1);
    } else {
      if ($date =~ m&(\d{4})(?:[-\D])?(\d{1,2})(?:[-\D])?(\d+)&) {
        ($year, $month, $day) = ($1, $2, $3);
      } else {
        ($year, $month, $day) = Parse_Date($date);
      }
      if ($year) {
        ($week, $year) = Week_of_Year($year, $month, $day);
        ($year, $month, $day) = Monday_of_Week($week, $year);
      } else {
        print STDERR "Unable to decode string $date to a date\n";
        exit(1);
      }
    }
  } elsif ($timeperiod eq "month") {
    if ($date =~ m&(\d{4})\D?(\d+)$&) { # Year, month #
      ($year, $month, $day) = ($1, $2, "01");
    } else {
      if ($date =~ m&(\d{4})(?:[-\D])?(\d{1,2})(?:[-\D])?(\d+)&) {
        ($year, $month, $day) = ($1, $2, "01");
      } else {
        ($year, $month, $day) = Parse_Date($date);
      }
      unless ($year) {
        print STDERR "Unable to decode string $date to a date\n";
        exit(1);
      }
    }
  } elsif ($timeperiod eq "year") {
    if ($date =~ m&(\d{4})$&) { # Year only
      ($year, $month, $day) = ($1, "01", "01");
    } else {
      if ($date =~ m&(\d{4})(?:[-\D])?(\d{1,2})(?:[-\D])?(\d+)&) {
        ($year, $month, $day) = ($1, "01", "01");
      } else {
        ($year, $month, $day) = Parse_Date($date);
      }
      unless ($year) {
        print STDERR "Unable to decode string $date to a date\n";
        exit(1);
      }
    }
  } else {
    print STDERR "ERROR: convert_to_dates does not understand timeperiod $timeperiod\n";
    exit(1);
  }
  if (wantarray) {
    return ($year, $month, $day);
  } else {
    string_date($year, $month, $day);
  }
}

sub string_date {
  my ($year, $month, $day) = @_;
  return unless ($year and $month and $day);
  return sprintf("%04d-%02d-%02d", $year, $month, $day);
}

sub convert_to_date {
  my $date = shift;
  return process_date($date) unless wantarray;
  # Return (current_date, current_date_end, next_date)
  my ($year, $month, $day) = process_date($date);
  return unless $year;
  my $result = string_date($year, $month, $day);
  if ($timeperiod eq "month") {
    return ($result,
            sprintf("%04d-%02d-%02d",
                    Add_Delta_YMD($year, $month, $day, 0, 1, -1)),
            sprintf("%04d-%02d-%02d",
                    Add_Delta_YMD($year, $month, $day, 0, 1, 0)));
  } elsif ($timeperiod eq "week") {
    return ($result,
            sprintf("%04d-%02d-%02d",
                    Add_Delta_Days($year, $month, $day, 6)),
            sprintf("%04d-%02d-%02d",
                    Add_Delta_Days($year, $month, $day, 7)));
  } elsif ($timeperiod eq "year") {
    return ($result,
            sprintf("%04d-%02d-%02d",
                    Add_Delta_YMD($year, $month, $day, 1, 0, -1)),
            sprintf("%04d-%02d-%02d",
                    Add_Delta_YMD($year, $month, $day, 1, 0, 0)));
  }
}

sub num_users {
  my $date = shift;

  my $result = 0;
  foreach my $id (sort by_name grep /^\d+$/, keys %{$vomrs_user_info}) {
    ++$result if ($vomrs_user_info->{$id}->{"totals"}->{$timeperiod}->{$date}->{"Njobs"});
  }
  return $result;
}

sub num_sites {
  my ($date, $reporting_name, $success) = @_;

  my $result = 0;
  foreach my $site (sort keys %{$vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{Site}}) {
    if (($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{Site}->{$site}->{"Njobs"}) and
        ((not $reporting_name) or
         (defined $success and
          $vomrs_user_info->{"totals"}->{"Reporting Name"}->{$reporting_name}->{Site}->{$site}->{$timeperiod}->{$date}->{$success}->{"Njobs"}) or
         $vomrs_user_info->{"totals"}->{"Reporting Name"}->{$reporting_name}->{Site}->{$site}->{$timeperiod}->{$date}->{"Njobs"})) {
      ++$result;
    }
  }
  return $result;
}

sub site_info {
  my $result = "";
  my $sites = {};
  foreach my $date (@_) {
    foreach my $site (keys %{$vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{Site}}) {
      next unless $vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{Site}->{$site}->{"Njobs"};
      $sites->{$site} = 1;
      if (length($site) > length($result)) {
        $result = $site;
      }
    }
  }
  return ($result, scalar keys %$sites);
}

sub max_length_cn {
  my ($previous_date, $current_date) = @_;
  my $result = "";
  foreach my $id (grep /^\d+$/, keys %{$vomrs_user_info}) {
    # User's CNs.
    foreach my $cn (keys %{$vomrs_user_info->{$id}->{CN}}) {
      next unless ($vomrs_user_info->{$id}->{"totals"}->{CN}->{$cn}->{$timeperiod}->{$previous_date}->{"Njobs"} or
                   $vomrs_user_info->{$id}->{"totals"}->{CN}->{$cn}->{$timeperiod}->{$current_date}->{"Njobs"});
      $result = $cn if (length($cn) > length($result));
    }
    # User's name (almost)
    my $user_name_test =
      sprintf("%s %s (success)",
              $vomrs_user_info->{$id}->{firstname} || "",
              $vomrs_user_info->{$id}->{lastname});
    $result = $user_name_test if (length($user_name_test) > length($result));
  }
  return $result;
}

sub rep_name_info {
  my $result = "";
  my $len = 0;
  my %rep_names = ();
  foreach my $id (grep /^\d+$/, keys %{$vomrs_user_info}) {
    # print STDERR "ID $id\n";
    foreach my $cn (keys %{$vomrs_user_info->{$id}->{CN}}) {
      # print STDERR "  CN: $cn\n";
      foreach my $date (@_) {
        # print STDERR "    DATE: $date\n";
        foreach my $site (keys %{$vomrs_user_info->{$id}->{CN}->{$cn}->{$timeperiod}->{$date}->{Site}}) {
          # print STDERR "      SITE: $site\n";
          foreach my $reporting_name (keys %{$vomrs_user_info->{$id}->{CN}->{$cn}->{$timeperiod}->{$date}->{Site}->{$site}->{VO}}) {
            # print STDERR "        REPORTING NAME $reporting_name\n";
            $rep_names{lc $reporting_name} = 1;
            if (length("$reporting_name") > $len) {
              $result = "$reporting_name";
              $len = length($result);
            }
          }
        }
      }
    }
  }
  # print STDERR "REP_NAME_INFO: $result, ", scalar(keys(%rep_names)), "\n";
  return ($result, scalar(keys(%rep_names)));
}

sub unique_list {
  # print STDERR "ARGS = ", join(", ", @_), "\n";
  my %hash = map { ( $_ => 1 ) } @_;
  # print STDERR "RETURNING ", join(", ", keys %hash), "\n";
  return keys %hash;
}

sub process_cn {
  my ($cn) = @_;
  return 0 if $cn =~ m&^(?:^Generic|Unknown$)&;
  my $person = $cn;
  my @array = split m&/CN=&, $cn;
  my $count = scalar @array;
  # Attempt to extract a real name from the CN string and neaten.
  $person =~ s&^/CN=[^/]+/CN=\d+/CN=([^/]+)$&${1}&; # CERN
  $person =~ s&^/CN=[^/]+/CN=cron/CN=([^/]+)/CN=UID:[^/]+$&${1}&; # FNAL robot certs
  $person =~ s&/CN=\d+&&g;    # Numeric CNs
  $person =~ s&/CN=UID:[^/]+$&&; # FNAL CN UID clause.
  $person =~ s&^/CN=&&;       # Leading /CN=
  $person =~ s&^(.*?)\s*\d+$&$1&; # Trailing ID #
  $person =~ s&\s*\(.*\)\s*$&&; # Parenthetical notes (eg Frederick G. Chambliss (Engage)).
  my $member_id;
  # Combine CNs that are identical to within known, simple manipulations
  $seen_people->{$person} = ++$userid unless exists $seen_people->{$person};
  my $id = $seen_people->{$person};
  ####################################
  # Old info
  unless (exists $vomrs_user_info->{$id}) {
    # Load up initial info.
    $vomrs_user_info->{$id} =
      { lastname => $person };
  }
  # Load up CN info.
  unless (exists $vomrs_user_info->{$id}->{CN}->{$cn}) {
    $vomrs_user_info->{$id}->{CN}->{$cn}->{FQAN} = '';
    # print STDERR "Added info for user $person, ID $id, CN=$cn\n";
  }
  return $id;
}

sub site_report(\@$$) {
  my ($email_addresses, $output_filehandle, $output_filename) = @_;

  my @lines = ();

  my @dates = sort by_date keys %dates;

  my ($max_length_site, $num_sites) = site_info($previous_date, $current_date);
  my $max_length_cn = max_length_cn($previous_date, $current_date);
  my ($max_length_rep_name, $num_rep_names) = rep_name_info($previous_date, $current_date);

  ######################################################################
  # Preamble
  print $output_filehandle <<EOF;
Comparing current data for $timeperiod $current_date - $current_date_end (inclusive)
to previous $timeperiod $previous_date - $previous_date_end (inclusive).

Days start and end at midnight UTC.

EOF

  # List selected sites
  if ($options{"site-name"}) {
    print $output_filehandle "Report includes data for ";
    print_anded_list($output_filehandle, @{$options{"site-name"}});
  }

  my @label = (" Current", "Previous");
  for my $date ($current_date, $previous_date) {
    my $label = shift @label;
    if ($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{"Njobs"}) {
      my $string = "$label ${timeperiod}'s total usage: ";
      print $output_filehandle $string,
        num_users($date), " users ";
      my $num_sites = num_sites($date);
      if ($options{"site-name"} and scalar @{$options{"site-name"}} > 1) {
        print $output_filehandle "utilized ",
          $num_sites, " site", (($num_sites == 1)?"":"s"), ";\n";
      } else {
        print $output_filehandle "\n";
      }
      my ($total, $success, $fail) =
        ( $vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{"Njobs"},
          $vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{1}->{"Njobs"} || 0,
          $vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{0}->{"Njobs"} || 0 );
      my $efficiency = $total?(100.0*$success/$total):0;
      print $output_filehandle ' ' x length($string),
        $total, " jobs total (",
          $success, " / ",
            $fail, " = ",
              sprintf("%.1f%%", $efficiency),
                " success);\n";
      ($total, $success, $fail) =
        ( convert_num($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{"WallDuration"},
                      "WallDuration"),
          convert_num($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{1}->{"WallDuration"} || 0,
                      "WallDuration"),
          convert_num($vomrs_user_info->{"totals"}->{$timeperiod}->{$date}->{0}->{"WallDuration"} || 0,
                      "WallDuration") );
      $efficiency = ($total+0)?(100.0*$success/$total):0;
      print $output_filehandle ' ' x length($string),
        $total, " wall clock hours total (",
          $success, " / ",
            $fail, " = ",
              sprintf("%.1f%%", $efficiency),
                " success);\n";
    } else {
      print $output_filehandle
        "$label ${timeperiod}'s total usage: zero.\n";
    }
  }
  print $output_filehandle "\n" if ($#label < 1);

  reporting_name_summary($output_filehandle);

  # Site summary
  if (num_sites($current_date) > 1) {
    sites_report($output_filehandle);
  }

  # Main report
  foreach my $id (sort by_usage grep /^\d+$/, keys %{$vomrs_user_info}) {
    my $name = $vomrs_user_info->{$id}->{firstname} || '';
    $name = "$name " if $name;
    $name = "$name$vomrs_user_info->{$id}->{lastname}";
    # print STDERR "Producing report for id $id, $name\n";
    my @lines = ();
    single_user_report(@lines,
                       $id,
                       $max_length_site, $num_sites,
                       $max_length_cn,
                       $max_length_rep_name,
                       $num_rep_names);
    print $output_filehandle
      join ("", @lines) if scalar @lines;
  }


  print $output_filehandle <<EOF;

------------------------------------------------------------------------
Notes:

* Data are only included for jobs that *completed* in the period in question.

* Durations are expressed in hours, to 1 decimal place.

* The Njobs metric may include intermediate jobs (when a job is
  forwarded from one gatekeeper to another), so there is the possibility
  of some double-counting.

* The statistics do not include Glexec information currently.

* The "Job Success?" column indicates whether the data in that row
  concern jobs where the *application* was successful. Gratia is unable
  to detect subsequent failures in middleware after the successful
  completion of the batch job.
EOF

  $output_filehandle->close();

  # Send the report if necessary
  if (scalar @$email_addresses) {
    print "Mailing output to: \n";
    print join(", ", @$email_addresses), "\n\n";

    # Fake html for broken browsers
    open (IN, $output_filename);
    my $text = join("", <IN>);
    close(IN);
    my $html_filename = $output_filename;
    $html_filename =~ s&\.txt$&.html&;
    open(OUT, ">$html_filename") or die "Unable to open temporary file $html_filename";
    print OUT <<EOF;
<html>
<body>
<pre>
$text
</pre>
</body>
<html>
EOF
    close(OUT);
    my $subject_sites = '';
    if ($options{"site-name"}) {
      $subject_sites =
        (scalar @{$options{"site-name"}} > 1)?
          "for $options{\"site-name\"}->[0] et al. ":
            "for $options{\"site-name\"}->[0] ";
    }

    my $cmd = sprintf(qq&mutt -F "/etc/gratia/gratia-reporting/muttrc" -a "$html_filename" -s "OSG site metrics report ${subject_sites}for $timeperiod $current_date to $current_date_end" %s&,
                      join(" ", map { qq/"$_"/ } @$email_addresses));

    open(MUTT, "|$cmd") or die "Unable to open mail command for input";
    print MUTT <<EOF;
Please find below the Gratia site-oriented statistics for OSG usage
for the $timeperiod $current_date - $current_date_end (inclusive).

Notes follow below the tables.

------------------------------------------------------------------------
EOF
    print MUTT $text;
    close(MUTT);
  }
}

sub single_user_report(\@$$$$$$) {
  my ($lines,
      $id,
      $max_length_site,
      $num_sites,
      $max_length_cn,
      $max_length_rep_name,
      $num_rep_names) = @_;
  my $user_info = $vomrs_user_info->{$id};
  unless ($user_info->{"totals"}->{$timeperiod}->{$current_date}->{"Njobs"}) {
    push @$lines, sprintf("%s %s%s\n",
                         $user_info->{firstname} || '',
                         $user_info->{lastname},
                         ": no usage this period\n")
      unless $options{"suppress-idle-users"};
    return ();
  }
  # Define the table
  my $user_table = Text::Table->new
    (
     { title => '| ', is_sep => '1' },
     { title => "CN", align_title => "center", sample =>  $max_length_cn },
     ($num_sites>1)?($column_separator,
                     { title => "Site",
                       align_title => "center",
                       sample => $max_length_site }):(),
     ($num_rep_names>1)?($column_separator,
                         { title => "VO:Reporting\nName",
                           align_title => "center",
                           sample => $max_length_rep_name }):(),
     $column_separator,
     { title => "Job\nSuccess?", align_title => "center", sample => "yes" },
     $column_separator,
     { title => "# Jobs", align_title => "center", sample => "99999999", align => 'num' },
     $column_separator,
     { title => "Wall\nTime (h)", align_title => "center", sample => "99999999.0", align => 'num' },
     $column_separator,
     { title => "Delta\nJobs", align_title => "center", sample => "-199999999", align => 'num' },
     $column_separator,
     { title => "Delta Wall\nTime (h)", align_title => "center", sample => "-199999999.0", align => 'num' },
     { title => ' |', is_sep => '1' }
    );

  my @sites = sort keys %{$user_info->{"totals"}->{Site}};

  # Load the table
  foreach my $cn (sort keys %{$user_info->{CN}}) {
    foreach my $site (@sites) {
      # print STDERR "SITE: $site\n";
      my @name_list = keys %{$user_info->{CN}->{$cn}->{$timeperiod}->{$previous_date}->{Site}->{$site}->{VO}};
      foreach my $reporting_name (sort(unique_list(keys %{$user_info->{CN}->{$cn}->{$timeperiod}->{$current_date}->{Site}->{$site}->{VO}},
                                                   keys %{$user_info->{CN}->{$cn}->{$timeperiod}->{$previous_date}->{Site}->{$site}->{VO}}))) {
        # print STDERR "REPORTING NAME: $reporting_name\n";
        foreach my $success (1, 0) {
          my $njobs_current = ($user_info->{CN}->{$cn}->{$timeperiod}->{$current_date}->{Site}->{$site}->{VO}->{$reporting_name}->{$success}->{"Njobs"} || 0);
          my $njobs_delta = convert_num($njobs_current -
                                        ($user_info->{CN}->{$cn}->{$timeperiod}->{$previous_date}->{Site}->{$site}->{VO}->{$reporting_name}->{$success}->{"Njobs"} || 0),
                                        "Njobs", 1);
          my @row =
            (
             $cn,
             ($num_sites>1)?($site):(),
             ($num_rep_names>1)?($reporting_name):(),
             $success?"Yes":"No",
             $njobs_current,
             convert_num(($user_info->{CN}->{$cn}->{$timeperiod}->{$current_date}->{Site}->{$site}->{VO}->{$reporting_name}->{$success}->{"WallDuration"} || 0),
                         "WallDuration"),
             $njobs_delta,
             convert_num(($user_info->{CN}->{$cn}->{$timeperiod}->{$current_date}->{Site}->{$site}->{VO}->{$reporting_name}->{$success}->{"WallDuration"} || 0) -
                         ($user_info->{CN}->{$cn}->{$timeperiod}->{$previous_date}->{Site}->{$site}->{VO}->{$reporting_name}->{$success}->{"WallDuration"} || 0),
                         "WallDuration", 1),
            );
          if ($njobs_current || $njobs_delta) {
            $user_table->add(@row);
          }
          # print STDERR join(", ", @row), "\n";
        }
      }
    }
  }

  # Print the table
  push @$lines,
    $user_table->rule('_', '_'),
      $user_table->title(),
        $user_table->rule('_', '|'),
          $user_table->body(),
            $user_table->rule('-', '+');

  # User totals
  my $total_lines = 0;
  my $user_name = sprintf("%s %s",
                          $user_info->{firstname} || "",
                          $user_info->{lastname}) || "";
  $user_name =~ s&^\s*(.*?)\s*$&$1&;
  foreach my $success (1, 0) {
    my $njobs_current = ($user_info->{"totals"}->{$timeperiod}->{$current_date}->{$success}->{"Njobs"} || 0);
    my $njobs_delta = convert_num($njobs_current -
                                  ($user_info->{"totals"}->{$timeperiod}->{$previous_date}->{$success}->{"Njobs"} || 0),
                                  "Njobs", 1);
    my @row =
      (
       sprintf("%s (%s)",
               $user_name,
               $success?"success":"failure"),
       ($num_sites>1)?("ALL"):(),
       ($num_rep_names>1)?("ALL"):(),
       $success?"Yes":"No",
       $njobs_current,
       convert_num(($user_info->{"totals"}->{$timeperiod}->{$current_date}->{$success}->{"WallDuration"} || 0),
                   "WallDuration"),
       $njobs_delta,
       convert_num(($user_info->{"totals"}->{$timeperiod}->{$current_date}->{$success}->{"WallDuration"} || 0) -
                   ($user_info->{"totals"}->{$timeperiod}->{$previous_date}->{$success}->{"WallDuration"} || 0),
                   "WallDuration", 1)
      );
    if ($njobs_current || $njobs_delta) {
      $user_table->add(@row);
      ++$total_lines;
    }
  }
  if ($total_lines == 2) {
    push @$lines,
      $user_table->body(-$total_lines, $total_lines),
        $user_table->rule('-', '+');
  }
  $user_table->add
    (
     sprintf("%s (%s)",
             $user_name,
             "all"),
     ($num_sites>1)?("ALL"):(),
     ($num_rep_names>1)?("ALL"):(),
     "N/A",
     ($user_info->{"totals"}->{$timeperiod}->{$current_date}->{"Njobs"} || 0),
     convert_num(($user_info->{"totals"}->{$timeperiod}->{$current_date}->{"WallDuration"} || 0),
                 "WallDuration"),
     convert_num(($user_info->{"totals"}->{$timeperiod}->{$current_date}->{"Njobs"} || 0) -
                 ($user_info->{"totals"}->{$timeperiod}->{$previous_date}->{"Njobs"} || 0),
                 "Njobs", 1),
     convert_num(($user_info->{"totals"}->{$timeperiod}->{$current_date}->{"WallDuration"} || 0) -
                 ($user_info->{"totals"}->{$timeperiod}->{$previous_date}->{"WallDuration"} || 0),
                 "WallDuration", 1)
    );

  push @$lines,
    $user_table->body(-1, 1),
      $user_table->rule('=', '='),
        "\n";
}

sub sites_report($) {
  my $output_filehandle = shift;
  my $extra_message = $using_reporting_names?" for selected reporting names":"";
  print $output_filehandle "Site summary$extra_message: \n";
  my $site_summary_table =
    Text::Table->
        new({ title => '| ', is_sep => '1' },
            {
             title => 'SiteName', align_title => 'center' },
            $column_separator,
            {
             title => "Job\nSuccess?", align_title => 'center' },
            $column_separator,
            {
             title => "# Users", align_title => "center", align => 'num' },
            $column_separator,
            {
             title => "# Jobs", align_title => "center", align => 'num' },
            $column_separator,
            {
             title => "Wall\nTime (h)", align_title => "center", align => 'num' },
            $column_separator,
            {
             title => "Delta\nUsers", align_title => "center", align => 'num' },
            $column_separator,
            {
             title => "Delta\nJobs", align_title => "center", align => 'num' },
            $column_separator,
            {
             title => "Delta Wall\nTime (h)", align_title => "center", align => 'num' },
            {
             title => ' |', is_sep => '1' });
  foreach my $site (sort keys %$sites) {
    foreach my $success (1, 0) {
      my $num_users_current =
        scalar keys %{$vomrs_user_info->{"totals"}->{$timeperiod}->{$current_date}->{Site}->{$site}->{USER}};
      my $num_users_previous = scalar keys %{$vomrs_user_info->{"totals"}->{$timeperiod}->{$previous_date}->{Site}->{$site}->{USER}};
      my @row =
        (
         $site,
         $success?"Yes":"No",
         $num_users_current || 0,
         $vomrs_user_info->{"totals"}->{$timeperiod}->{$current_date}->{Site}->{$site}->{$success}->{"Njobs"} || 0,
         convert_num($vomrs_user_info->{"totals"}->{$timeperiod}->{$current_date}->{Site}->{$site}->{$success}->{"WallDuration"} || 0,
                     "WallDuration"),
         convert_num($num_users_current || 0 - $num_users_previous || 0, "Users", 1),
         convert_num(($vomrs_user_info->{"totals"}->{$timeperiod}->{$current_date}->{Site}->{$site}->{$success}->{"Njobs"} || 0) -
                     ($vomrs_user_info->{"totals"}->{$timeperiod}->{$previous_date}->{Site}->{$site}->{$success}->{"Njobs"} || 0),
                     "Njobs", 1),
         convert_num(($vomrs_user_info->{"totals"}->{$timeperiod}->{$current_date}->{Site}->{$site}->{$success}->{"WallDuration"} || 0) -
                     ($vomrs_user_info->{"totals"}->{$timeperiod}->{$previous_date}->{Site}->{$site}->{$success}->{"WallDuration"} || 0),
                     "WallDuration", 1)
        );
      if ($row[3] || $row[6]) {
        $site_summary_table->add(@row);
      }
    }
  }
  print $output_filehandle
    $site_summary_table->rule('_', '_'),
      $site_summary_table->title(),
        $site_summary_table->rule('_', '|'),
          $site_summary_table->body(),
            $site_summary_table->rule('=', '='),
              "\n";
}

sub reporting_name_summary($) {
  my $output_filehandle = shift;
  # Compile a full list of used reporting names (for all active timeperiods).
  my %wanted_reporting_names = map { $_ => 1 }
    (map { keys %{$_->get_alt_branch("ByReportingName")->get_summed_branches()} }
     values %{$all_info->get_alt_branch($timeperiod)->get_alt_branches()});
  my %used_real_vos = map { s&:.*$&&; $_ => 1 } keys %wanted_reporting_names;
  my $want_vo_column = (scalar keys %used_real_vos) > 1;
  my $want_vo_in_intro_line = (scalar keys %used_real_vos) == 1;
  
  if (scalar (keys %used_real_vos)) {
    my $science_fields = "";
    if (exists $vo_data->{(keys %used_real_vos)[0]}
	and exists $vo_data->{(keys %used_real_vos)[0]}->{science_fields}) {
      $science_fields = join(", ", sort keys %{$vo_data->{(keys %used_real_vos)[0]}->{science_fields}});
    }
    my $message = sprintf("Summary of active%s reporting names%s:\n",
			  ($using_reporting_names)?" selected":"",
			  $want_vo_in_intro_line?"":
			  sprintf(" for VO %s (%s)",
				  (keys %used_real_vos)[0],
				  $science_fields));
    print $output_filehandle $message;
    my $reporting_name_table = Text::Table->new
      (
       {
	title => '| ', is_sep => '1' },
       $want_vo_column?({ title => 'VO', align_title => 'center' }, $column_separator,
			{ title => 'Field(s) of Science', align_title => 'center' }, $column_separator):(),
       {
	title => 'Reporting Name', align_title => 'center' },
       $column_separator,
       {
	title => "Job\nSuccess?", align_title => 'center' },
       $column_separator,
       {
	title => '# Sites', align_title => 'center', align => 'num' },
       $column_separator,
       {
	title => "# Jobs", align_title => "center", align => 'num' },
       $column_separator,
       {
	title => "Wall\nTime (h)", align_title => "center", align => 'num' },
       $column_separator,
       {
	title => "Delta\nSites", align => "right", align_title => "center", align => 'num' },
       $column_separator,
       {
	title => "Delta\nJobs", align => "right", align_title => "center", align => 'num' },
       $column_separator,
       {
	title => "Delta Wall\nTime (h)", align_title => "center", align => 'num' },
       {
	title => ' |', is_sep => '1' }
      );
    for my $rep_name (sort keys %wanted_reporting_names) {
      my ($vo_name, $short_reporting_name) = ($rep_name =~ m&^([^:]*):(.*)$&);
      foreach my $success (1, 0) {
	my $njobs = $vomrs_user_info->{"totals"}->{"Reporting Name"}->{$rep_name}->{$timeperiod}->{$current_date}->{$success}->{"Njobs"} || 0;
	my $delta_njobs = convert_num($njobs -
				      ($vomrs_user_info->{"totals"}->{"Reporting Name"}->{$rep_name}->{$timeperiod}->{$previous_date}->{$success}->{"Njobs"} || 0),
				      "Njobs", 1);
	local($Text::Wrap::columns) = 40;
	local($Text::Wrap::huge) = 'overflow';
	my $science_fields = (exists $vo_data->{$vo_name}->{reporting_groups}->{$short_reporting_name}->{science_fields})?
	  $vo_data->{$vo_name}->{reporting_groups}->{$short_reporting_name}->{science_fields}:
	    $vo_data->{$vo_name}->{science_fields};
	my @row =
	  (
	   $want_vo_column?($vo_name,
			    wrap("", "  ", join(", ", sort keys %{$science_fields}))):(),
	   $short_reporting_name,
	   $success?"Yes":"No",
	   num_sites($current_date, $rep_name, $success),
	   $njobs,
	   convert_num($vomrs_user_info->{"totals"}->{"Reporting Name"}->{$rep_name}->{$timeperiod}->{$current_date}->{$success}->{"WallDuration"} || 0,
		       "WallDuration"),
	   convert_num(num_sites($current_date, $rep_name, $success) - num_sites($previous_date, $rep_name, $success), "Sites", 1),
	   $delta_njobs,
	   convert_num(($vomrs_user_info->{"totals"}->{"Reporting Name"}->{$rep_name}->{$timeperiod}->{$current_date}->{$success}->{"WallDuration"} || 0) -
		       ($vomrs_user_info->{"totals"}->{"Reporting Name"}->{$rep_name}->{$timeperiod}->{$previous_date}->{$success}->{"WallDuration"} || 0),
		       "WallDuration", 1)
	  );
	if ($njobs || $delta_njobs) {
	  $reporting_name_table->add(@row);
	}
      }
    }
    print $output_filehandle
      $reporting_name_table->rule('_', '_'),
	$reporting_name_table->title(),
	  $reporting_name_table->rule('_', '|'),
	    $reporting_name_table->body(),
	      $reporting_name_table->rule('=', '='),
		"\n";
  } else {
    print  $output_filehandle "There is no active VO.\n";
  }
}

sub translation_report($) {
  my $output_filehandle = shift;
  return unless $vo_query;
  my $translation_summary_table = Text::Table->new
    (
     {
      title => '| ', is_sep => '1' },
     {
      title => 'FQAN / voi:VOc', align_title => 'center' },
     $column_separator,
     {
      title => 'Reporting Name', align_title => 'center' },
     $column_separator,
     {
      title => 'Source', align_title => 'center' },
     $column_separator,
     {
      title => 'Comment', align_title => 'center' },
     {
      title => ' |', is_sep => '1' }
    );
  my @rows = ();
  # From OIM
  foreach my $reporting_name_group (sort keys %{$vo_data->{$vo}->{reporting_groups}}) {
    foreach my $fqan (@{$vo_data->{$vo}->{reporting_groups}->{$reporting_name_group}->{FQAN}}) {
      next if ($options{"reporting-name"} and
               scalar @{$options{"reporting-name"}} and not
               grep { $_ eq sprintf("%s:%s", lc $vo, $reporting_name_group) } @{$options{"reporting-name"}});
      my @row = (
                 $fqan,
                 $reporting_name_group,
                 "OIM", undef
                );
      push @rows, \@row;
    }
  }
  # From DB.
  my $query = <<EOF;
SELECT VC.VOName as ReportedVOName,
       VC.ReportableVOName as ReportableVOName,
       VO.VOName as `VOName`
FROM VONameCorrection VC
     join VO on (VC.void = VO.void)
WHERE $vo_query
ORDER BY VC.VOName, `VOName`;
EOF
  my $sth = $dbh->prepare($query);
  # print STDERR $sth->{Statement}, "\n";
  $sth->execute();
  while (my $row = $sth->fetchrow_hashref()) {
    my $ReportableVOName = (defined $row->{ReportableVOName})?($row->{ReportableVOName} || '""'):"NULL";
    next if ($options{"reporting-name"} and
             scalar @{$options{"reporting-name"}} and not
             grep { $_ eq sprintf("%s:%s", lc $vo, $row->{VOName}) } @{$options{"reporting-name"}});
    my $fqan = $row->{ReportedVOName};
    if ($fqan =~ m&^/&) {
      $fqan =~ s&/Role=NULL&&;
      $fqan =~ s&/Capability=NULL&&;
    } else {
      $fqan = sprintf("%s:%s",
                      $row->{ReportedVOName},
                      $ReportableVOName);
    }
    my @row =
      (
       $fqan,
       $row->{VOName},
       "Gratia",
       undef
      );
    push @rows, \@row;
  }
  my @final_rows = ();
  foreach my $row (sort rows_by_fqan_rep @rows) {
    # Toss out Gratia records duplicated by OIM records.
    next if ($row->[2] eq "Gratia" and
             grep { $_->[2] eq "OIM" and
                      $_->[0] eq $row->[0] and
                        $_->[1] eq $row->[1] } @rows);
    if ($row->[2] eq "OIM" and
        grep { $_->[2] eq "Gratia" and
                 $_->[0] eq $row->[0] and
                   $_->[1] ne $row->[1] } @rows) {
      $row->[3] = "MISMATCH: Gratia entry overrides until sync.";
    } elsif ($row->[2] eq "Gratia" and
             $row->[0] =~ m&^/& and
             not grep { $_->[2] eq "OIM" and
                          $_->[0] eq $row->[0] } @rows) {
      $row->[3] = "No OIM entry.";
    }

    push @final_rows, $row;
  }
  $translation_summary_table->load(@final_rows);

  print $output_filehandle
    $translation_summary_table->rule('_', '_'),
      $translation_summary_table->title(),
        $translation_summary_table->rule('_', '|'),
          $translation_summary_table->body(),
            $translation_summary_table->rule('=', '='),
              "\n";

  print $output_filehandle <<EOF;
Notes for translation summary table:

* The FQAN is obtained from the job's delegated proxy where available.

* In the absence of the FQAN, the site's reverse gridmap file
  (osg-user-vo-map.txt) is used providing a voi/VOc pair which is
  used for lookup.

* "Source" is the source of the translation. Valid values are, "Gratia"
  or, "OIM." Precedence is given to OIM translations where
  available. Default translations are provided by the collector the
  first time a particular FQAN or voi/VOc combination is seen.

EOF

}

my $alt_vo_lookup_table;
sub alt_vo_table {
  return $alt_vo_lookup_table if $alt_vo_lookup_table;
  $alt_vo_lookup_table = {};
  foreach my $vo (keys %$vo_data) {
    if (exists $vo_data->{$vo}->{alt_vos} and $vo_data->{$vo}->{alt_vos}) {
      foreach my $alt_vo (@{$vo_data->{$vo}->{alt_vos}}) {
        $alt_vo_lookup_table->{lc $alt_vo} = $vo;
      }
    }
  }
  return $alt_vo_lookup_table;
}

sub actual_vo_name {
  my $vo = shift;
  return alt_vo_table()->{lc $vo} || $vo;
}

sub rows_by_fqan_rep {
  return ($a->[0] cmp $b->[0] or
          $a->[2] cmp $b->[2] or
          $a->[1] cmp $b->[1]);
}

sub print_anded_list($\@) {
  my ($fh, $listref) = @_;
  my $and_index = scalar @$listref - 2;
  my $item_count = 0;
  foreach my $item (@$listref) {
    print $fh "$item";
    if ($item_count < $and_index) {
      print $fh ", ";
    } elsif ($item_count == $and_index) {
      print $fh " and ";
    } else {
      print $fh ".\n\n";
    }
    ++$item_count;
  }
}

__END__

### Local Variables:
### mode: cperl
### End:
