Code refractoring and trying to get the function working