improved logic and performance