Also, rationalized this to generally make it safer and more readable. It could use a more modern approach, at some point...