Update main.js

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