Added sanity checks to prevent buffer overflows