major code refactoring for more code reuse and smaller code size