Big update, mostly function refactoring