Broke out some variables, adjusted for new versions
Fixed a couple syntax typos, works but not tested from scratch