copy initial implementation from my hacked-together script