Optimized and fixed the code