Fixed off-by-one and index bugs.