#! /usr/bin/perl
$sF = "C2bin.state";
if (open(ST,"<$sF")) {
  $s = <ST>;
  $s = int($s);
  close(ST);
} else {
  $x = <STDIN>;
  $s = 0;
  $y = 0;
  $r = 0;
  goto OUT;
}
# State +/- mimics the state that C1 is thought to be in
# value determines the action
# given a new value by negative input (nearest integer)
# positive input -- no change in state
$plus = 1;
if ($s < 0 ) {
  $plus = -1;
} #sign of the old state (0 is +)

$s = $plus*$s;  #make positive

$r = 7; #constant, not noticed

chop($x = <STDIN>);

if ($x < 0) { #change state
  $y = 0;  #default is to not call C1 with state unchanged
  $x = -$x;
  $x = int($x/20.0); # 5->0 for [-100,0), use as switch
  if ($x > 3) { #error:  pass to handler for message, no state change
  } elsif ($s == 0) { # go into states 0-3 on command
    $s = $x;
  } elsif ($s <= 2) { 
    if ($x == $s) { #advance to next state
      $s += 1;
    } # else message 1 or 2
  } elsif ($s >= 3) {
    if ($x == 3) { #invoke C1 for mode change
      if ($s < 7 || $plus < 0) { #too many mode changes, but end up in positive
        $s += 1; 
        $y = 1;
        $r = 9;
        $plus *= -1;  #reverse local state
      } #else message 8
    } # else message 3 - 7
  } else { #default
  }

} else {
  $y = 1;  #call C1
  $r = 3;
}
$s = $plus*$s; #restore sign to state

OUT:
print "$y\n";
print STDERR "$r\n";
open(ST, ">$sF");
print ST $s;
close(ST);
