fixed some errors and more refactoring

MERGE MEEE