More refractoring and minor fixes