# Copyright (c) 2007  Paul Price
#
# $Id: Operations.pm,v 1.7 2008-02-06 04:04:33 price Exp $

package PS::IPP::Operations;

use strict;
use warnings FATAL => qw( all );

our $VERSION = '0.01';

use Carp qw( carp );
use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Config qw( caturi
			file_scheme
			);

# Allow exporting of functions
use base qw( Exporter );
our @EXPORT_OK = qw(
		    skycell_file
		    generate_skycells 
		    );

#$::RD_TRACE = 1;
#$::RD_HINT = 1;
#use Data::Dumper;

sub skycell_file
{
    my $tess_id = shift;	# Tessellation identifier
    my $skycell_id = shift;	# Skycell identifier
    my $workdir = shift;	# Working directory

    unless (defined $tess_id and defined $skycell_id and defined $workdir) {
	carp "Input parameters not defined";
	return 0;
    }

    return caturi($workdir, "tess_" . $tess_id, "sky_" . $skycell_id, $skycell_id );
}



# Extract skycells to images
sub generate_skycells
{
    my $ipprc = shift;		# Configuration object
    my $tess_id = shift;	# Tessellation identifier
    my $skycells = shift;	# List of skycell ids
    my $workdir = shift;	# Working directory
    my $verbose = shift;	# Verbose?

    unless (defined $ipprc and defined $tess_id and defined $skycells and defined $workdir) {
	carp "Input parameters not defined.";
	return 0;
    }

    my $dvoImageExtract = can_run('dvoImageExtract') or die "Can't find dvoImageExtract";

    my $tess_dir = $ipprc->tessellation_catdir( $tess_id ); # Tessellation catdir for DVO
    unless (defined $tess_dir) {
	carp "Can't get list of tessellations.";
	return 0;
    }
    $tess_dir = $ipprc->convert_filename_absolute( $tess_dir );

    foreach my $skycell_id ( @$skycells ) {
	# Extract the skycell to an image
	my $skyFile = skycell_file($tess_id, $skycell_id, $workdir);
	unless ($ipprc->file_exists( $skyFile )) {
	    my $skyFileResolved = $ipprc->file_create( $skyFile ); # Resolved filename, for Nebulous
	    my $command = "$dvoImageExtract -D CATDIR $tess_dir $skycell_id -o $skyFileResolved";
	    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
		run(command => $command, verbose => $verbose);
	    unless ($success) {
		carp "Unable to perform dvoImageExtract for $tess_id $skycell_id";
		return 0;
	    }
	}
    }

    return 1;
}






1;

__END__;

