Redirecting to SEF links when SEF is enabled

When creating redirects, usually non-SEF links are saved as they are universal (alias can be changed later; when SEF is switched off links are still valid) and easier to find (for instance by using JCE Editor to find links to articles). The problem with that is that on SEF site, non-SEF links are explored and displayed by search engines.
Here is a solution, how to detect non-SEF links and convert them to SEF ones.