Added some checks and optimized some code