#! /usr/bin/gawk -f

# Cleans the raw screen brightness sensor (SBS) channel
# by mapping values 0, -0.125, and -0.25 (or
# close to them) to 0, 0.5, and 1.0, respectively.
# Also sets it to 0.5 in all SETUP intervals.

BEGIN {
  nt = 0;      # Number of frames read.
  up = -1;     # Value of cleaned SBS in previous frame;
  nup = 0;     # Num frames with SBS value {up}.
  v_tol = 0.3; 
  v_zero =  0.0;
  v_half = -1.0;
  v_unit = -2.6;
  v_max =  v_zero + v_tol;
  v_min =  v_unit - v_tol;
  force = 1; # If 1, forces cleaned SBS = 0.5 for the SETUP intervals based on frame count.
}

// { 
  nt = nt + 1; # One more frame read.
  v = $1 / 1e5; 
  if ((v < v_min) || (v > v_max)) {
    printf "** BUG %23.16e = %23.16e\n", $1, v > "/dev/stderr";
    exit(1);
  }
  
  # Set cleaned SBS signal {u} from {v}:
  if (v < v_half - 0.2) { u = 1.0; }
  else if (v > v_half + 0.2) { u = 0.0; }
  else { u = 0.5; }
  
  if (force) {
    # Set {u = 0.5} forcefully for specific frames:
    if ((nt <= 60462) || ((nt >= 594314) && (nt <= 792024)) || (nt >= 1325878)) { u = 0.5; } 
  }
    
  if (u != up) { 
    report(up,nt-1,nup)
    up = u;
    nup = 1;
  } else {
    nup = nup + 1;
  }
  printf "%3.1f\n", u
  next
}

END {
  report(up,nt,nup)
}

function report(uval,itlast,n) {
  # Report a segment of uniform {u = uval} consisting of the last {n} frames ending at {itlast}.
  if (uval != -1) { printf "%8d .. %8d : %8d frames with u = %3.2f\n", itlast+1-n, itlast, n, uval > "/dev/stderr"; }
}