Fixed possible infinite loop
Better testing coverage