Optimized with help of da_guru