Patched in files from hs-scripts.
Refactored into smaller functions.