Might be easier to just debug what you have? Is it live somewhere to see if it throws any errors? The function works fine when called pretty much anywhere... haven't tested it in certain scenarios, but eh... didn't think they would be required anyway.
The way to success is to assume that there are no impossible things. After all, if you think something is impossible, you will not even try to do it.
How to ask smart questions?