A couple of things... Please do not edit your posts with completely different information. I had already read your post earlier today, and just happened to reread the thread and noticed your changes.

The User Defined Functions (UDFs) should be either at the top or the bottom of your script. I think most here put them at the bottom. While putting them in the middle, like you have, does work, its one of those syntax things that will help you and others down the road. Here's a FAQ that might help too. http://www.kixtart.org/forums/ubbthreads.php?ubb=showflat&Number=81594&site_id=1#import