Slight refactor, plus error checking