#!/usr/local/bin/perl -w

# Pair correlation analysis for two data files(the latter refers the formaer).
# Self correlation analysis for single data file.
# Data should be numerical and one column.
# Mon Jun 25 2001 ;  by Isoji MIYAGI

# data file reading. 
if(@ARGV==2){
    open(RAIN,"<$ARGV[0]") or die "cannot open rain data\n";
    @rains=<RAIN>;
    close(RAIN);
    open(ERUPT,"<$ARGV[1]") or die "cannot open eruption data\n";
    @eruptions=<ERUPT>;
    close(ERUPT);
    chomp (@eruptions, @rains);
    &catdog();
    &printGraph("pair correlation", "p", "", "-84:84", "-42:42", "-21:21");
} elsif (@ARGV==1){
    open(FILE,"<$ARGV[0]") or die "cannot open data\n";
    @myselves=<FILE>;
    close(FILE);
    chomp @myselves;
    &selfish();
    &printGraph("self correlation", "s", "", "-84:84", "-42:42", "-21:21");
} else {
    print STDERR "data file open failed\n";
    exit 0;
}


# a subroutine for pair correlation 
sub catdog(){
    open(OUT,">./deleteMe.txt");
    foreach $theRainday (@rains) {
        foreach $theEruptionday (@eruptions) {
            $delDay = sprintf("%d", $theRainday - $theEruptionday);
#            print OUT "#\t$theRainday\t$theEruptionday\t$delDay\n";
            $N{$delDay}++;
        }
    }
    foreach $theDelDay (sort{$a <=> $b}keys(%N)) {
        print OUT "$theDelDay\t$N{$theDelDay}\n";
    }
    close(OUT);
}


# a subroutine for self correlation 
sub selfish () {
    open(OUT,">./deleteMe.txt");
    foreach $theDay (@myselves) {
        foreach $theOtherDay (@myselves) {
            $delDay = sprintf("%d", $theDay - $theOtherDay);
            print OUT "#\t$theDay\t$theOtherDay\t$delDay\n";
            $N{$delDay}++;
        }
    }
    foreach $theDelDay (sort{$a <=> $b}keys(%N)) {
        print OUT "$theDelDay\t$N{$theDelDay}\n";
    }
    close(OUT);
}


# a subroutine for graph making
sub printGraph(){
    my($title, $type, @xrange)=@_;
    foreach $theXRange (@xrange) {
    open (GNUP, "|/usr/bin/gnuplot") || die "could not open GNUPLOT\n";
    print GNUP <<PERIOD;
set terminal png small color
set title \"$title\"
set output \"$ARGV[0]-$ARGV[1]$type$theXRange.png\"
set xlabel \"rainy day after the eruption\"
set ylabel \"number\"
plot  \[$theXRange\]\[0:\] \'deleteMe.txt\' title  \"$ARGV[0]-$ARGV[1]\"  with impulses 

PERIOD
close (GNUP);
    }
}
exit 0;