Cleaned up code, added comments, added logging