Initial patch was submitted by kib and additional work was done by Divacky Roman. Tested by: emulation