Headers needs to be written before you encode anything or SIGSEGV.. I cleaned it bit and commented.