Update main.js

Updated plug structure to fix scope issues. Some minor refactoring as well to increase performance.