Completed code for dir = 1