I'm pretty sure that that code is mostly copy/pasted from somewhere. 
So please:
- say from where, and which version (or branch, date) so that in the future, we will be able to know what changed in the original version (and so, we can follow security problem, for ex)
- clearly say what are the modification and what are the intents of each of them (so that comparison with the original is possible, and comparison with future version will be, too)