refactored it to work in a self invoking function