[bugfix #417] delete old files that have been replaced by a directory

This also addresses the bug #417, where creating a dir named the same as a file in a previous build creates an error, as does PR #1086. But this code should be more comprehensible than the old one.