Refactor main script for easier external invocation.