#!/usr/bin/perl -w

use strict;

sub main
{
    my $argc = scalar(@ARGV);

    if ($argc < 1 || $ARGV[0] eq '-h' || $ARGV[0] eq '--help')
    {
        print "Usage: $0 <complete list file> [<partially list file>]\n";

        exit 10;
    }

    my $filename_list = $ARGV[0];
    my $filename_part = ($argc == 2 ? $ARGV[1] : "-");

    my @code_list = ();

    my %hash_date = ();
    my %hash_list = ();
    my %hash_part = ();

    my $list_count = 0;

    # read complete list file
    open(FILE, "$filename_list") || die "cannot open file '$filename_list'";

    while (<FILE>)
    {
        chomp;

        next if /^$/;
        next if /^# /;

        if (/^(\d{4}-\d{2}-\d{2}) ([A-Za-z0-9]{12}) /)
        {
            push @code_list, $2;

            $hash_date{"$1 $2"} = $2;
            $hash_list{$2} = $_;

            $list_count++;
        }
        elsif (/^([A-Za-z0-9]{12}) /)
        {
            push @code_list, $1;

            $hash_list{$1} = $_;

            $list_count++;
        }
        else
        {
            die "cannot parse line '$_'";
        }
    }

    close FILE;

    print "INFO: $list_count entries in complete list.\n";

    # read partially list file
    open(FILE, "$filename_part") || die "cannot open file '$filename_part'";

    my $part_count = 0;

    while (<FILE>)
    {
        chomp;

        if (/^([A-Za-z0-9]{12}) / || /^([A-Za-z0-9]{12})$/)
        {
            $hash_part{$1} = $_;

            $part_count++;
        }
        else
        {
            die "cannot parse line '$_'";
        }
    }

    close FILE;

    print "INFO: $part_count entries in partial list.\n";

    # print all complete list lines for cave codes from partial list

    my $match_count = 0;

    foreach my $i (@code_list)
    {
        if (defined($hash_part{$i}))
        {
            print $hash_list{$i} . "\n";

            $match_count++;
        }
    }

    foreach my $i (keys %hash_part)
    {
        if (!defined($hash_list{$i}))
        {
            # die "cannot find cave code '$i' in complete list";
            print "WARN: cave '$i' not found!\n";
        }
    }

    print "INFO: $match_count matches found.\n";
}

main();
exit 0;
