code optimised and proper error handling