Error Checking

Added error checking, ensuring memory can not be read outside of the
allocated array's.
Added debug messaging for above.
Comments where required.