added curly braces and avoid a race condition

added curly braces around ifs and some other places
added check in ensurePath() to avoid a race condition