Small refactoring to make ws handling a little more robust
Moved profiling functions to their own module. Started refactoring.