removed extra loops and optimized further