Major refactor of legacy script

I suggest you make sure this is working before merging.