Cleaned up code and added some documentation