Added safe type casting and fixed a rather serious array reading issue.