Moved the open directory code into a function