Fixed a major bug and a bunch of off-by-one-errors