Big code refactoring.

All code responsible for optimizations, variable allocation and few
other minor things has been refactored - neatly divided into smaller
pieces and files.
Few optimizations were improved (more or less), but no major changes
except this.