Fixed some severe bugs in the code