code cleaning (almost rewriting)