Lamvak's pull request + improvements

Insert lamvak's pull request with changes from comments