Untested, but cleaned up code and renamed functions