Refactorized, cleaned and corrected code.