Improve dirname detection