It's probably possible to improve things here, but it's likely best done as a separate open source project.