Refractoring and added logging