fixed fatal errors, solved off-by-one problem