Refactored main engine and gateway