Added additional logic for handling substitutions