Some improvements to the code
Additional error fixing