How to Debug?

Start by getting exact input, then try reproducing the problem in your test environment with as little data as possible. Now one of the first things you will notice is that echo generally does not work.