Code has been corrected and optimized (2nd try)

fixed merge conflicts !