#!/usr/local/bin/perl
#
# MKTHRUCAT -- Create the thruput catalog used by mkcomptab
#
# Usage: traverse [directory]

undef %table;			# Global vriable for storing patterns
my ($arg, $pattern, $dir);

# Use default directory if none passed on the command line

push (@ARGV , '/grp/hst/cdbs/comp/') unless @ARGV;

# Open the thruput catalog and write the header

open (THRUCAT, '>thrucat.dat') || die "Can't write catalog\n";
print THRUCAT <<EOQ;
# Each line in the thruput catalog contains a filename pattern
# and a corresponding iraf directory name. Mkcomptab uses this 
# file to figure out what directory a thruput file belongs in.
# If mkcomptab returns the error 'match not found in thruput 
# catalog', this file will need to be updated to include a pattern
# for the new thruput file.
#
# This catalog was created by mkthrucat.pl in the util directory.
#
# FILENAME_PATTERN      DIRECTORY
#--------------------------------
EOQ

# Traverse all directories passed on command line
# Build the hash table from the filenames and directories

foreach $arg (@ARGV) {
    traverse ($arg, 0);
}

# Write the contents of the hash table to the catalog

@pattern = sort keys %table;

foreach $pattern (@pattern) {
    $dir = $table{$pattern};
    $pattern .= "\t" if length($pattern) < 8;

    print THRUCAT "$pattern\t\t$dir\n";
}

close (THRUCAT);

# TRAVERSE -- Recursive subroutine to handle directory traversal

sub traverse {
    my ($dir, $level) = @_;
    my (@files, $olddir, $file);

    # Save current directory in $olddir

    $olddir = `pwd`;
    chop ($olddir);

    if (chdir ($dir) && opendir (DIR, '.')) {
	# Scarf filenames into array

	@files = readdir (DIR);
	closedir (DIR);

	# Call traverse recursively for subdirectories

	foreach $file (@files) {
	    &traverse ($file, $level + 1) 
		if -d $file && $file ne '.' && $file ne '..';
	}

	# Remove directories from list of filenames

	@files = grep (! -d, @files);

	# Call subroutine to process non-directory files in current dir

	&addpattern (@files) if $level;

    } else {
	print "Can't access $dir\n";
    }

    chdir $olddir || die "Can't return to $olddir\n";
}

# ADDPATTERN -- Add patterns to the hash table

sub addpattern {
    my (@files) = @_;
    my (@dir, $dir, $pattern, $olddir);

    # Get current directory
    
    $dir = `pwd`;
    chop $dir;

    # Convert to iraf logical

    @dir = split(m%/%, $dir);
    $dir = pop(@dir);
    $dir = "cr${dir}comp\$";

    # Get patterns and store in hash table if they are new

    foreach $pattern (@files) {
	next if $pattern !~ /_\d\d\d\.(tab|fits)$/;

	$pattern =~ s/_[^\.]*/_\*/;
	$table{$pattern} = $dir unless $table{$pattern};

	if ($table{$pattern} != $dir) {
	    $olddir = $table{$pattern};
	    die "Error: $pattern is in two directories: $dir and $olddir\n";
	}
    }
}
