// Detect It Easy: detection rule file format
// Author: Jason Hood <jadoxa@yahoo.com.au>

init("image", "JPEG");

function detect(bShowType, bShowVersion, bShowOptions) {
    if (Binary.getSize() >= 22) {
        if (Binary.compare("FFD8FFE0....'JFIF'00")) {
            bDetected = true;
            sVersion = Binary.readByte(11) + "."
            if (Binary.readByte(12) < 10) {
                sVersion = sVersion + "0"
            }
            sVersion = sVersion + Binary.readByte(12)
                // Search for a Start Of Frame to get dimensions.
            var nOffset = 2;
            while (nOffset < Binary.getSize()) {
                var wTag = Binary.readBEWord(nOffset);
                if (wTag >= 0xFFC0 && wTag <= 0xFFC3) {
                    sOptions = Binary.readBEWord(nOffset + 7) + "x" +
                        Binary.readBEWord(nOffset + 5);
                    switch (Binary.readByte(nOffset + 9)) {
                        case 1:
                            sOptions = sOptions.append("grey");
                            break;
                        case 3:
                            sOptions = sOptions.append("YCbCr");
                            break;
                        case 4:
                            sOptions = sOptions.append("CMYK");
                            break;
                    }
                    break;
                }
                nOffset += 2 + Binary.readBEWord(nOffset + 2);
            }
        } else if (Binary.compare("FFD8FFE1....'Exif'00")) {
            bDetected = true;
            sVersion = Binary.readByte(11) + "."
            if (Binary.readByte(12) < 10) {
                sVersion = sVersion + "0"
            }
            sVersion = sVersion + Binary.readByte(12)
            sOptions = "EXIF";
        } else if (Binary.compare("FFD8FFDB")) {
            bDetected = true;
            sOptions = "OLD";
        }
    }

    return result(bShowType, bShowVersion, bShowOptions);
}