The great refactoring.

I am unable to comment on every thing that was changed. There are just too many changes!
If you have any questions about particular parts - feel free to ask.
Basically it's all about correct quoting, moving copy-pasted parts to functions, consistent code style, better code flow and of course bug fixes! I've tried not to change functionality, focusing just on the source code. Now it is much cleaner and shorter, should be easier to understand as well!