#!/usr/bin/env perl

use warnings;
use strict;

use File::Spec;
use File::Find::Rule;

die "Usage: $0 SOURCE_DIR TARGET_DIR\n" if scalar @ARGV != 2;

my $source = File::Spec->canonpath( $ARGV[0] );
my $target = File::Spec->canonpath( $ARGV[1] );

my @dirs = File::Find::Rule->directory->in( $source );

# Create the directory structure
foreach my $dir ( @dirs ) {
    my $rel = File::Spec->abs2rel( $dir, $source );
    my @subs = File::Spec->splitpath( $rel );
    
    # Create all the underlying directories
    my $source_path = $source;	# Path we've traversed for source
    my $path = $target;	# Path we've traversed for target
    foreach my $subdir ( @subs ) {
	my $newdir = File::Spec->catdir( $path, $subdir );
	if (defined $subdir and length $subdir > 0) {
	    if (not -d $newdir) {
		print "mkdir $newdir\n";
#		mkdir $newdir;
	    }
	    $path = $newdir;
	}
    }
}

# Find the files
my @files = File::Find::Rule->file->name( '*.fits*' )->in( $source );

foreach my $file ( @files ) {
    my $rel_name = File::Spec->abs2rel( $file, $source );

    my $unzipper;
    if ($rel_name =~ /\.fits\.gz$/) {
	$unzipper = 'gunzip -c';
	$rel_name =~ s/\.gz$//;
    } elsif ($rel_name =~ /\.fits\.bz2$/) {
	$unzipper = 'bunzip2 -c';
	$rel_name =~ s/\.bz2$//;
    } elsif ($rel_name =~ /\.fits$/) {
	$unzipper = 'cat';
    } else {
	die "Unrecognised file type for $rel_name\n";
    }

    my $out_file = File::Spec->rel2abs( $rel_name, $target );

    print "$unzipper $file > $out_file\n";
#    system "$unzipper $file > $out_file";
}

__END__;

