#!/usr/bin/perl -w

# lab 10 example
#-----------------------------------------

$outfile = $ENV{HOME}.'/tmp.txt';

# Prompt the user to enter a path.
do {
    # Check that the entered path is a directory. Either quit or ask again 
    # if the path fails the directory test.
    print "Please enter a directory path: ";
    chomp($ans = <STDIN>);
    $path = $ans if( -d $ans);
}until($path ne '');


# Scan the contents of the directory for any files.
opendir(ED, "$path") || die "cannot open directory: $!";
$oldestdate = 9999999999999999999999;
$biggestsize = -1;
while($item = readdir(ED)) {
    next if(($item eq '.') || ($item eq '..'));
    $fullpath = $path.'/'.$item;
    if( -f $fullpath ) {
        @fileinfo = stat($fullpath);
        # Determine the oldest file in the directory (based on modification date)
        if($fileinfo[9] < $oldestdate) {
            $oldestdate = $fileinfo[9];
            $oldestfile = $fullpath;
        }
        # Determine the oldest file in the directory (based on modification date)
        if($fileinfo[7] > $biggestsize) {
            $biggestsize = $fileinfo[7];
            $biggestfile = $fullpath;
        }
    }   
}
closedir(ED);

open(OUT, ">$outfile") || die "cannot open file: $!";

# print the results to both the screen and a file named tmp.txt 
# using the file's absolute path.
$oldstring = "The oldest file found is $oldestfile\n";
print OUT $oldstring;
print $oldstring;

$bigstring = "The largets file found is $biggestfile with a size of $biggestsize bytes.\n";
print OUT $bigstring;
print $bigstring;
close(OUT);

# Rename the tmp.txt file to lab10.output.txt
chdir($ENV{HOME});
rename ('./tmp.txt', './lab01.output.txt');
exit;