Correction, simplifying and optimizing of the code