Working version. But it does not terminate