rewritten completely in BASH