massive refactor, to be used as module