Add some helper functions and refactor a little