Fixing all mentioned issues

Take a look and accept this pull request. Merge it with your repo and try out the code.