Corrected syntax errors + casting problems + tested for production

Code have been tested and everything should work fine. Of course additional tests and scrutiny is welcomed!