Rewrite for error checking, stability, style