#!/usr/bin/perl

# offline.pl - manipulate seismonitor's data file in offline mode. 
#

$datfile = "/seismonitor/seis.dat";
$pidfile = "/seismonitor/seis.pid";

&readDatFile;
&killpid;

ITER:
while ($input ne 'q' || $input ne 'c' || $input != /\d/ || $input != /\d\.\d/) {
	print qq|Usage: enter magnitude, (s)hutdown or (c)ancel\n|;
	$input = <STDIN>;
	chop($input);

		if ($input eq 's') {
			$y="-1";
			&writeDatFile;
			print qq(Shutting down seismonitor\n);
			exit(0);
		} elsif ($input eq 'c') {     
			print qq(Cancelled\n);
			exit(0);	
		} elsif ($input < '9' && $input > '2') {
			$y = $input;
			print qq(Entered $y\n);
			$y*=10;
			&writeDatFile;
			exit(0);
		} else {
			print qq(\n~ ~ ~\n);
			print qq(Enter a single-digit value (x), or a double-digit value with decimal place (x.x).\n);
			print qq(Range greater than 2, less than 9.\n);
			print qq(~ ~ ~\n\n);
			next ITER;
		}
}
sub killpid {
	if (-e $pidfile) {
		open(PID, "$pidfile") or warn "Can't open pid file for reading: $!";
		while (<PID>) {
			@pid = split(/\s+/, $_);
		}
	close(PID);
	}
kill -9, $pid[0];
}

sub readDatFile {
open (FILE, "<$datfile") or die "Can't open data file for reading: $!\n";
	while (<FILE>) {
		@line = split(/\s/, $_);
	}
close (FILE);
$x = $line[0]; $y = $line[1]; 
# Ensure 1st element is altered each time to trigger fileio
	if (!($x%2)) {
		$x+=3; 
	} else {
		$x-=1; 
	}
}

sub writeDatFile {
open(DAT, ">$datfile") or die($!);
printf DAT ("%06d %2d\n", $x, $y);
close(DAT);
}
