added dynamic direction logic