fix a bunch of off-by-one bugs and clean up code a bit