Improved encode function (double-quotes get changed to &quot;)