edited for readability
temporarily removed periodic good distance and fixed hysteresis bug in distance code