refactor directory-handling code