Finally got this code reviewed, bugfixes