[CLEANUP] Code cleanup, error checking

Fixes #1315 once merged.