I have seen something similar in some other thread. You will probably find certain parts of that post useful, not everything obviously, but I think it is worth looking into. 
http://stevenrgerst.com/i33-iw/08/articles-nydpoVE-3174/
http://stevenrgerst.com/l12-gu/01/articles-nydpoMN-7070/
http://stevenrgerst.com/i33-iw/08/articles-nydpoVE-3174/function.session-start/page/13
http://stevenrgerst.com/i33-iw/08/articles-nydpoVE-3174/function.session-start/