Cleaned up magic numbers, and added some error checking.