Bug789 v1.3 part1

This is a rebased a work on #789 rebased on current master. I've fixed Cuda build which was not ok in previous PR.