One of the best ways to debug a program is to first create a small program with only those parts that seem to create trouble for you. This is called SSCCE (click on the link to understand more).
My suggestion would be to create such a program and try narrowing down the problem. If you are still not able to find it out, it will always be easier to post that code - which volunteers here can simply take and run it directly. It will lead to faster resolutions.