Fixes integer overflow and out of array accesses. Found-by: Mateusz j00ru Jurczyk and Gynvael Coldwind