some optimisation and refactoring done.