Medium changes to code.

Changed all background measurements to happen in the first half of the
loop.
Changed background struct to have different detection values depending
on state.
Other streamlining changes to improve speed.