fixed several off-by-one bugs