Major refactor of all functions