Refactored substitution logic. Moved it to a separate class