Big refactoring. Moved most of the complicated stuff to a possible encore part