Improved logic for gesture handling