Fixed file descriptor leak and added some stricter checks for input data.