Getting stuck in infinite loop