minor refactoring and made it able to run as a script