Improve finding base directory logic