Fixed many off-by-one errors and uninitialized variables