Improved CMakeList.txt, and fixed some bugs.

Bugs mainly related to memory access issues...