Refractoring and code cleanup