-    my_src_ptr src = (my_src_ptr) cinfo->src;
-    
-    src->pub.next_input_byte += (size_t) num_bytes;
-    src->pub.bytes_in_buffer -= (size_t) num_bytes;
+    if (num_bytes > 0)
+    {
+        wx_src_ptr src = (wx_src_ptr) cinfo->src;
+
+        while (num_bytes > (long)src->pub.bytes_in_buffer)
+        {
+            num_bytes -= (long) src->pub.bytes_in_buffer;
+            src->pub.fill_input_buffer(cinfo);
+        }
+        src->pub.next_input_byte += (size_t) num_bytes;
+        src->pub.bytes_in_buffer -= (size_t) num_bytes;
+    }
+}
+
+CPP_METHODDEF(void) wx_term_source ( j_decompress_ptr cinfo )
+{
+    wx_src_ptr src = (wx_src_ptr) cinfo->src;
+
+    if (src->pub.bytes_in_buffer > 0)
+        src->stream->SeekI(-(long)src->pub.bytes_in_buffer, wxFromCurrent);
+    delete[] src->buffer;
+}
+
+
+// JPEG error manager:
+
+struct wx_error_mgr : public jpeg_error_mgr
+{
+  jmp_buf setjmp_buffer;    /* for return to caller */
+};
+
+/*
+ * Here's the routine that will replace the standard error_exit method:
+ */
+
+CPP_METHODDEF(void) wx_error_exit (j_common_ptr cinfo)
+{
+  /* cinfo->err really points to a wx_error_mgr struct, so coerce pointer */
+  wx_error_mgr * const jerr = (wx_error_mgr *) cinfo->err;
+
+  /* Always display the message. */
+  /* We could postpone this until after returning, if we chose. */
+  (*cinfo->err->output_message) (cinfo);
+
+  /* Return control to the setjmp point */
+  longjmp(jerr->setjmp_buffer, 1);