// DIE's signature file
// Authors: Jason Hood <jadoxa@yahoo.com.au>, Kae <TG@kaens>

init("image", "Windows Icon");

includeScript("CurIcoBPP");

function detect(bShowType, bShowVersion, bShowOptions) {
    if (Binary.compare("00000100")) {
        // Find the biggest, assuming square.
        var nCount = Binary.read_uint16(4, _LE);
        var nWidth = 0,
            nHeight = 0,
            nBPP = 0,
            sz = 6 + nCount * 16;
        if (sz === 6 || sz > File.getSize()) return false;
        for (var i = 0; i < nCount; i++) {
            if (Binary.read_uint8(9 + i * 16)) return false;
            var w = Binary.read_uint8(6 + i * 16),
                h;
            var b = getCurIcoBPP(6 + i * 16);
            sz_ = Binary.read_uint32(14 + i * 16, _LE);
            if (!sz_ || sz_ > File.getSize() - 22)
                return false;
            sz += sz_;
            if (w === 0) {
                var nOffset = Binary.read_uint32(18 + i * 16, _LE);
                if (Binary.compare("89'PNG\r\n'1A0A........'IHDR'", nOffset)) {
                    w = Binary.read_int32(nOffset + 16, _BE);
                    h = Binary.read_int32(nOffset + 20, _BE);
                } else if (Binary.compare("28000000", nOffset)) {
                    //TODO find at least one .ico that has a BMP > 256x256, and check this
                    w = abs(Binary.read_int32(nOffset + 4, _BE));
                    h = abs(Binary.read_int32(nOffset + 8, _BE)); //abs for top-down and otherwise weird BMPs
                } else return false //unknown format after all
            } else {
                _log("bmp, ht @ " + Hex(i * 16 + 7));
                h = Binary.read_uint8(7 + i * 16);
            }
            if (w > nWidth) {
                nWidth = w;
                nHeight = h;
                nBPP = b;
            } else if (w == nWidth)
                if (b > nBPP)
                    nBPP = b;
        }
        if (!w || !h) return false;
        sOptions = sOptions.append(nWidth + "x" + nHeight, nBPP + "bpp");
        if (nCount > 1)
            sOptions = sOptions.append(nCount + " icons");
        sOptions = sOptions.append("sz:" + sz)
        bDetected = true;
    }

    return result(bShowType, bShowVersion, bShowOptions);
}