Cleaned up, made safe, restructured, and commented code