renamed safelen to end, and fixed some buffer overflow. Added debug