In future it is best not to post code of this size. Not only is it difficult to read but it prevents others from actually following and helping with your problem.
Now, what is your aim with this code? Is it going to be a simple function call and you want to display the results in your template? If so the quick way to put the code in is to make it an operator. Read this:
If you need to have further communication where you use POST or GET commands to pass information back and forward you should consider building a module. It isn't too hard and is within the documents.