improved logic of clip function