added protection to avoid overflowing arrays