Added check to avoid memory leak: http://stackoverflow.com/a/20762570/956886