infinite loop for some cases - fixed