Revert "Revert "huge refactoring""

This reverts commit 12cb12d8c485339aaf5f5de11fac109dceee2e33.