Use an iterative algorithm for turnon() and turnoff(), fixes #160

This may also bring some performance benefit.