added comments, optimizations, additional bounds checking