First working version.

Fixed memory overallocation issues.
Small tweaks overall.