WIP: convert script to library
WIP: more work