re-arranged functions into a new module and fixed several bugs