check $dir early for efficiency