added length validation and debug info