#!/usr/bin/env perl

use warnings;
use strict;

use IPC::Cmd qw( can_run run );
use File::Spec;
use File::Find::Rule;
use PS::IPP::Config;
my $ipprc = PS::IPP::Config->new();

die "Usage: $0 DIR1 DIR2 DIR3...\n" if scalar @ARGV == 0;

my $pxinject = can_run('pxinject') or die "Can't find pxinject\n";

my $num = 0;
foreach my $dir ( @ARGV ) {
    my $absdir = File::Spec->rel2abs( $dir );

    $num += inject('bias', 'zero*.fits', $absdir);
    $num += inject('flat', '?flat*.fits', $absdir);
    $num += inject('sm', 'sm*.fits', $absdir);
    $num += inject('w', 'w*.fits', $absdir);
}

print "$num files injected.\n";


sub inject
{
    my $type = shift;		# Type of image
    my $glob = shift;		# Glob for this type
    my $dir  = shift;		# Directory to search (absolute path)

    my @files = File::Find::Rule->file->name( $glob )->in( $dir );
    foreach my $file ( @files ) {
	my ( $vol, $path, $name ) = File::Spec->splitpath( $file );
	my ( $exp ) = $name =~ /(.*)\.fits/;

	my $relpath = $ipprc->convert_filename_relative( $file );

	my $command_exp = "$pxinject -newExp -exp_id $exp -inst CTIO_MOSAIC2 -telescope CTIO4m " .
	    "-exp_type $type -imfiles 1" ; # Command to run
	my ( $success_exp, $error_code_exp, $full_buf_exp, $stdout_buf_exp, $stderr_buf_exp ) =
	    run( command => $command_exp, verbose => 1 );
	die "Unable to inject $exp: $error_code_exp\n" if not $success_exp;
	
	my @line = split(/\s+/, $$stdout_buf_exp[0]); # The output line, containing the exposure tag
	my $exp_tag = $line[2];	# The exposure tag

	my $command_imfile = "$pxinject -newImfile -exp_tag $exp_tag -class fpa -class_id fpa " .
	    "-uri $relpath"; # Command to run
	my ( $success_imfile, $error_code_imfile, $full_buf_imfile,
	     $stdout_buf_imfile, $stderr_buf_imfile ) = run( command => $command_imfile, verbose => 1 );
	die "Unable to inject $exp imfile: $error_code_imfile\n" if not $success_imfile;
    }

    return scalar @files;
}


__END__
