fixed the errors and modularised and optimised