#!/usr/bin/perl

#------------------------------------------------------------------------------
#This PERL script makes one big list for all the files found under the user supplied
#directory.
#Written by Matthew McCready
#--------------------------------------------------------------------------

use Getopt::Long;
use File::Copy;
 use Cwd;

use lib "/home/m/mccre004/File-Recurse-0.11/blib/lib";
use File::Recurse;


sub usage() {
        print "Usage: perl $0 [-directory=<directory>]\n";
        print "Example: perl $0  -directory=/usr/directory\n";
        print"where list.txt is the filename of the list file\n";
        print "and /usr/directory is the directory where the .xml files to";
        print " be listed are located.\n";

}
%gOptions;
&GetOptions(\%gOptions, qw(directory=s) );
unless ($gOptions{directory}) {
        usage();
        exit(1);
};

$directory=$gOptions{directory};

my $Currdir = getcwd;
#print "\$Currdir = $Currdir\n";
#print "\$0 = $0\n";

opendir INMIF, $directory;

foreach $file (readdir INMIF){
if ($file ne "." or $file ne ".."){
#print "-------------------------------------------------------------------\n";
#print "\$file = $file\n";
$locFirstUnder=index($file,"_");
$FileA=substr($file,$locFirstUnder+1);
#print "\$FileA = $FileA\n";
$locSecondUnder=index($FileA,"_");
$FileB=substr($FileA,$locSecondUnder+1);
#print "\$FileB = $FileB\n";
$locThirdUnder=index($FileB,"_");
#print "\$locThirdUnder = $locThirdUnder\n";
$lastUnder=rindex($FileB,"_");
#print "\$lastUnder = $lastUnder\n";
$length=$lastUnder-$locThirdUnder-1;
$theme=substr($FileB,$locThirdUnder+1,$length);
#print "\$theme = $theme\n";

$fullfile = $directory . "/" . $file;
$FullDirectory= $Currdir  . "/" . $theme;
$ParentDirectory= $Currdir  . "/" . "ParentFiles";
$currProgram = $Currdir  . "/" .  $0;
print "\$currProgram = $currProgram\n";

if (-e $ParentDirectory){
}else{
#print "making the $ParentDirectory(parent Directory)\n";
system  "mkdir $ParentDirectory";
};

if (-e $theme){
if ($file ne "." or $file ne ".." or $file ne "..."){
system "cp $fullfile $FullDirectory";
};
}else{

if ($FullDirectory ne $currProgram){
#print "making $FullDirectory(theme directory)\n";
system "mkdir $FullDirectory";
system "cp $fullfile $FullDirectory";
system "cp $fullfile $ParentDirectory";
};
};
};
};
