Moved sampling to the back end
Improved code