Implement Vadym's changes with a few fixes etc.