Improvements based on Fedir's source code:

https://groups.google.com/forum/?fromgroups#!topic/joomla-dev-cms/s2Wqo7eNKfo