# Date: Sat, 28 Aug 2004 12:20:22 -0700
# From: Zed Lopez
# Subject: Re: [SPOILER] Solution to Perl Quiz-of-the-Week #22
# 
# This is driven by File::Find so it processes the files in whatever
# order File::Find finds them, and also will go on to process any files
# in subdirectories.
# 
#!/usr/bin/perl
use strict;
use warnings;

use Getopt::Long;
use File::Find;
use Date::Calc qw(Today Date_to_Days);

my $lookahead = 7;
GetOptions("n=i" => \$lookahead);

my $dir = "$ENV{HOME}/.upcoming";
die "No directory $dir" unless -d $dir;

my $any_output;
my ($this_year, $this_month, $today) = Today();
my $days = Date_to_Days($this_year, $this_month, $this_day);

find \&process, $dir;

sub process {
    return if -d;
    open FH, "<$_" or die "Couldn't open $File::Find::name: $!";
    my @out;
    {
        local $_;
        while (<FH>) {
            my ($month, $day, $year, $event) =
m|^\s*(\d+)(?:/(\d+))?(?:/(\d*))?\s+(.*)$|;
            $year ||= $this_year;
            ($month, $day) = ($this_month, $month) unless defined
$day; # just DD not MM/DD or MM/DD/YYYY
            my $diff = Date_to_Days($year, $month, $day) - $days;
            if ($diff >= 0 and $diff <= $lookahead) {
                push @out, [$diff, join ' ', proximity($diff),
(sprintf "%02d/%02d", $month, $day), "$event"];
            }
        }
        return unless @out;
    }
    print "\n" if $any_output++;
    print join "\n", $_, (map $_->[1], sort { $a->[0] <=> $b->[0] } @out), '';
    close(FH);
}

sub proximity {
    my $diff = shift;
    return "($diff)" if $diff > 7;
    return ('   ===>', 
            '   -->',
            '  -->',
            ' -->',
            '-->',
            '->',
            '>',
            '',
            )[$diff];
}
