Major refactoring for flexibility and extensibility