don't leak filedescriptors in case of errors
fixed some edge cases + cleanings
ensure fd is valid before passing it to close()
just an extra check

to avoid calling close() when fd is invalid (-1)
extra checks