Added some code to deal with direction changes.