#!/usr/bin/perl

# We put any configuration constants here in front.  It helps
# to capitalize them for visibility later in the program.

$RECLEN = 8;

# Note how we can assign a list of pairs to an entire
# associative array in order to initialize it.

%fullname = (
    'sh', 'sheep',
    'ca', 'camels',
    'ox', 'oxen',
    'do', 'donkeys',
    'so', 'sons',
    'da', 'daughters',
);

# Open the files (devices, in this case).

open(PCTR, "</dev/pctr")
    || die "Couldn't open pigeon's clay tablet reader: $!\n";
open(PCTW, ">/dev/pctw")
    || die "Couldn't open pigeon's clay tablet writer: $!\n";

# Main loop.  This loop runs till last pigeon brings EOF tablet.

for ($recnum = 0; read(PCTR, $record, $RECSIZE); $recnum++) {

    # Break apart the record into its fields.

    ($beastie, $count) = unpack("A2 A6", $record);

    # Add the count into the proper associative array entry.
    # Note that $count may be negative, in which case the
    # entry is decreased by the += operator.

    $count{$beastie} += $count;

    # Print out the acknowledgement for the return pigeon.
    # Instead of sending a count back, we send back the record
    # number, for the beastie keepers to check off as received.
    # $newrec is guaranteed to be exactly 8 bytes long.

    $newrec = pack("A2 A6", $beastie, $recnum);
    print PCTW $newrec;
}

# End-of-Day processing.  We translate the abbreviated beastie
# name back to the full name to print it out, along with the
# accumulated count for the day.

foreach $key (sort keys(%count)) {
    printf "%-20s %d\n", $fullname{$key}, $count{$key};
}
