Added logging and some code cleaning