Further code cleaning and improvement