Huge cleanup and refactorization