Cleaned up code, added some helper functions