Fixed boundary checking and switch most vars to constants