 /**
  Creates an image out of given thumbnail image data packet (for format, see the start of this source file).
  
+ This method could be somewhat CPU intense so you might consider running it in a non-UI thread.
+ 
  - parameter data: thumbnail packet data
  - parameter maxSize: Max dimensions to scale the image to, retaining aspect ratio.
+ - parameter imageScale: value for result image's UIImage.scale. Specify 0.0 to match the scale of the device's screen.
  - returns: Scaled-up and blurred version of the thumbnail, if successful
 */
-public func jpegThumbnailDataToImage(data data: NSData, maxSize: CGSize) -> UIImage? {
+public func jpegThumbnailDataToImage(data data: NSData, maxSize: CGSize, imageScale: CGFloat = 0.0) -> UIImage? {
     log.debug("** creating image from thumbnail **")
     
     let ptr = UnsafeMutablePointer<UInt8>(data.bytes)
-    if ptr[0] != headerPacketVersion {
+    if ptr[0] != thumbHeaderPacketVersion {
         log.error("Version mismatch!")
         return nil
     }
     
-    let thumbWidth = ptr[1]
-    let thumbHeight = ptr[2]
-    let jpegDataPtr = UnsafePointer<UInt8>(data.bytes)
+    if ptr[1] != thumbHeaderDataTypeIOSJPEG {
+        log.error("Invalid data type value in packet: \(ptr[1])")
+        return nil
+    }
+    
+    let thumbWidth = ptr[2]
+    let thumbHeight = ptr[3]
     log.debug("Read thumb size from packet: \(thumbWidth) x \(thumbHeight)")
     
     // Construct a whole JPEG from a predefined header block, the jpeg data and EOI marker (2 bytes)

//  Offset | Length (bytes) | Content
// --------+----------------+------------------------------------------------
//    0    |        1       | Version of dataformat; currently, 1
//    1    |        1       | Width of the thumbnail
//    2    |        1       | Height of the thumbnail
//    3    |        n       | JPEG image data without header (contents of SOS marker)

// JPEG header constants
private let jpegMarkerByte: UInt8 = 0xFF

        log.error("Failed to allocate memory for JPEG data!")
        return nil
    }

    let eoiMarker = [jpegMarkerByte, jpegEOIMarker]
    jpegData.appendData(jpegHeaderData)
    jpegData.appendBytes(UnsafePointer<UInt8>(data.bytes).advancedBy(thumbHeaderLength), length: (data.length - thumbHeaderLength))
    jpegData.appendBytes(UnsafePointer<Void>(eoiMarker), length: eoiMarker.count)
    log.debug("jpegData.length = \(jpegData.length)")
    
    // Patch in the thumbnail size into the copied header to get an result image of the correct size
