fix for trunk-8483 and trunk-4322

Hi Darius,

This is my initial commit for the above tickets. Can you please review it and let me know if it needs more fixes.

Thanks!