#!/usr/bin/perl -w
#
# Go through list of input files
#   Extract run and field from input filename
#   If a $run-$field directory doesn't yet exist, create it
#   Move the file to that directory
@filelist = @ARGV;

die( "Give file list as arg!\n") unless (length($ARGV[0]) > 0);


foreach $file (@filelist) {
    # Extract run and rerun, at the same time skipping non-SDSS filenames
    if ($file =~ /fpC-([0-9]{6})-([ugriz])[1-6]-([0-9]{4})\.fit/) {
	$run = $1;
	$filter = $2;
	$field = $3;
	# For the run number, I want to strip leading 0s
	$run =~ s/^0+//;
	$targetdir = "$filter/$run-$field";
	print "$targetdir\n";

	# Test if directory exists and is writeable to; if exists but not writeable, die
	if (-e $targetdir) {
	    die("$targetdir exists, but is not a directory\n") unless 
		-d $targetdir;
	    die("$targetdir exists, but I cannot write to it\n") unless
		-w $targetdir;
	} else {
	    # If it doesn't exist, create it - but first assume that
	    # the parent needs to be created, too
	    $filterdir = $filter;
	    if (-e $filterdir) {
		die("$filterdir exists, but is not a directory\n") unless 
		    -d $filterdir;
		die("$filterdir exists, but I cannot write to it\n") unless
		    -w $filterdir;
	    } else {
		mkdir $filterdir or die("Cannot create per-filter directory $filterdir\n");
	    }
	    mkdir $targetdir or die ("Cannot create $targetdir\n");
	}
	if (system("mv $file $targetdir/") != 0) {
	    die ("Could not write $file to $targetdir");
	}
    }
}

exit 0;
