Ditto here. This code is complex. It should have some comments. For instance, why do we sometimes need to subtract 1 from stuff?