#!/usr/bin/perl
use Statistics::OLS;
use Math::FFT;
use Math::Stat;
use Math::Spline qw(spline linsearch binsearch);
use Math::Derivative qw(Derivative2);
use Math::Approx;
use Astro::FITS::CFITSIO qw( :longnames :constants );
use PDL;
use PDL::Fit::Polynomial; 
use PDL::Filter::Linear;
use PGPLOT;  # Load PGPLOT module
use PDL::Fit::Gaussian;
use PDL::Slatec;
use PDL::Image2D;
#use PDL::Matrix;


$DIR_DATA="/disk-a/sanchez/ppak/legacy/DATA/V500/reduced_v1.3c/";
#$DIR_DATA="/disk-b/sanchez/ppak/legacy/DATA/V500/reduced_v1.3c/";

$max_size=10;
$frac=0.9;


$n=0;
open(DIR,"ls $DIR_DATA/*.V500.rscube.fits.gz |");
while($file=<DIR>) {
    chop($file);
    $name=$file;
    $name =~ s/$DIR_DATA//;
    $name =~ s/\///g;
    $cut=".V500.rscube.fits.gz";
    $name =~ s/$cut//;
    $existe=0;
    
    open(NOW,"ls cont_seg.*$name*.fits.gz |");
    $now=<NOW>;
    close(NOW);
    chop($now);
    if ($now eq "") {
	$FILE[$n]=$file;
	$NAME[$n]=$name;
	print "$file $name $existe\n";
	$existe=1;
	$n++;
    }
}
close(DIR);
#exit;
open(LOG,">ana_seg.log");
for ($i=0;$i<$n;$i++) {    

    $call="./ana_single.pl ".$NAME[$i];
    mycall($call);
    $do_ftp=0;
    if ($do_ftp==1) {
	open(FTP,">ftp.input");
	print FTP "open ftp://mycalifa:myafi07lAc\@ftp.caha.es\n";
	print FTP "mkdir /TMP/GAS_tests/FIT3D/SEG6_v1.3c\n";
	print FTP "cd /TMP/GAS_tests/FIT3D/SEG6_v1.3c\n";
	print FTP "mkdir maps\n";
	print FTP "cd maps\n";
	print FTP "mput -f map.*$NAME[$i]*.fits.gz\n";
	print FTP "cd ..\n";
	print FTP "mkdir cubes\n";
	print FTP "cd cubes\n";
	print FTP "mput -f GAS.$NAME[$i].cube.fits.gz\n";
	print FTP "cd ..\n";
	print FTP "mkdir plots\n";
	print FTP "cd plots\n";
	print FTP "mput -f *$NAME[$i]*.ps\n";
	close(FTP);
	$call="ncftp < ftp.input ";
	mycall($call);
    }

}
close(LOG);
exit;

sub mycall {                                      
                                                                   my $call=$_[0];

														     print "$call | PROCESSING\n";                                                                                 
    system($call);                                                                                                
    print LOG "$call\n";                                                                                          
    print "DONE\n";                                                                                              
} 
