Fix leaking filedescriptors. Fix some checks.