Hopefully fixed the errors with some bounds checks.