#!/usr/bin/perl
use strict;
use warnings;
while(<>)
{
	my $file = $_;
	chomp($file);
        if(check_file($file)) {	
		exit 0 if($file =~ /^--EOF--/); 
		print "This does not look like a program library dump\n";
		print "we got $_ as the first line instead of a file name\n";
		exit 1;
        } else {
		mkdir("OPLC");
		write_file($_);
	}
}

#Make sure we hit a file
#a file should be all uppercase
#and be 7 chars long
#and it should not be named
#COMMON
#we return a 0 for success and
#a 1 for fail. 
sub check_file {
	my $file = $_;
	#make sure we trim all whitespace from filenames
	$file =~ s/\s+//g; 
	if ($file =~ /^COMMON$/) {
		return 1;
	}
	if (length($file) <= 7) {
		if ($file eq uc $file) {
			return 0;
		}
	}
	return 1;
}

#Write a file up to --EOR-- marker
#returning to the main while loop
#to get the next file to process.
sub write_file {
	my $fh;
	my $file;
	$file = $_;
        chomp($file);
	#make sure we trim all whitespace from filenames
	$file =~ s/\s+//g;
	my $firstline = $_;
	my $secondline = <>;
	if($file =~ /^--EOF--/) {
		exit 0;
        }
	if($secondline =~ /^COMMON/) {
		open($fh,">","OPLC/$file");
		print "extracting OPLC/$file\n";
	} else {
		open($fh,">","$file");
		print "extracting $file\n";
	}
	print $fh $firstline;
	print $fh $secondline;
	while(<>) {
		my $line = $_;
		chomp($line);
		if($line =~ /^--EOR--/) {
			close($fh);
			return;
		}	
		if($line =~ /^--EOF--/) {
			close($fh);
			exit 0;
		}
		print $fh $_;
	}
}
