rewritten for posix-shell (dash), added improvements