Added hysteresis code (Neil Martin version fixed and simplified)