Ported and cleaned up from local repository.