# Period search for a star for frequencies between 0 and 20 c/d.
# Input lines consist
use Period;

$Period::N = 0;

if (!$star)
{
	$star = "Test";
}
print STDERR "Star = $star\n";

while ($line = <>)
{
	if (substr($line,0,1) ne '#')
	{
		chomp($line);
		if ($line ne "")
		{
			@obs = split(' ',$line);
			$Period::N++;
			$Period::ObsJD[$Period::N] = $obs[0];
			$Period::ObsMag[$Period::N] = $obs[1];
		}
	}
}

print STDERR "Data read\n";

my $analysis = "pdm"; # PDM periodogram
#$analysis = "lsp"; # Lomb-Scargle periodogram

my $freqfile = "$Period::OUTDIR$star.$analysis";
my $step = Period::HighStep;
my $f0 = 0;
my $f1 = 20;

# Do the analysis
#open(ANALYSIS, "| $Period::HOME$analysis $f0 $f1 $step >$freqfile") || die "can't fork: $!";
if ($ENV{PeriodPDM} && open(ANALYSIS, "| $Period::HOME$analysis $f0 $f1 $step >$freqfile"))
{
	local $SIG{PIPE} = sub { die "spooler pipe broke" };

	for ($i = 1; $i <= $Period::N; $i++)
	{
		print ANALYSIS "$Period::ObsJD[$i] $Period::ObsMag[$i]\n";
	}

	close ANALYSIS || die "bad spool: $! $?";
}
elsif ($analysis eq "pdm")
{	# Executable not present, do the analysis in Perl
	Period::Analysis ($f0, $f1, $step, ">$freqfile");
}
else
{
	die "can't fork: $!"
}

print STDERR "Analysis done\n";

# Make a GNUPlot command file
#$GNUfile = "Analysis.gnp";
#Period::PlotAnalysis ("$Period::OUTDIR$star-$analysis", $freqfile, $analysis, $GNUFile);

# Draw the graph
#system("$Period::GNUPlot $GNUfile");
Period::PlotAnalysis ("$Period::OUTDIR$star-$analysis", $freqfile, $analysis, "| $Period::GNUPlot");

print STDERR "Analysis plotted\n";


# List frequencies
my $ext = "min";
if ($analysis eq "lsp")
{
	$ext = "max";
}

# List the extrema
#system("$Period::Extrema -search=$ext -n=25 $freqfile");

# Make phase plots
my $PhaseFile;
my $PhaseList = "";
my $GifList = "";

open (FREQ, "$Period::Extrema -search=$ext -n=4 $freqfile |");
while ($line = <FREQ>)
{
	my ($id, $freq) = split(' ',$line);
	my $title;
	if ($freq < 1)
	{
		$title = sprintf("$id (%.4f d)",1/$freq);
	}
	else
	{
		$title = "$id ($freq c/d)";
	}
	$PhaseFile = "$Period::OUTDIR$id.dat";
	Period::Phase ($freq, ">$PhaseFile");
	$GifList = "$GifList $Period::OUTDIR$id.gif";
	$PhaseList = "$PhaseList $PhaseFile";
	Period::PlotPhase ($PhaseFile, "$Period::OUTDIR$id", $title, "| $Period::GNUPlot");
#system ("ren $PhaseFile $Period::OUTDIR$id.txt");
}
close FREQ;

# Make a montage of the phase diagrams
my $PhasePlot = "$Period::OUTDIR$star.gif";
system ("$Period::Montage  -tile 2x2 -geometry 320x240+3+10 $GifList $PhasePlot");

print STDERR "Phase plots created\n";


# Remove temporary files
system("$Period::RM $PhaseList");
system("$Period::RM $GifList");





