bugfixes, refactoring, ported bash func