Couple of optimization tricks
fixed perpetual loop