Added additional logic to handle substitutions