/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qkbd_qws.h" #include "qkbd_qws_p.h" #ifndef QT_NO_QWS_KEYBOARD #include #include #include #ifdef Q_WS_QWS #include "qwindowsystem_qws.h" #include "qscreen_qws.h" #endif #ifdef Q_WS_QPA #include #include #endif #include "qtimer.h" #include //#define QT_DEBUG_KEYMAP QT_BEGIN_NAMESPACE class QWSKbPrivate : public QObject { Q_OBJECT public: QWSKbPrivate(QWSKeyboardHandler *h, const QString &device) : m_handler(h), m_modifiers(0), m_composing(0), m_dead_unicode(0xffff), m_no_zap(false), m_do_compose(false), m_keymap(0), m_keymap_size(0), m_keycompose(0), m_keycompose_size(0) { m_ar_timer = new QTimer(this); m_ar_timer->setSingleShot(true); connect(m_ar_timer, SIGNAL(timeout()), SLOT(autoRepeat())); m_ar_delay = 400; m_ar_period = 80; memset(m_locks, 0, sizeof(m_locks)); QString keymap; QStringList args = device.split(QLatin1Char(':')); foreach (const QString &arg, args) { if (arg.startsWith(QLatin1String("keymap="))) keymap = arg.mid(7); else if (arg == QLatin1String("disable-zap")) m_no_zap = true; else if (arg == QLatin1String("enable-compose")) m_do_compose = true; else if (arg.startsWith(QLatin1String("repeat-delay="))) m_ar_delay = arg.mid(13).toInt(); else if (arg.startsWith(QLatin1String("repeat-rate="))) m_ar_period = arg.mid(12).toInt(); } if (keymap.isEmpty() || !loadKeymap(keymap)) unloadKeymap(); } ~QWSKbPrivate() { unloadKeymap(); } void beginAutoRepeat(int uni, int code, Qt::KeyboardModifiers mod) { m_ar_unicode = uni; m_ar_keycode = code; m_ar_modifier = mod; m_ar_timer->start(m_ar_delay); } void endAutoRepeat() { m_ar_timer->stop(); } static Qt::KeyboardModifiers toQtModifiers(quint8 mod) { Qt::KeyboardModifiers qtmod = Qt::NoModifier; if (mod & (QWSKeyboard::ModShift | QWSKeyboard::ModShiftL | QWSKeyboard::ModShiftR)) qtmod |= Qt::ShiftModifier; if (mod & (QWSKeyboard::ModControl | QWSKeyboard::ModCtrlL | QWSKeyboard::ModCtrlR)) qtmod |= Qt::ControlModifier; if (mod & QWSKeyboard::ModAlt) qtmod |= Qt::AltModifier; return qtmod; } void unloadKeymap(); bool loadKeymap(const QString &file); private slots: void autoRepeat() { m_handler->processKeyEvent(m_ar_unicode, m_ar_keycode, m_ar_modifier, false, true); m_handler->processKeyEvent(m_ar_unicode, m_ar_keycode, m_ar_modifier, true, true); m_ar_timer->start(m_ar_period); } private: QWSKeyboardHandler *m_handler; // auto repeat simulation int m_ar_unicode; int m_ar_keycode; Qt::KeyboardModifiers m_ar_modifier; int m_ar_delay; int m_ar_period; QTimer *m_ar_timer; // keymap handling quint8 m_modifiers; quint8 m_locks[3]; int m_composing; quint16 m_dead_unicode; bool m_no_zap; bool m_do_compose; const QWSKeyboard::Mapping *m_keymap; int m_keymap_size; const QWSKeyboard::Composing *m_keycompose; int m_keycompose_size; static const QWSKeyboard::Mapping s_keymap_default[]; static const QWSKeyboard::Composing s_keycompose_default[]; friend class QWSKeyboardHandler; }; // simple builtin US keymap #include "qkbd_defaultmap_qws_p.h" // the unloadKeymap() function needs to be AFTER the defaultmap include, // since the sizeof(s_keymap_default) wouldn't work otherwise. void QWSKbPrivate::unloadKeymap() { if (m_keymap && m_keymap != s_keymap_default) delete [] m_keymap; if (m_keycompose && m_keycompose != s_keycompose_default) delete [] m_keycompose; m_keymap = s_keymap_default; m_keymap_size = sizeof(s_keymap_default) / sizeof(s_keymap_default[0]); m_keycompose = s_keycompose_default; m_keycompose_size = sizeof(s_keycompose_default) / sizeof(s_keycompose_default[0]); // reset state, so we could switch keymaps at runtime m_modifiers = 0; memset(m_locks, 0, sizeof(m_locks)); m_composing = 0; m_dead_unicode = 0xffff; } bool QWSKbPrivate::loadKeymap(const QString &file) { QFile f(file); if (!f.open(QIODevice::ReadOnly)) { qWarning("Could not open keymap file '%s'", qPrintable(file)); return false; } // .qmap files have a very simple structure: // quint32 magic (QWSKeyboard::FileMagic) // quint32 version (1) // quint32 keymap_size (# of struct QWSKeyboard::Mappings) // quint32 keycompose_size (# of struct QWSKeyboard::Composings) // all QWSKeyboard::Mappings via QDataStream::operator(<<|>>) // all QWSKeyboard::Composings via QDataStream::operator(<<|>>) quint32 qmap_magic, qmap_version, qmap_keymap_size, qmap_keycompose_size; QDataStream ds(&f); ds >> qmap_magic >> qmap_version >> qmap_keymap_size >> qmap_keycompose_size; if (ds.status() != QDataStream::Ok || qmap_magic != QWSKeyboard::FileMagic || qmap_version != 1 || qmap_keymap_size == 0) { qWarning("'%s' is not a valid .qmap keymap file.", qPrintable(file)); return false; } QWSKeyboard::Mapping *qmap_keymap = new QWSKeyboard::Mapping[qmap_keymap_size]; QWSKeyboard::Composing *qmap_keycompose = qmap_keycompose_size ? new QWSKeyboard::Composing[qmap_keycompose_size] : 0; for (quint32 i = 0; i < qmap_keymap_size; ++i) ds >> qmap_keymap[i]; for (quint32 i = 0; i < qmap_keycompose_size; ++i) ds >> qmap_keycompose[i]; if (ds.status() != QDataStream::Ok) { delete [] qmap_keymap; delete [] qmap_keycompose; qWarning("Keymap file '%s' can not be loaded.", qPrintable(file)); return false; } // unload currently active and clear state unloadKeymap(); m_keymap = qmap_keymap; m_keymap_size = qmap_keymap_size; m_keycompose = qmap_keycompose; m_keycompose_size = qmap_keycompose_size; m_do_compose = true; return true; } /*! \class QWSKeyboardHandler \ingroup qws \brief The QWSKeyboardHandler class is a base class for keyboard drivers in Qt for Embedded Linux. Note that this class is only available in \l{Qt for Embedded Linux}. \l{Qt for Embedded Linux} provides ready-made drivers for several keyboard protocols, see the \l{Qt for Embedded Linux Character Input}{character input} documentation for details. Custom keyboard drivers can be implemented by subclassing the QWSKeyboardHandler class and creating a keyboard driver plugin (derived from QKbdDriverPlugin). The default implementation of the QKbdDriverFactory class will automatically detect the plugin, and load the driver into the server application at run-time using Qt's \l{How to Create Qt Plugins}{plugin system}. The keyboard driver receives keyboard events from the system device and encapsulates each event with an instance of the QWSEvent class which it then passes to the server application (the server is responsible for propagating the event to the appropriate client). To receive keyboard events, a QWSKeyboardHandler object will usually create a QSocketNotifier object for the given device. The QSocketNotifier class provides support for monitoring activity on a file descriptor. When the socket notifier receives data, it will call the keyboard driver's processKeyEvent() function to send the event to the \l{Qt for Embedded Linux} server application for relaying to clients. QWSKeyboardHandler also provides functions to control auto-repetion of key sequences, beginAutoRepeat() and endAutoRepeat(), and the transformDirKey() function enabling transformation of arrow keys according to the display orientation. \sa QKbdDriverPlugin, QKbdDriverFactory, {Qt for Embedded Linux Character Input} */ /*! Constructs a keyboard driver. The \a device argument is passed by the QWS_KEYBOARD environment variable. Call the QWSServer::setKeyboardHandler() function to make the newly created keyboard driver, the primary driver. Note that the primary driver is controlled by the system, i.e., the system will delete it upon exit. */ QWSKeyboardHandler::QWSKeyboardHandler(const QString &device) { d = new QWSKbPrivate(this, device); } /*! \overload */ QWSKeyboardHandler::QWSKeyboardHandler() { d = new QWSKbPrivate(this, QString()); } /*! Destroys this keyboard driver. Do not call this function if this driver is the primary keyboard handler, i.e., if QWSServer::setKeyboardHandler() function has been called passing this driver as argument. The primary keyboard driver is deleted by the system. */ QWSKeyboardHandler::~QWSKeyboardHandler() { delete d; } /*! Sends a key event to the \l{Qt for Embedded Linux} server application. The key event is identified by its \a unicode value and the \a keycode, \a modifiers, \a isPress and \a autoRepeat parameters. The \a keycode parameter is the Qt keycode value as defined by the Qt::Key enum. The \a modifiers is an OR combination of Qt::KeyboardModifier values, indicating whether \gui Shift/Alt/Ctrl keys are pressed. The \a isPress parameter is true if the event is a key press event and \a autoRepeat is true if the event is caused by an auto-repeat mechanism and not an actual key press. Note that this function does not handle key mapping. Please use processKeycode() if you need that functionality. \sa processKeycode(), beginAutoRepeat(), endAutoRepeat(), transformDirKey() */ void QWSKeyboardHandler::processKeyEvent(int unicode, int keycode, Qt::KeyboardModifiers modifiers, bool isPress, bool autoRepeat) { #if defined(Q_WS_QWS) qwsServer->processKeyEvent(unicode, keycode, modifiers, isPress, autoRepeat); #elif defined(Q_WS_QPA) QEvent::Type type = isPress ? QEvent::KeyPress : QEvent::KeyRelease; QString str; if (unicode != 0xffff) str = QString(unicode); QWindowSystemInterface::handleKeyEvent(0, type, keycode, modifiers, str); #endif } /*! \fn int QWSKeyboardHandler::transformDirKey(int keycode) Transforms the arrow key specified by the given \a keycode, to the orientation of the display and returns the transformed keycode. The \a keycode is a Qt::Key value. The values identifying arrow keys are: \list \o Qt::Key_Left \o Qt::Key_Up \o Qt::Key_Right \o Qt::Key_Down \endlist \sa processKeyEvent() */ int QWSKeyboardHandler::transformDirKey(int key) { #ifdef Q_WS_QWS static int dir_keyrot = -1; if (dir_keyrot < 0) { // get the rotation switch (qgetenv("QWS_CURSOR_ROTATION").toInt()) { case 90: dir_keyrot = 1; break; case 180: dir_keyrot = 2; break; case 270: dir_keyrot = 3; break; default: dir_keyrot = 0; break; } } int xf = qt_screen->transformOrientation() + dir_keyrot; return (key-Qt::Key_Left+xf)%4+Qt::Key_Left; #else return 0; #endif } /*! \fn void QWSKeyboardHandler::beginAutoRepeat(int unicode, int keycode, Qt::KeyboardModifiers modifier) Begins auto-repeating the specified key press; after a short delay the key press is sent periodically until the endAutoRepeat() function is called. The key press is specified by its \a unicode, \a keycode and \a modifier state. \sa endAutoRepeat(), processKeyEvent() */ void QWSKeyboardHandler::beginAutoRepeat(int uni, int code, Qt::KeyboardModifiers mod) { d->beginAutoRepeat(uni, code, mod); } /*! Stops auto-repeating a key press. \sa beginAutoRepeat(), processKeyEvent() */ void QWSKeyboardHandler::endAutoRepeat() { d->endAutoRepeat(); } /*! \enum QWSKeyboardHandler::KeycodeAction This enum describes the various special actions that actual QWSKeyboardHandler implementations have to take care of. \value None No further action required. \value CapsLockOn Set the state of the Caps lock LED to on. \value CapsLockOff Set the state of the Caps lock LED to off. \value NumLockOn Set the state of the Num lock LED to on. \value NumLockOff Set the state of the Num lock LED to off. \value ScrollLockOn Set the state of the Scroll lock LED to on. \value ScrollLockOff Set the state of the Scroll lock LED to off. \value PreviousConsole Switch to the previous virtual console (by default Ctrl+Alt+Left on Linux). \value NextConsole Switch to the next virtual console (by default Ctrl+Alt+Right on Linux). \value SwitchConsoleFirst Switch to the first virtual console (0). \value SwitchConsoleLast Switch to the last virtual console (255). \value SwitchConsoleMask If the KeyAction value is between SwitchConsoleFirst and SwitchConsoleLast, you can use this mask to get the specific virtual console number to switch to. \value Reboot Reboot the machine - this is ignored in both the TTY and LinuxInput handlers though (by default Ctrl+Alt+Del on Linux). \sa processKeycode() */ /*! \fn QWSKeyboardHandler::KeycodeAction QWSKeyboardHandler::processKeycode(quint16 keycode, bool isPress, bool autoRepeat) \since 4.6 Maps \a keycode according to a keymap and sends that key event to the \l{Qt for Embedded Linux} server application. Please see the \l{Qt for Embedded Linux Character Input} and the \l {kmap2qmap} documentations for a description on how to create and use keymap files. The key event is identified by its \a keycode value and the \a isPress and \a autoRepeat parameters. The \a keycode parameter is \bold NOT the Qt keycode value as defined by the Qt::Key enum. This functions expects a standard Linux 16 bit kernel keycode as it is used in the Linux Input Event sub-system. This \a keycode is transformed to a Qt::Key code by using either a compiled-in US keyboard layout or by dynamically loading a keymap at startup which can be specified via the QWS_KEYBOARD environment variable. The \a isPress parameter is true if the event is a key press event and \a autoRepeat is true if the event is caused by an auto-repeat mechanism and not an actual key press. The return value indicates if the actual QWSKeyboardHandler implementation needs to take care of a special action, like console switching or LED handling. If standard Linux console keymaps are used, \a keycode must be one of the standardized values defined in \c /usr/include/linux/input.h \sa processKeyEvent(), KeycodeAction */ QWSKeyboardHandler::KeycodeAction QWSKeyboardHandler::processKeycode(quint16 keycode, bool pressed, bool autorepeat) { KeycodeAction result = None; bool first_press = pressed && !autorepeat; const QWSKeyboard::Mapping *map_plain = 0; const QWSKeyboard::Mapping *map_withmod = 0; // get a specific and plain mapping for the keycode and the current modifiers for (int i = 0; i < d->m_keymap_size && !(map_plain && map_withmod); ++i) { const QWSKeyboard::Mapping *m = d->m_keymap + i; if (m->keycode == keycode) { if (m->modifiers == 0) map_plain = m; quint8 testmods = d->m_modifiers; if (d->m_locks[0] /*CapsLock*/ && (m->flags & QWSKeyboard::IsLetter)) testmods ^= QWSKeyboard::ModShift; if (m->modifiers == testmods) map_withmod = m; } } #ifdef QT_DEBUG_KEYMAP qWarning("Processing key event: keycode=%3d, modifiers=%02x pressed=%d, autorepeat=%d | plain=%d, withmod=%d, size=%d", \ keycode, d->m_modifiers, pressed ? 1 : 0, autorepeat ? 1 : 0, \ map_plain ? map_plain - d->m_keymap : -1, \ map_withmod ? map_withmod - d->m_keymap : -1, \ d->m_keymap_size); #endif const QWSKeyboard::Mapping *it = map_withmod ? map_withmod : map_plain; if (!it) { #ifdef QT_DEBUG_KEYMAP // we couldn't even find a plain mapping qWarning("Could not find a suitable mapping for keycode: %3d, modifiers: %02x", keycode, d->m_modifiers); #endif return result; } bool skip = false; quint16 unicode = it->unicode; quint32 qtcode = it->qtcode; if ((it->flags & QWSKeyboard::IsModifier) && it->special) { // this is a modifier, i.e. Shift, Alt, ... if (pressed) d->m_modifiers |= quint8(it->special); else d->m_modifiers &= ~quint8(it->special); } else if (qtcode >= Qt::Key_CapsLock && qtcode <= Qt::Key_ScrollLock) { // (Caps|Num|Scroll)Lock if (first_press) { quint8 &lock = d->m_locks[qtcode - Qt::Key_CapsLock]; lock ^= 1; switch (qtcode) { case Qt::Key_CapsLock : result = lock ? CapsLockOn : CapsLockOff; break; case Qt::Key_NumLock : result = lock ? NumLockOn : NumLockOff; break; case Qt::Key_ScrollLock: result = lock ? ScrollLockOn : ScrollLockOff; break; default : break; } } } else if ((it->flags & QWSKeyboard::IsSystem) && it->special && first_press) { switch (it->special) { case QWSKeyboard::SystemReboot: result = Reboot; break; case QWSKeyboard::SystemZap: if (!d->m_no_zap) qApp->quit(); break; case QWSKeyboard::SystemConsolePrevious: result = PreviousConsole; break; case QWSKeyboard::SystemConsoleNext: result = NextConsole; break; default: if (it->special >= QWSKeyboard::SystemConsoleFirst && it->special <= QWSKeyboard::SystemConsoleLast) { result = KeycodeAction(SwitchConsoleFirst + ((it->special & QWSKeyboard::SystemConsoleMask) & SwitchConsoleMask)); } break; } skip = true; // no need to tell QWS about it } else if ((qtcode == Qt::Key_Multi_key) && d->m_do_compose) { // the Compose key was pressed if (first_press) d->m_composing = 2; skip = true; } else if ((it->flags & QWSKeyboard::IsDead) && d->m_do_compose) { // a Dead key was pressed if (first_press && d->m_composing == 1 && d->m_dead_unicode == unicode) { // twice d->m_composing = 0; qtcode = Qt::Key_unknown; // otherwise it would be Qt::Key_Dead... } else if (first_press && unicode != 0xffff) { d->m_dead_unicode = unicode; d->m_composing = 1; skip = true; } else { skip = true; } } if (!skip) { // a normal key was pressed const int modmask = Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier | Qt::KeypadModifier; // we couldn't find a specific mapping for the current modifiers, // or that mapping didn't have special modifiers: // so just report the plain mapping with additional modifiers. if ((it == map_plain && it != map_withmod) || (map_withmod && !(map_withmod->qtcode & modmask))) { qtcode |= QWSKbPrivate::toQtModifiers(d->m_modifiers); } if (d->m_composing == 2 && first_press && !(it->flags & QWSKeyboard::IsModifier)) { // the last key press was the Compose key if (unicode != 0xffff) { int idx = 0; // check if this code is in the compose table at all for ( ; idx < d->m_keycompose_size; ++idx) { if (d->m_keycompose[idx].first == unicode) break; } if (idx < d->m_keycompose_size) { // found it -> simulate a Dead key press d->m_dead_unicode = unicode; unicode = 0xffff; d->m_composing = 1; skip = true; } else { d->m_composing = 0; } } else { d->m_composing = 0; } } else if (d->m_composing == 1 && first_press && !(it->flags & QWSKeyboard::IsModifier)) { // the last key press was a Dead key bool valid = false; if (unicode != 0xffff) { int idx = 0; // check if this code is in the compose table at all for ( ; idx < d->m_keycompose_size; ++idx) { if (d->m_keycompose[idx].first == d->m_dead_unicode && d->m_keycompose[idx].second == unicode) break; } if (idx < d->m_keycompose_size) { quint16 composed = d->m_keycompose[idx].result; if (composed != 0xffff) { unicode = composed; qtcode = Qt::Key_unknown; valid = true; } } } if (!valid) { unicode = d->m_dead_unicode; qtcode = Qt::Key_unknown; } d->m_composing = 0; } if (!skip) { #ifdef QT_DEBUG_KEYMAP qWarning("Processing: uni=%04x, qt=%08x, qtmod=%08x", unicode, qtcode & ~modmask, (qtcode & modmask)); #endif // send the result to the QWS server processKeyEvent(unicode, qtcode & ~modmask, Qt::KeyboardModifiers(qtcode & modmask), pressed, autorepeat); } } return result; } QT_END_NAMESPACE #include "qkbd_qws.moc" #endif // QT_NO_QWS_KEYBOARD id='n94' href='#n94'>94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485
/*
 * tkImgPNG.c --
 *
 *	A Tk photo image file handler for PNG files.
 *
 * Copyright (c) 2006-2008 Muonics, Inc.
 * Copyright (c) 2008 Donal K. Fellows
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkInt.h"

#define	PNG_INT32(a,b,c,d)	\
	(((long)(a) << 24) | ((long)(b) << 16) | ((long)(c) << 8) | (long)(d))
#define	PNG_BLOCK_SZ	1024		/* Process up to 1k at a time. */
#define PNG_MIN(a, b) (((a) < (b)) ? (a) : (b))

/*
 * Every PNG image starts with the following 8-byte signature.
 */

#define PNG_SIG_SZ	8
static const unsigned char pngSignature[] = {
    137, 80, 78, 71, 13, 10, 26, 10
};

static const int startLine[8] = {
    0, 0, 0, 4, 0, 2, 0, 1
};

/*
 * Chunk type flags.
 */

#define PNG_CF_ANCILLARY 0x10000000L	/* Non-critical chunk (can ignore). */
#define PNG_CF_PRIVATE   0x00100000L	/* Application-specific chunk. */
#define PNG_CF_RESERVED  0x00001000L	/* Not used. */
#define PNG_CF_COPYSAFE  0x00000010L	/* Opaque data safe for copying. */

/*
 * Chunk types, not all of which have support implemented. Note that there are
 * others in the official extension set which we will never support (as they
 * are officially deprecated).
 */

#define CHUNK_IDAT	PNG_INT32('I','D','A','T')	/* Pixel data. */
#define CHUNK_IEND	PNG_INT32('I','E','N','D')	/* End of Image. */
#define CHUNK_IHDR	PNG_INT32('I','H','D','R')	/* Header. */
#define CHUNK_PLTE	PNG_INT32('P','L','T','E')	/* Palette. */

#define CHUNK_bKGD	PNG_INT32('b','K','G','D')	/* Background Color */
#define CHUNK_cHRM	PNG_INT32('c','H','R','M')	/* Chroma values. */
#define CHUNK_gAMA	PNG_INT32('g','A','M','A')	/* Gamma. */
#define CHUNK_hIST	PNG_INT32('h','I','S','T')	/* Histogram. */
#define CHUNK_iCCP	PNG_INT32('i','C','C','P')	/* Color profile. */
#define CHUNK_iTXt	PNG_INT32('i','T','X','t')	/* Internationalized
							 * text (comments,
							 * etc.) */
#define CHUNK_oFFs	PNG_INT32('o','F','F','s')	/* Image offset. */
#define CHUNK_pCAL	PNG_INT32('p','C','A','L')	/* Pixel calibration
							 * data. */
#define CHUNK_pHYs	PNG_INT32('p','H','Y','s')	/* Physical pixel
							 * dimensions. */
#define CHUNK_sBIT	PNG_INT32('s','B','I','T')	/* Significant bits */
#define CHUNK_sCAL	PNG_INT32('s','C','A','L')	/* Physical scale. */
#define CHUNK_sPLT	PNG_INT32('s','P','L','T')	/* Suggested
							 * palette. */
#define CHUNK_sRGB	PNG_INT32('s','R','G','B')	/* Standard RGB space
							 * declaration. */
#define CHUNK_tEXt	PNG_INT32('t','E','X','t')	/* Plain Latin-1
							 * text. */
#define CHUNK_tIME	PNG_INT32('t','I','M','E')	/* Time stamp. */
#define CHUNK_tRNS	PNG_INT32('t','R','N','S')	/* Transparency. */
#define CHUNK_zTXt	PNG_INT32('z','T','X','t')	/* Compressed Latin-1
							 * text. */

/*
 * Color flags.
 */

#define PNG_COLOR_INDEXED	1
#define PNG_COLOR_USED		2
#define PNG_COLOR_ALPHA		4

/*
 * Actual color types.
 */

#define PNG_COLOR_GRAY		0
#define PNG_COLOR_RGB		(PNG_COLOR_USED)
#define PNG_COLOR_PLTE		(PNG_COLOR_USED | PNG_COLOR_INDEXED)
#define PNG_COLOR_GRAYALPHA	(PNG_COLOR_GRAY | PNG_COLOR_ALPHA)
#define PNG_COLOR_RGBA		(PNG_COLOR_USED | PNG_COLOR_ALPHA)

/*
 * Compression Methods.
 */

#define PNG_COMPRESS_DEFLATE	0

/*
 * Filter Methods.
 */

#define PNG_FILTMETH_STANDARD	0

/*
 * Interlacing Methods.
 */

#define	PNG_INTERLACE_NONE	0
#define PNG_INTERLACE_ADAM7	1

/*
 * State information, used to store everything about the PNG image being
 * currently parsed or created.
 */

typedef struct {
    /*
     * PNG data source/destination channel/object/byte array.
     */

    Tcl_Channel channel;	/* Channel for from-file reads. */
    Tcl_Obj *objDataPtr;
    unsigned char *strDataBuf;	/* Raw source data for from-string reads. */
    int strDataLen;		/* Length of source data. */
    unsigned char *base64Data;	/* base64 encoded string data. */
    unsigned char base64Bits;	/* Remaining bits from last base64 read. */
    unsigned char base64State;	/* Current state of base64 decoder. */
    double alpha;		/* Alpha from -format option. */

    /*
     * Image header information.
     */

    unsigned char bitDepth;	/* Number of bits per pixel. */
    unsigned char colorType;	/* Grayscale, TrueColor, etc. */
    unsigned char compression;	/* Compression Mode (always zlib). */
    unsigned char filter;	/* Filter mode (0 - 3). */
    unsigned char interlace;	/* Type of interlacing (if any). */
    unsigned char numChannels;	/* Number of channels per pixel. */
    unsigned char bytesPerPixel;/* Bytes per pixel in scan line. */
    int bitScale;		/* Scale factor for RGB/Gray depths < 8. */
    int currentLine;		/* Current line being unfiltered. */
    unsigned char phase;	/* Interlacing phase (0..6). */
    Tk_PhotoImageBlock block;
    int blockLen;		/* Number of bytes in Tk image pixels. */

    /*
     * For containing data read from PLTE (palette) and tRNS (transparency)
     * chunks.
     */

    int paletteLen;		/* Number of PLTE entries (1..256). */
    int useTRNS;		/* Flag to indicate whether there was a
				 * palette given. */
    struct {
	unsigned char red;
	unsigned char green;
	unsigned char blue;
	unsigned char alpha;
    } palette[256];		/* Palette RGB/Transparency table. */
    unsigned char transVal[6];	/* Fully-transparent RGB/Gray Value. */

    /*
     * For compressing and decompressing IDAT chunks.
     */

    Tcl_ZlibStream stream;	/* Inflating or deflating stream; this one is
				 * not bound to a Tcl command. */
    Tcl_Obj *lastLineObj;	/* Last line of pixels, for unfiltering. */
    Tcl_Obj *thisLineObj;	/* Current line of pixels to process. */
    int lineSize;		/* Number of bytes in a PNG line. */
    int phaseSize;		/* Number of bytes/line in current phase. */
} PNGImage;

/*
 * Maximum size of various chunks.
 */

#define	PNG_PLTE_MAXSZ 768	/* 3 bytes/RGB entry, 256 entries max */
#define	PNG_TRNS_MAXSZ 256	/* 1-byte alpha, 256 entries max */

/*
 * Forward declarations of non-global functions defined in this file:
 */

static void		ApplyAlpha(PNGImage *pngPtr);
static int		CheckColor(Tcl_Interp *interp, PNGImage *pngPtr);
static inline int	CheckCRC(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned long calculated);
static void		CleanupPNGImage(PNGImage *pngPtr);
static int		DecodeLine(Tcl_Interp *interp, PNGImage *pngPtr);
static int		DecodePNG(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle,
			    int destX, int destY);
static int		EncodePNG(Tcl_Interp *interp,
			    Tk_PhotoImageBlock *blockPtr, PNGImage *pngPtr);
static int		FileMatchPNG(Tcl_Channel chan, const char *fileName,
			    Tcl_Obj *fmtObj, int *widthPtr, int *heightPtr,
			    Tcl_Interp *interp);
static int		FileReadPNG(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *fmtObj,
			    Tk_PhotoHandle imageHandle, int destX, int destY,
			    int width, int height, int srcX, int srcY);
static int		FileWritePNG(Tcl_Interp *interp, const char *filename,
			    Tcl_Obj *fmtObj, Tk_PhotoImageBlock *blockPtr);
static int		InitPNGImage(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tcl_Channel chan, Tcl_Obj *objPtr, int dir);
static inline unsigned char Paeth(int a, int b, int c);
static int		ParseFormat(Tcl_Interp *interp, Tcl_Obj *fmtObj,
			    PNGImage *pngPtr);
static int		ReadBase64(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned char *destPtr, int destSz,
			    unsigned long *crcPtr);
static int		ReadByteArray(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned char *destPtr, int destSz,
			    unsigned long *crcPtr);
static int		ReadData(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned char *destPtr, int destSz,
			    unsigned long *crcPtr);
static int		ReadChunkHeader(Tcl_Interp *interp, PNGImage *pngPtr,
			    int *sizePtr, unsigned long *typePtr,
			    unsigned long *crcPtr);
static int		ReadIDAT(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		ReadIHDR(Tcl_Interp *interp, PNGImage *pngPtr);
static inline int	ReadInt32(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned long *resultPtr, unsigned long *crcPtr);
static int		ReadPLTE(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		ReadTRNS(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		SkipChunk(Tcl_Interp *interp, PNGImage *pngPtr,
			    int chunkSz, unsigned long crc);
static int		StringMatchPNG(Tcl_Obj *dataObj, Tcl_Obj *fmtObj,
			    int *widthPtr, int *heightPtr,
			    Tcl_Interp *interp);
static int		StringReadPNG(Tcl_Interp *interp, Tcl_Obj *dataObj,
			    Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY);
static int		StringWritePNG(Tcl_Interp *interp, Tcl_Obj *fmtObj,
			    Tk_PhotoImageBlock *blockPtr);
static int		UnfilterLine(Tcl_Interp *interp, PNGImage *pngPtr);
static inline int	WriteByte(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned char c, unsigned long *crcPtr);
static inline int	WriteChunk(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned long chunkType,
			    const unsigned char *dataPtr, int dataSize);
static int		WriteData(Tcl_Interp *interp, PNGImage *pngPtr,
			    const unsigned char *srcPtr, int srcSz,
			    unsigned long *crcPtr);
static int		WriteExtraChunks(Tcl_Interp *interp,
			    PNGImage *pngPtr);
static int		WriteIHDR(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tk_PhotoImageBlock *blockPtr);
static int		WriteIDAT(Tcl_Interp *interp, PNGImage *pngPtr,
			    Tk_PhotoImageBlock *blockPtr);
static inline int	WriteInt32(Tcl_Interp *interp, PNGImage *pngPtr,
			    unsigned long l, unsigned long *crcPtr);

/*
 * The format record for the PNG file format:
 */

Tk_PhotoImageFormat tkImgFmtPNG = {
    "png",			/* name */
    FileMatchPNG,		/* fileMatchProc */
    StringMatchPNG,		/* stringMatchProc */
    FileReadPNG,		/* fileReadProc */
    StringReadPNG,		/* stringReadProc */
    FileWritePNG,		/* fileWriteProc */
    StringWritePNG,		/* stringWriteProc */
    NULL
};

/*
 *----------------------------------------------------------------------
 *
 * InitPNGImage --
 *
 *	This function is invoked by each of the Tk image handler procs
 *	(MatchStringProc, etc.) to initialize state information used during
 *	the course of encoding or decoding a PNG image.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if initialization failed.
 *
 * Side effects:
 *	The reference count of the -data Tcl_Obj*, if any, is incremented.
 *
 *----------------------------------------------------------------------
 */

static int
InitPNGImage(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    Tcl_Channel chan,
    Tcl_Obj *objPtr,
    int dir)
{
    memset(pngPtr, 0, sizeof(PNGImage));

    pngPtr->channel = chan;
    pngPtr->alpha = 1.0;

    /*
     * If decoding from a -data string object, increment its reference count
     * for the duration of the decode and get its length and byte array for
     * reading with ReadData().
     */

    if (objPtr) {
	Tcl_IncrRefCount(objPtr);
	pngPtr->objDataPtr = objPtr;
	pngPtr->strDataBuf =
		Tcl_GetByteArrayFromObj(objPtr, &pngPtr->strDataLen);
    }

    /*
     * Initialize the palette transparency table to fully opaque.
     */

    memset(pngPtr->palette, 255, sizeof(pngPtr->palette));

    /*
     * Initialize Zlib inflate/deflate stream.
     */

    if (Tcl_ZlibStreamInit(NULL, dir, TCL_ZLIB_FORMAT_ZLIB,
	    TCL_ZLIB_COMPRESS_DEFAULT, NULL, &pngPtr->stream) != TCL_OK) {
	Tcl_SetResult(interp, "zlib initialization failed", TCL_STATIC);
	if (objPtr) {
	    Tcl_DecrRefCount(objPtr);
	}
	return TCL_ERROR;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CleanupPNGImage --
 *
 *	This function is invoked by each of the Tk image handler procs
 *	(MatchStringProc, etc.) prior to returning to Tcl in order to clean up
 *	any allocated memory and call other cleanup handlers such as zlib's
 *	inflateEnd/deflateEnd.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The reference count of the -data Tcl_Obj*, if any, is decremented.
 *	Buffers are freed, streams are closed. The PNGImage should not be used
 *	for any purpose without being reinitialized post-cleanup.
 *
 *----------------------------------------------------------------------
 */

static void
CleanupPNGImage(
    PNGImage *pngPtr)
{
    /*
     * Don't need the object containing the -data value anymore.
     */

    if (pngPtr->objDataPtr) {
	Tcl_DecrRefCount(pngPtr->objDataPtr);
    }

    /*
     * Discard pixel buffer.
     */

    if (pngPtr->stream) {
	Tcl_ZlibStreamClose(pngPtr->stream);
    }

    if (pngPtr->block.pixelPtr) {
	ckfree(pngPtr->block.pixelPtr);
    }
    if (pngPtr->thisLineObj) {
	Tcl_DecrRefCount(pngPtr->thisLineObj);
    }
    if (pngPtr->lastLineObj) {
	Tcl_DecrRefCount(pngPtr->lastLineObj);
    }

    memset(pngPtr, 0, sizeof(PNGImage));
}

/*
 *----------------------------------------------------------------------
 *
 * ReadBase64 --
 *
 *	This function is invoked to read the specified number of bytes from
 *	base-64 encoded image data.
 *
 *	Note: It would be better if the Tk_PhotoImage stuff handled this by
 *	creating a channel from the -data value, which would take care of
 *	base64 decoding and made the data readable as if it were coming from a
 *	file.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs.
 *
 * Side effects:
 *	The file position will change. The running CRC is updated if a pointer
 *	to it is provided.
 *
 *----------------------------------------------------------------------
 */

static int
ReadBase64(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned char *destPtr,
    int destSz,
    unsigned long *crcPtr)
{
    static const unsigned char from64[] = {
	0x82, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x80, 0x80,
	0x83, 0x80, 0x80, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x80,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x3e,
	0x83, 0x83, 0x83, 0x3f, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a,
	0x3b, 0x3c, 0x3d, 0x83, 0x83, 0x83, 0x81, 0x83, 0x83, 0x83, 0x00,
	0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
	0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
	0x17, 0x18, 0x19, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x1a, 0x1b,
	0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26,
	0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31,
	0x32, 0x33, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83,
	0x83, 0x83
    };

    /*
     * Definitions for the base-64 decoder.
     */

#define PNG64_SPECIAL	0x80	/* Flag bit */
#define PNG64_SPACE	0x80	/* Whitespace */
#define PNG64_PAD	0x81	/* Padding */
#define PNG64_DONE	0x82	/* End of data */
#define PNG64_BAD	0x83	/* Ooooh, naughty! */

    while (destSz && pngPtr->strDataLen) {
	unsigned char c = 0;
	unsigned char c64 = from64[*pngPtr->strDataBuf++];

	pngPtr->strDataLen--;

	if (PNG64_SPACE == c64) {
	    continue;
	}

	if (c64 & PNG64_SPECIAL) {
	    c = (unsigned char) pngPtr->base64Bits;
	} else {
	    switch (pngPtr->base64State++) {
	    case 0:
		pngPtr->base64Bits = c64 << 2;
		continue;
	    case 1:
		c = (unsigned char) (pngPtr->base64Bits | (c64 >> 4));
		pngPtr->base64Bits = (c64 & 0xF) << 4;
		break;
	    case 2:
		c = (unsigned char) (pngPtr->base64Bits | (c64 >> 2));
		pngPtr->base64Bits = (c64 & 0x3) << 6;
		break;
	    case 3:
		c = (unsigned char) (pngPtr->base64Bits | c64);
		pngPtr->base64State = 0;
		pngPtr->base64Bits = 0;
		break;
	    }
	}

	if (crcPtr) {
	    *crcPtr = Tcl_ZlibCRC32(*crcPtr, &c, 1);
	}

	if (destPtr) {
	    *destPtr++ = c;
	}

	destSz--;

	if (c64 & PNG64_SPECIAL) {
	    break;
	}
    }

    if (destSz) {
	Tcl_SetResult(interp, "Unexpected end of image data", TCL_STATIC);
	return TCL_ERROR;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadByteArray --
 *
 *	This function is invoked to read the specified number of bytes from a
 *	non-base64-encoded byte array provided via the -data option.
 *
 *	Note: It would be better if the Tk_PhotoImage stuff handled this by
 *	creating a channel from the -data value and made the data readable as
 *	if it were coming from a file.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs.
 *
 * Side effects:
 *	The file position will change. The running CRC is updated if a pointer
 *	to it is provided.
 *
 *----------------------------------------------------------------------
 */

static int
ReadByteArray(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned char *destPtr,
    int destSz,
    unsigned long *crcPtr)
{
    /*
     * Check to make sure the number of requested bytes are available.
     */

    if (pngPtr->strDataLen < destSz) {
	Tcl_SetResult(interp, "Unexpected end of image data", TCL_STATIC);
	return TCL_ERROR;
    }

    while (destSz) {
	int blockSz = PNG_MIN(destSz, PNG_BLOCK_SZ);

	memcpy(destPtr, pngPtr->strDataBuf, blockSz);

	pngPtr->strDataBuf += blockSz;
	pngPtr->strDataLen -= blockSz;

	if (crcPtr) {
	    *crcPtr = Tcl_ZlibCRC32(*crcPtr, destPtr, blockSz);
	}

	destPtr += blockSz;
	destSz -= blockSz;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadData --
 *
 *	This function is invoked to read the specified number of bytes from
 *	the image file or data. It is a wrapper around the choice of byte
 *	array Tcl_Obj or Tcl_Channel which depends on whether the image data
 *	is coming from a file or -data.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs.
 *
 * Side effects:
 *	The file position will change. The running CRC is updated if a pointer
 *	to it is provided.
 *
 *----------------------------------------------------------------------
 */

static int
ReadData(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned char *destPtr,
    int destSz,
    unsigned long *crcPtr)
{
    if (pngPtr->base64Data) {
	return ReadBase64(interp, pngPtr, destPtr, destSz, crcPtr);
    } else if (pngPtr->strDataBuf) {
	return ReadByteArray(interp, pngPtr, destPtr, destSz, crcPtr);
    }

    while (destSz) {
	int blockSz = PNG_MIN(destSz, PNG_BLOCK_SZ);

	blockSz = Tcl_Read(pngPtr->channel, (char *)destPtr, blockSz);

	/*
	 * Check for read failure.
	 */

	if (blockSz < 0) {
	    /* TODO: failure info... */
	    Tcl_SetResult(interp, "Channel read failed", TCL_STATIC);
	    return TCL_ERROR;
	}

	/*
	 * Update CRC, pointer, and remaining count if anything was read.
	 */

	if (blockSz) {
	    if (crcPtr) {
		*crcPtr = Tcl_ZlibCRC32(*crcPtr, destPtr, blockSz);
	    }

	    destPtr += blockSz;
	    destSz -= blockSz;
	}

	/*
	 * Check for EOF before all desired data was read.
	 */

	if (destSz && Tcl_Eof(pngPtr->channel)) {
	    Tcl_SetResult(interp, "Unexpected end of file ", TCL_STATIC);
	    return TCL_ERROR;
	}
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadInt32 --
 *
 *	This function is invoked to read a 32-bit integer in network byte
 *	order from the image data and return the value in host byte order.
 *	This is used, for example, to read the 32-bit CRC value for a chunk
 *	stored in the image file for comparison with the calculated CRC value.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs.
 *
 * Side effects:
 *	The file position will change. The running CRC is updated if a pointer
 *	to it is provided.
 *
 *----------------------------------------------------------------------
 */

static inline int
ReadInt32(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned long *resultPtr,
    unsigned long *crcPtr)
{
    unsigned char p[4];

    if (ReadData(interp, pngPtr, p, 4, crcPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    *resultPtr = PNG_INT32(p[0], p[1], p[2], p[3]);

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CheckCRC --
 *
 *	This function is reads the final 4-byte integer CRC from a chunk and
 *	compares it to the running CRC calculated over the chunk type and data
 *	fields.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error or CRC mismatch occurs.
 *
 * Side effects:
 *	The file position will change.
 *
 *----------------------------------------------------------------------
 */

static inline int
CheckCRC(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned long calculated)
{
    unsigned long chunked;

    /*
     * Read the CRC field at the end of the chunk.
     */

    if (ReadInt32(interp, pngPtr, &chunked, NULL) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Compare the read CRC to what we calculate to make sure they match.
     */

    if (calculated != chunked) {
	Tcl_SetResult(interp, "CRC check failed", TCL_STATIC);
	return TCL_ERROR;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SkipChunk --
 *
 *	This function is used to skip a PNG chunk that is not used by this
 *	implementation. Given the input stream has had the chunk length and
 *	chunk type fields already read, this function will read the number of
 *	bytes indicated by the chunk length, plus four for the CRC, and will
 *	verify that CRC is correct for the skipped data.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error or CRC mismatch occurs.
 *
 * Side effects:
 *	The file position will change.
 *
 *----------------------------------------------------------------------
 */

static int
SkipChunk(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    int chunkSz,
    unsigned long crc)
{
    unsigned char buffer[PNG_BLOCK_SZ];

    /*
     * Skip data in blocks until none is left. Read up to PNG_BLOCK_SZ bytes
     * at a time, rather than trusting the claimed chunk size, which may not
     * be trustworthy.
     */

    while (chunkSz) {
	int blockSz = PNG_MIN(chunkSz, PNG_BLOCK_SZ);

	if (ReadData(interp, pngPtr, buffer, blockSz, &crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	chunkSz -= blockSz;
    }

    if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    return TCL_OK;
}

/*
 * 4.3. Summary of standard chunks
 *
 * This table summarizes some properties of the standard chunk types. 
 *
 *	Critical chunks (must appear in this order, except PLTE is optional):
 *
 *		Name   Multiple	 Ordering constraints OK?
 *
 *		IHDR	No	 Must be first
 *		PLTE	No	 Before IDAT
 *		IDAT	Yes	 Multiple IDATs must be consecutive
 *		IEND	No	 Must be last
 *
 *	Ancillary chunks (need not appear in this order):
 *
 *		Name   Multiple	 Ordering constraints OK?
 *
 *		cHRM	No	 Before PLTE and IDAT
 *		gAMA	No	 Before PLTE and IDAT
 *		iCCP	No	 Before PLTE and IDAT
 *		sBIT	No	 Before PLTE and IDAT
 *		sRGB	No	 Before PLTE and IDAT
 *		bKGD	No	 After PLTE; before IDAT
 *		hIST	No	 After PLTE; before IDAT
 *		tRNS	No	 After PLTE; before IDAT
 *		pHYs	No	 Before IDAT
 *		sPLT	Yes	 Before IDAT
 *		tIME	No	 None
 *		iTXt	Yes	 None
 *		tEXt	Yes	 None
 *		zTXt	Yes	 None
 *
 *	[From the PNG specification.]
 */

/*
 *----------------------------------------------------------------------
 *
 * ReadChunkHeader --
 *
 *	This function is used at the start of each chunk to extract the
 *	four-byte chunk length and four-byte chunk type fields. It will
 *	continue reading until it finds a chunk type that is handled by this
 *	implementation, checking the CRC of any chunks it skips.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs or an unknown critical
 *	chunk type is encountered.
 *
 * Side effects:
 *	The file position will change. The running CRC is updated.
 *
 *----------------------------------------------------------------------
 */

static int
ReadChunkHeader(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    int *sizePtr,
    unsigned long *typePtr,
    unsigned long *crcPtr)
{
    unsigned long chunkType = 0;
    int chunkSz = 0;
    unsigned long crc = 0;

    /*
     * Continue until finding a chunk type that is handled.
     */

    while (!chunkType) {
	unsigned long temp;
	unsigned char pc[4];
	int i;

	/*
	 * Read the 4-byte length field for the chunk. The length field is not
	 * included in the CRC calculation, so the running CRC must be reset
	 * afterward. Limit chunk lengths to INT_MAX, to align with the
	 * maximum size for Tcl_Read, Tcl_GetByteArrayFromObj, etc.
	 */

	if (ReadData(interp, pngPtr, pc, 4, NULL) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	temp = PNG_INT32(pc[0], pc[1], pc[2], pc[3]);

	if (temp > INT_MAX) {
	    Tcl_SetResult(interp, "Chunk size is out of supported range "
		    "on this architecture", TCL_STATIC);
	    return TCL_ERROR;
	}

	chunkSz = (int) temp;
	crc = Tcl_ZlibCRC32(0, NULL, 0);

	/*
	 * Read the 4-byte chunk type.
	 */

	if (ReadData(interp, pngPtr, pc, 4, &crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	/*
	 * Convert it to a host-order integer for simple comparison.
	 */

	chunkType = PNG_INT32(pc[0], pc[1], pc[2], pc[3]);

	/*
	 * Check to see if this is a known/supported chunk type. Note that the
	 * PNG specs require non-critical (i.e., ancillary) chunk types that
	 * are not recognized to be ignored, rather than be treated as an
	 * error. It does, however, recommend that an unknown critical chunk
	 * type be treated as a failure.
	 *
	 * This switch/loop acts as a filter of sorts for undesired chunk
	 * types. The chunk type should still be checked elsewhere for
	 * determining it is in the correct order.
	 */

	switch (chunkType) {
	    /*
	     * These chunk types are required and/or supported.
	     */

	case CHUNK_IDAT:
	case CHUNK_IEND:
	case CHUNK_IHDR:
	case CHUNK_PLTE:
	case CHUNK_tRNS:
	    break;

	    /*
	     * These chunk types are part of the standard, but are not used by
	     * this implementation (at least not yet). Note that these are all
	     * ancillary chunks (lowercase first letter).
	     */

	case CHUNK_bKGD:
	case CHUNK_cHRM:
	case CHUNK_gAMA:
	case CHUNK_hIST:
	case CHUNK_iCCP:
	case CHUNK_iTXt:
	case CHUNK_oFFs:
	case CHUNK_pCAL:
	case CHUNK_pHYs:
	case CHUNK_sBIT:
	case CHUNK_sCAL:
	case CHUNK_sPLT:
	case CHUNK_sRGB:
	case CHUNK_tEXt:
	case CHUNK_tIME:
	case CHUNK_zTXt:
	    /*
	     * TODO: might want to check order here.
	     */

	    if (SkipChunk(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
		return TCL_ERROR;
	    }

	    chunkType = 0;
	    break;

	default:
	    /*
	     * Unknown chunk type. If it's critical, we can't continue.
	     */

	    if (!(chunkType & PNG_CF_ANCILLARY)) {
		Tcl_SetResult(interp,
			"Encountered an unsupported criticial chunk type",
			TCL_STATIC);
		return TCL_ERROR;
	    }

	    /*
	     * Check to see if the chunk type has legal bytes.
	     */

	    for (i=0 ; i<4 ; i++) {
		if ((pc[i] < 65) || (pc[i] > 122) ||
			((pc[i] > 90) && (pc[i] < 97))) {
		    Tcl_SetResult(interp, "Invalid chunk type", TCL_STATIC);
		    return TCL_ERROR;
		}
	    }

	    /*
	     * It seems to be an otherwise legally labelled ancillary chunk
	     * that we don't want, so skip it after at least checking its CRC.
	     */

	    if (SkipChunk(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
		return TCL_ERROR;
	    }

	    chunkType = 0;
	}
    }

    /*
     * Found a known chunk type that's handled, albiet possibly not in the
     * right order. Send back the chunk type (for further checking or
     * handling), the chunk size and the current CRC for the rest of the
     * calculation.
     */

    *typePtr = chunkType;
    *sizePtr = chunkSz;
    *crcPtr = crc;

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CheckColor --
 *
 *	Do validation on color type, depth, and related information, and
 *	calculates storage requirements and offsets based on image dimensions
 *	and color.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if color information is invalid or some other
 *	failure occurs.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static int
CheckColor(
    Tcl_Interp *interp,
    PNGImage *pngPtr)
{
    int result = TCL_OK;
    int offset;

    /*
     * Verify the color type is valid and the bit depth is allowed.
     */

    switch (pngPtr->colorType) {
    case PNG_COLOR_GRAY:
	pngPtr->numChannels = 1;
	if ((1 != pngPtr->bitDepth) && (2 != pngPtr->bitDepth) &&
		(4 != pngPtr->bitDepth) && (8 != pngPtr->bitDepth) &&
		(16 != pngPtr->bitDepth)) {
	    result = TCL_ERROR;
	}
	break;

    case PNG_COLOR_RGB:
	pngPtr->numChannels = 3;
	if ((8 != pngPtr->bitDepth) && (16 != pngPtr->bitDepth)) {
	    result = TCL_ERROR;
	}
	break;

    case PNG_COLOR_PLTE:
	pngPtr->numChannels = 1;
	if ((1 != pngPtr->bitDepth) && (2 != pngPtr->bitDepth) &&
		(4 != pngPtr->bitDepth) && (8 != pngPtr->bitDepth)) {
	    result = TCL_ERROR;
	}
	break;

    case PNG_COLOR_GRAYALPHA:
	pngPtr->numChannels = 2;
	if ((8 != pngPtr->bitDepth) && (16 != pngPtr->bitDepth)) {
	    result = TCL_ERROR;
	}
	break;

    case PNG_COLOR_RGBA:
	pngPtr->numChannels = 4;
	if ((8 != pngPtr->bitDepth) && (16 != pngPtr->bitDepth)) {
	    result = TCL_ERROR;
	}
	break;

    default:
	Tcl_SetResult(interp, "Unknown Color Type field", TCL_STATIC);
	return TCL_ERROR;
    }

    if (TCL_ERROR == result) {
	Tcl_SetResult(interp, "Bit depth is not allowed for given color type",
		TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Set up the Tk photo block's pixel size and channel offsets. offset
     * array elements should already be 0 from the memset during InitPNGImage.
     */

    offset = (pngPtr->bitDepth > 8) ? 2 : 1;

    if (pngPtr->colorType & PNG_COLOR_USED) {
	pngPtr->block.pixelSize = offset * 4;
	pngPtr->block.offset[1] = offset;
	pngPtr->block.offset[2] = offset * 2;
	pngPtr->block.offset[3] = offset * 3;
    } else {
	pngPtr->block.pixelSize = offset * 2;
	pngPtr->block.offset[3] = offset;
    }

    /*
     * Calculate the block pitch, which is the number of bytes per line in the
     * image, given image width and depth of color. Make sure that it it isn't
     * larger than Tk can handle.
     */

    if (pngPtr->block.width > INT_MAX / pngPtr->block.pixelSize) {
	Tcl_SetResult(interp,
		"Image pitch is out of supported range on this architecture",
		TCL_STATIC);
	return TCL_ERROR;
    }

    pngPtr->block.pitch = pngPtr->block.pixelSize * pngPtr->block.width;

    /*
     * Calculate the total size of the image as represented to Tk given pitch
     * and image height. Make sure that it isn't larger than Tk can handle.
     */

    if (pngPtr->block.height > INT_MAX / pngPtr->block.pitch) {
	Tcl_SetResult(interp, "Image total size is out of supported range "
		"on this architecture", TCL_STATIC);
	return TCL_ERROR;
    }

    pngPtr->blockLen = pngPtr->block.height * pngPtr->block.pitch;

    /*
     * Determine number of bytes per pixel in the source for later use.
     */

    switch (pngPtr->colorType) {
    case PNG_COLOR_GRAY:
	pngPtr->bytesPerPixel = (pngPtr->bitDepth > 8) ? 2 : 1;
	break;
    case PNG_COLOR_RGB:
	pngPtr->bytesPerPixel = (pngPtr->bitDepth > 8) ? 6 : 3;
	break;
    case PNG_COLOR_PLTE:
	pngPtr->bytesPerPixel = 1;
	break;
    case PNG_COLOR_GRAYALPHA:
	pngPtr->bytesPerPixel = (pngPtr->bitDepth > 8) ? 4 : 2;
	break;
    case PNG_COLOR_RGBA:
	pngPtr->bytesPerPixel = (pngPtr->bitDepth > 8) ? 8 : 4;
	break;
    default:
	Tcl_SetResult(interp, "internal error - unknown color type",
		TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Calculate scale factor for bit depths less than 8, in order to adjust
     * them to a minimum of 8 bits per pixel in the Tk image.
     */

    if (pngPtr->bitDepth < 8) {
	pngPtr->bitScale = 255 / (int)(pow(2, pngPtr->bitDepth) - 1);
    } else {
	pngPtr->bitScale = 1;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadIHDR --
 *
 *	This function reads the PNG header from the beginning of a PNG file
 *	and returns the dimensions of the image.
 *
 * Results:
 *	The return value is 1 if file "f" appears to start with a valid PNG
 *	header, 0 otherwise. If the header is valid, then *widthPtr and
 *	*heightPtr are modified to hold the dimensions of the image.
 *
 * Side effects:
 *	The access position in f advances.
 *
 *----------------------------------------------------------------------
 */

static int
ReadIHDR(
    Tcl_Interp *interp,
    PNGImage *pngPtr)
{
    unsigned char sigBuf[PNG_SIG_SZ];
    unsigned long chunkType;
    int chunkSz;
    unsigned long crc;
    unsigned long width, height;
    int mismatch;

    /*
     * Read the appropriate number of bytes for the PNG signature.
     */

    if (ReadData(interp, pngPtr, sigBuf, PNG_SIG_SZ, NULL) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Compare the read bytes to the expected signature.
     */

    mismatch = memcmp(sigBuf, pngSignature, PNG_SIG_SZ);

    /*
     * If reading from string, reset position and try base64 decode.
     */

    if (mismatch && pngPtr->strDataBuf) {
	pngPtr->strDataBuf = Tcl_GetByteArrayFromObj(pngPtr->objDataPtr,
		&pngPtr->strDataLen);
	pngPtr->base64Data = pngPtr->strDataBuf;

	if (ReadData(interp, pngPtr, sigBuf, PNG_SIG_SZ, NULL) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	mismatch = memcmp(sigBuf, pngSignature, PNG_SIG_SZ);
    }

    if (mismatch) {
	Tcl_SetResult(interp, "Data stream does not have a PNG signature",
		TCL_STATIC);
	return TCL_ERROR;
    }

    if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
	    &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Read in the IHDR (header) chunk for width, height, etc.
     *
     * The first chunk in the file must be the IHDR (headr) chunk.
     */

    if (chunkType != CHUNK_IHDR) {
	Tcl_SetResult(interp, "Expected IHDR chunk type", TCL_STATIC);
	return TCL_ERROR;
    }

    if (chunkSz != 13) {
	Tcl_SetResult(interp, "Invalid IHDR chunk size", TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Read and verify the image width and height to be sure Tk can handle its
     * dimensions. The PNG specification does not permit zero-width or
     * zero-height images.
     */

    if (ReadInt32(interp, pngPtr, &width, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (ReadInt32(interp, pngPtr, &height, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (!width || !height || (width > INT_MAX) || (height > INT_MAX)) {
	Tcl_SetResult(interp,
		"Image dimensions are invalid or beyond architecture limits",
		TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Set height and width for the Tk photo block.
     */

    pngPtr->block.width = (int) width;
    pngPtr->block.height = (int) height;

    /*
     * Read and the Bit Depth and Color Type.
     */

    if (ReadData(interp, pngPtr, &pngPtr->bitDepth, 1, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (ReadData(interp, pngPtr, &pngPtr->colorType, 1, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Verify that the color type is valid, the bit depth is allowed for the
     * color type, and calculate the number of channels and pixel depth (bits
     * per pixel * channels). Also set up offsets and sizes in the Tk photo
     * block for the pixel data.
     */

    if (CheckColor(interp, pngPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Only one compression method is currently defined by the standard.
     */

    if (ReadData(interp, pngPtr, &pngPtr->compression, 1, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (PNG_COMPRESS_DEFLATE != pngPtr->compression) {
	Tcl_SetResult(interp, "Unknown compression method", TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Only one filter method is currently defined by the standard; the method
     * has five actual filter types associated with it.
     */

    if (ReadData(interp, pngPtr, &pngPtr->filter, 1, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (PNG_FILTMETH_STANDARD != pngPtr->filter) {
	Tcl_SetResult(interp, "Unknown filter method", TCL_STATIC);
	return TCL_ERROR;
    }

    if (ReadData(interp, pngPtr, &pngPtr->interlace, 1, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    switch (pngPtr->interlace) {
    case PNG_INTERLACE_NONE:
    case PNG_INTERLACE_ADAM7:
	break;

    default:
	Tcl_SetResult(interp, "Unknown interlace method", TCL_STATIC);
	return TCL_ERROR;
    }

    return CheckCRC(interp, pngPtr, crc);
}

/*
 *----------------------------------------------------------------------
 *
 * ReadPLTE --
 *
 *	This function reads the PLTE (indexed color palette) chunk data from
 *	the PNG file and populates the palette table in the PNGImage
 *	structure.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs or the PLTE chunk is
 *	invalid.
 *
 * Side effects:
 *	The access position in f advances.
 *
 *----------------------------------------------------------------------
 */

static int
ReadPLTE(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    int chunkSz,
    unsigned long crc)
{
    unsigned char buffer[PNG_PLTE_MAXSZ];
    int i, c;

    /*
     * This chunk is mandatory for color type 3 and forbidden for 2 and 6.
     */

    switch (pngPtr->colorType) {
    case PNG_COLOR_GRAY:
    case PNG_COLOR_GRAYALPHA:
	Tcl_SetResult(interp, "PLTE chunk type forbidden for grayscale",
		TCL_STATIC);
	return TCL_ERROR;

    default:
	break;
    }

    /*
     * The palette chunk contains from 1 to 256 palette entries. Each entry
     * consists of a 3-byte RGB value. It must therefore contain a non-zero
     * multiple of 3 bytes, up to 768.
     */

    if (!chunkSz || (chunkSz > PNG_PLTE_MAXSZ) || (chunkSz % 3)) {
	Tcl_SetResult(interp, "Invalid palette chunk size", TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Read the palette contents and stash them for later, possibly.
     */

    if (ReadData(interp, pngPtr, buffer, chunkSz, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Stash away the palette entries and entry count for later mapping each
     * pixel's palette index to its color.
     */

    for (i=0, c=0 ; c<chunkSz ; i++) {
	pngPtr->palette[i].red = buffer[c++];
	pngPtr->palette[i].green = buffer[c++];
	pngPtr->palette[i].blue = buffer[c++];
    }

    pngPtr->paletteLen = i;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadTRNS --
 *
 *	This function reads the tRNS (transparency) chunk data from the PNG
 *	file and populates the alpha field of the palette table in the
 *	PNGImage structure or the single color transparency, as appropriate
 *	for the color type.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs or the tRNS chunk is
 *	invalid.
 *
 * Side effects:
 *	The access position in f advances.
 *
 *----------------------------------------------------------------------
 */

static int
ReadTRNS(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    int chunkSz,
    unsigned long crc)
{
    unsigned char buffer[PNG_TRNS_MAXSZ];
    int i;

    if (pngPtr->colorType & PNG_COLOR_ALPHA) {
	Tcl_SetResult(interp,
		"tRNS chunk not allowed color types with a full alpha channel",
		TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * For indexed color, there is up to one single-byte transparency value
     * per palette entry (thus a max of 256).
     */

    if (chunkSz > PNG_TRNS_MAXSZ) {
	Tcl_SetResult(interp, "Invalid tRNS chunk size", TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Read in the raw transparency information.
     */

    if (ReadData(interp, pngPtr, buffer, chunkSz, &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    switch (pngPtr->colorType) {
    case PNG_COLOR_GRAYALPHA:
    case PNG_COLOR_RGBA:
	break;

    case PNG_COLOR_PLTE:
	/*
	 * The number of tRNS entries must be less than or equal to the number
	 * of PLTE entries, and consists of a single-byte alpha level for the
	 * corresponding PLTE entry.
	 */

	if (chunkSz > pngPtr->paletteLen) {
	    Tcl_SetResult(interp,
		    "Size of tRNS chunk is too large for the palette",
		    TCL_STATIC);
	    return TCL_ERROR;
	}

	for (i=0 ; i<chunkSz ; i++) {
	    pngPtr->palette[i].alpha = buffer[i];
	}
	break;

    case PNG_COLOR_GRAY:
	/*
	 * Grayscale uses a single 2-byte gray level, which we'll store in
	 * palette index 0, since we're not using the palette.
	 */

	if (chunkSz != 2) {
	    Tcl_SetResult(interp,
		    "Invalid tRNS chunk size - must 2 bytes for grayscale",
		    TCL_STATIC);
	    return TCL_ERROR;
	}

	/*
	 * According to the PNG specs, if the bit depth is less than 16, then
	 * only the lower byte is used.
	 */

	if (16 == pngPtr->bitDepth) {
	    pngPtr->transVal[0] = buffer[0];
	    pngPtr->transVal[1] = buffer[1];
	} else {
	    pngPtr->transVal[0] = buffer[1];
	}
	pngPtr->useTRNS = 1;
	break;

    case PNG_COLOR_RGB:
	/*
	 * TrueColor uses a single RRGGBB triplet.
	 */

	if (chunkSz != 6) {
	    Tcl_SetResult(interp,
		    "Invalid tRNS chunk size - must 6 bytes for RGB",
		    TCL_STATIC);
	    return TCL_ERROR;
	}

	/*
	 * According to the PNG specs, if the bit depth is less than 16, then
	 * only the lower byte is used. But the tRNS chunk still contains two
	 * bytes per channel.
	 */

	if (16 == pngPtr->bitDepth) {
	    memcpy(pngPtr->transVal, buffer, 6);
	} else {
	    pngPtr->transVal[0] = buffer[1];
	    pngPtr->transVal[1] = buffer[3];
	    pngPtr->transVal[2] = buffer[5];
	}
	pngPtr->useTRNS = 1;
	break;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Paeth --
 *
 *	Utility function for applying the Paeth filter to a pixel. The Paeth
 *	filter is a linear function of the pixel to be filtered and the pixels
 *	to the left, above, and above-left of the pixel to be unfiltered.
 *
 * Results:
 *	Result of the Paeth function for the left, above, and above-left
 *	pixels.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static inline unsigned char
Paeth(
    int a,
    int b,
    int c)
{
    int pa = abs(b - c);
    int pb = abs(a - c);
    int pc = abs(a + b - c - c);

    if ((pa <= pb) && (pa <= pc)) {
	return (unsigned char) a;
    }

    if (pb <= pc) {
	return (unsigned char) b;
    }

    return (unsigned char) c;
}

/*
 *----------------------------------------------------------------------
 *
 * UnfilterLine --
 *
 *	Applies the filter algorithm specified in first byte of a line to the
 *	line of pixels being read from a PNG image.
 *
 *	PNG specifies four filter algorithms (Sub, Up, Average, and Paeth)
 *	that combine a pixel's value with those of other pixels in the same
 *	and/or previous lines. Filtering is intended to make an image more
 *	compressible.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the filter type is not recognized.
 *
 * Side effects:
 *	Pixel data in thisLineObj are modified.
 *
 *----------------------------------------------------------------------
 */

static int
UnfilterLine(
    Tcl_Interp *interp,
    PNGImage *pngPtr)
{
    unsigned char *thisLine =
	    Tcl_GetByteArrayFromObj(pngPtr->thisLineObj, NULL);
    unsigned char *lastLine =
	    Tcl_GetByteArrayFromObj(pngPtr->lastLineObj, NULL);

#define	PNG_FILTER_NONE		0
#define	PNG_FILTER_SUB		1
#define	PNG_FILTER_UP		2
#define	PNG_FILTER_AVG		3
#define	PNG_FILTER_PAETH	4

    switch (*thisLine) {
    case PNG_FILTER_NONE:	/* Nothing to do */
	break;
    case PNG_FILTER_SUB: {	/* Sub(x) = Raw(x) - Raw(x-bpp) */
	unsigned char *rawBpp = thisLine + 1;
	unsigned char *raw = rawBpp + pngPtr->bytesPerPixel;
	unsigned char *end = thisLine + pngPtr->phaseSize;

	while (raw < end) {
	    *raw++ += *rawBpp++;
	}
	break;
    }
    case PNG_FILTER_UP:		/* Up(x) = Raw(x) - Prior(x) */
	if (pngPtr->currentLine > startLine[pngPtr->phase]) {
	    unsigned char *prior = lastLine + 1;
	    unsigned char *raw = thisLine + 1;
	    unsigned char *end = thisLine + pngPtr->phaseSize;

	    while (raw < end) {
		*raw++ += *prior++;
	    }
	}
	break;
    case PNG_FILTER_AVG:
	/* Avg(x) = Raw(x) - floor((Raw(x-bpp)+Prior(x))/2) */
	if (pngPtr->currentLine > startLine[pngPtr->phase]) {
	    unsigned char *prior = lastLine + 1;
	    unsigned char *rawBpp = thisLine + 1;
	    unsigned char *raw = rawBpp;
	    unsigned char *end = thisLine + pngPtr->phaseSize;
	    unsigned char *end2 = raw + pngPtr->bytesPerPixel;

	    while ((raw < end2) && (raw < end)) {
		*raw++ += *prior++ / 2;
	    }

	    while (raw < end) {
		*raw++ += (unsigned char)
			(((int) *rawBpp++ + (int) *prior++) / 2);
	    }
	} else {
	    unsigned char *rawBpp = thisLine + 1;
	    unsigned char *raw = rawBpp + pngPtr->bytesPerPixel;
	    unsigned char *end = thisLine + pngPtr->phaseSize;

	    while (raw < end) {
		*raw++ += *rawBpp++ / 2;
	    }
	}
	break;
    case PNG_FILTER_PAETH:
	/* Paeth(x) = Raw(x) - PaethPredictor(Raw(x-bpp), Prior(x), Prior(x-bpp)) */
	if (pngPtr->currentLine > startLine[pngPtr->phase]) {
	    unsigned char *priorBpp = lastLine + 1;
	    unsigned char *prior = priorBpp;
	    unsigned char *rawBpp = thisLine + 1;
	    unsigned char *raw = rawBpp;
	    unsigned char *end = thisLine + pngPtr->phaseSize;
	    unsigned char *end2 = rawBpp + pngPtr->bytesPerPixel;

	    while ((raw < end) && (raw < end2)) {
		*raw++ += *prior++;
	    }

	    while (raw < end) {
		*raw++ += Paeth(*rawBpp++, *prior++, *priorBpp++);
	    }
	} else {
	    unsigned char *rawBpp = thisLine + 1;
	    unsigned char *raw = rawBpp + pngPtr->bytesPerPixel;
	    unsigned char *end = thisLine + pngPtr->phaseSize;

	    while (raw < end) {
		*raw++ += *rawBpp++;
	    }
	}
	break;
    default:
	Tcl_SetResult(interp, "Invalid filter type", TCL_STATIC);
	return TCL_ERROR;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DecodeLine --
 *
 *	Unfilters a line of pixels from the PNG source data and decodes the
 *	data into the Tk_PhotoImageBlock for later copying into the Tk image.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the filter type is not recognized.
 *
 * Side effects:
 *	Pixel data in thisLine and block are modified and state information
 *	updated.
 *
 *----------------------------------------------------------------------
 */

static int
DecodeLine(
    Tcl_Interp *interp,
    PNGImage *pngPtr)
{
    unsigned char *pixelPtr = pngPtr->block.pixelPtr;
    int colNum = 0;		/* Current pixel column */
    unsigned char chan = 0;	/* Current channel (0..3) = (R, G, B, A) */
    unsigned char readByte = 0;	/* Current scan line byte */
    int haveBits = 0;		/* Number of bits remaining in current byte */
    unsigned char pixBits = 0;	/* Extracted bits for current channel */
    int shifts = 0;		/* Number of channels extracted from byte */
    int offset = 0;		/* Current offset into pixelPtr */
    int colStep = 1;		/* Column increment each pass */
    int pixStep = 0;		/* extra pixelPtr increment each pass */
    unsigned char lastPixel[6];
    unsigned char *p = Tcl_GetByteArrayFromObj(pngPtr->thisLineObj, NULL);

    p++;
    if (UnfilterLine(interp, pngPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (pngPtr->interlace) {
	switch (pngPtr->phase) {
	case 1:			/* Phase 1: */
	    colStep = 8;	/* 1 pixel per block of 8 per line */
	    break;		/* Start at column 0 */
	case 2:			/* Phase 2: */
	    colStep = 8;	/* 1 pixels per block of 8 per line */
	    colNum = 4;		/* Start at column 4 */
	    break;
	case 3:			/* Phase 3: */
	    colStep = 4;	/* 2 pixels per block of 8 per line */
	    break;		/* Start at column 0 */
	case 4:			/* Phase 4: */
	    colStep = 4;	/* 2 pixels per block of 8 per line */
	    colNum = 2;		/* Start at column 2 */
	    break;
	case 5:			/* Phase 5: */
	    colStep = 2;	/* 4 pixels per block of 8 per line */
	    break;		/* Start at column 0 */
	case 6:			/* Phase 6: */
	    colStep = 2;	/* 4 pixels per block of 8 per line */
	    colNum = 1;		/* Start at column 1 */
	    break;
				/* Phase 7: */
				/* 8 pixels per block of 8 per line */
				/* Start at column 0 */
	}
    }

    /*
     * Calculate offset into pixelPtr for the first pixel of the line.
     */

    offset = pngPtr->currentLine * pngPtr->block.pitch;

    /*
     * Adjust up for the starting pixel of the line.
     */

    offset += colNum * pngPtr->block.pixelSize;

    /*
     * Calculate the extra number of bytes to skip between columns.
     */

    pixStep = (colStep - 1) * pngPtr->block.pixelSize;

    for ( ; colNum < pngPtr->block.width ; colNum += colStep) {
	if (haveBits < (pngPtr->bitDepth * pngPtr->numChannels)) {
	    haveBits = 0;
	}

	for (chan = 0 ; chan < pngPtr->numChannels ; chan++) {
	    if (!haveBits) {
		shifts = 0;
		readByte = *p++;
		haveBits += 8;
	    }

	    if (16 == pngPtr->bitDepth) {
		pngPtr->block.pixelPtr[offset++] = readByte;

		if (pngPtr->useTRNS) {
		    lastPixel[chan * 2] = readByte;
		}

		readByte = *p++;

		if (pngPtr->useTRNS) {
		    lastPixel[(chan * 2) + 1] = readByte;
		}

		pngPtr->block.pixelPtr[offset++] = readByte;

		haveBits = 0;
		continue;
	    }

	    switch (pngPtr->bitDepth) {
	    case 1:
		pixBits = (unsigned char)((readByte >> (7-shifts)) & 0x01);
		break;
	    case 2:
		pixBits = (unsigned char)((readByte >> (6-shifts*2)) & 0x03);
		break;
	    case 4:
		pixBits = (unsigned char)((readByte >> (4-shifts*4)) & 0x0f);
		break;
	    case 8:
		pixBits = readByte;
		break;
	    }

	    if (PNG_COLOR_PLTE == pngPtr->colorType) {
		pixelPtr[offset++] = pngPtr->palette[pixBits].red;
		pixelPtr[offset++] = pngPtr->palette[pixBits].green;
		pixelPtr[offset++] = pngPtr->palette[pixBits].blue;
		pixelPtr[offset++] = pngPtr->palette[pixBits].alpha;
		chan += 2;
	    } else {
		pixelPtr[offset++] = (unsigned char)
			(pixBits * pngPtr->bitScale);

		if (pngPtr->useTRNS) {
		    lastPixel[chan] = pixBits;
		}
	    }

	    haveBits -= pngPtr->bitDepth;
	    shifts++;
	}

	/*
	 * Apply boolean transparency via tRNS data if necessary (where
	 * necessary means a tRNS chunk was provided and we're not using an
	 * alpha channel or indexed alpha).
	 */

	if ((PNG_COLOR_PLTE != pngPtr->colorType) &&
		((pngPtr->colorType & PNG_COLOR_ALPHA) == 0)) {
	    unsigned char alpha;

	    if (pngPtr->useTRNS) {
		if (memcmp(lastPixel, pngPtr->transVal,
			pngPtr->bytesPerPixel) == 0) {
		    alpha = 0x00;
		} else {
		    alpha = 0xff;
		}
	    } else {
		alpha = 0xff;
	    }

	    pixelPtr[offset++] = alpha;

	    if (16 == pngPtr->bitDepth) {
		pixelPtr[offset++] = alpha;
	    }
	}

	offset += pixStep;
    }

    if (pngPtr->interlace) {
	/* Skip lines */

	switch (pngPtr->phase) {
	case 1: case 2: case 3:
	    pngPtr->currentLine += 8;
	    break;
	case 4: case 5:
	    pngPtr->currentLine += 4;
	    break;
	case 6: case 7:
	    pngPtr->currentLine += 2;
	    break;
	}

	/*
	 * Start the next phase if there are no more lines to do.
	 */

	if (pngPtr->currentLine >= pngPtr->block.height) {
	    unsigned long pixels = 0;

	    while ((!pixels || (pngPtr->currentLine >= pngPtr->block.height))
		    && (pngPtr->phase < 7)) {
		pngPtr->phase++;

		switch (pngPtr->phase) {
		case 2:
		    pixels = (pngPtr->block.width + 3) >> 3;
		    pngPtr->currentLine = 0;
		    break;
		case 3:
		    pixels = (pngPtr->block.width + 3) >> 2;
		    pngPtr->currentLine = 4;
		    break;
		case 4:
		    pixels = (pngPtr->block.width + 1) >> 2;
		    pngPtr->currentLine = 0;
		    break;
		case 5:
		    pixels = (pngPtr->block.width + 1) >> 1;
		    pngPtr->currentLine = 2;
		    break;
		case 6:
		    pixels = pngPtr->block.width >> 1;
		    pngPtr->currentLine = 0;
		    break;
		case 7:
		    pngPtr->currentLine = 1;
		    pixels = pngPtr->block.width;
		    break;
		}
	    }

	    if (16 == pngPtr->bitDepth) {
		pngPtr->phaseSize = 1 + (pngPtr->numChannels * pixels * 2);
	    } else {
		pngPtr->phaseSize = 1 + ((pngPtr->numChannels * pixels *
			pngPtr->bitDepth + 7) >> 3);
	    }
	}
    } else {
	pngPtr->currentLine++;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadIDAT --
 *
 *	This function reads the IDAT (pixel data) chunk from the PNG file to
 *	build the image. It will continue reading until all IDAT chunks have
 *	been processed or an error occurs.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs or an IDAT chunk is
 *	invalid.
 *
 * Side effects:
 *	The access position in f advances. Memory may be allocated by zlib
 *	through PNGZAlloc.
 *
 *----------------------------------------------------------------------
 */

static int
ReadIDAT(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    int chunkSz,
    unsigned long crc)
{
    /*
     * Process IDAT contents until there is no more in this chunk.
     */

    while (chunkSz && !Tcl_ZlibStreamEof(pngPtr->stream)) {
	int len1, len2;

	/*
	 * Read another block of input into the zlib stream if data remains.
	 */

	if (chunkSz) {
	    Tcl_Obj *inputObj = NULL;
	    int blockSz = PNG_MIN(chunkSz, PNG_BLOCK_SZ);
	    unsigned char *inputPtr = NULL;

	    /*
	     * Check for end of zlib stream.
	     */

	    if (Tcl_ZlibStreamEof(pngPtr->stream)) {
		Tcl_SetResult(interp, "Extra data after end of zlib stream",
			TCL_STATIC);
		return TCL_ERROR;
	    }

	    inputObj = Tcl_NewObj();
	    Tcl_IncrRefCount(inputObj);
	    inputPtr = Tcl_SetByteArrayLength(inputObj, blockSz);

	    /*
	     * Read the next bit of IDAT chunk data, up to read buffer size.
	     */

	    if (ReadData(interp, pngPtr, inputPtr, blockSz,
		    &crc) == TCL_ERROR) {
		Tcl_DecrRefCount(inputObj);
		return TCL_ERROR;
	    }

	    chunkSz -= blockSz;

	    Tcl_ZlibStreamPut(pngPtr->stream, inputObj, TCL_ZLIB_NO_FLUSH);
	    Tcl_DecrRefCount(inputObj);
	}

	/*
	 * Inflate, processing each output buffer's worth as a line of pixels,
	 * until we cannot fill the buffer any more.
	 */

    getNextLine:
	Tcl_GetByteArrayFromObj(pngPtr->thisLineObj, &len1);
	if (Tcl_ZlibStreamGet(pngPtr->stream, pngPtr->thisLineObj,
		pngPtr->phaseSize - len1) == TCL_ERROR) {
	    return TCL_ERROR;
	}
	Tcl_GetByteArrayFromObj(pngPtr->thisLineObj, &len2);

	if (len2 == pngPtr->phaseSize) {
	    if (pngPtr->phase > 7) {
		Tcl_SetResult(interp,
			"Extra data after final scan line of final phase",
			TCL_STATIC);
		return TCL_ERROR;
	    }

	    if (DecodeLine(interp, pngPtr) == TCL_ERROR) {
		return TCL_ERROR;
	    }

	    /*
	     * Swap the current/last lines so that we always have the last
	     * line processed available, which is necessary for filtering.
	     */

	    {
		Tcl_Obj *temp = pngPtr->lastLineObj;

		pngPtr->lastLineObj = pngPtr->thisLineObj;
		pngPtr->thisLineObj = temp;
	    }
	    Tcl_SetByteArrayLength(pngPtr->thisLineObj, 0);

	    /*
	     * Try to read another line of pixels out of the buffer
	     * immediately.
	     */

	    goto getNextLine;
	}

	/*
	 * Got less than a whole buffer-load of pixels. Either we're going to
	 * be getting more data from the next IDAT, or we've done what we can
	 * here.
	 */
    }

    /*
     * Ensure that if we've got to the end of the compressed data, we've
     * also got to the end of the compressed stream. This sanity check is
     * enforced by most PNG readers.
     */

    if (chunkSz != 0) {
	Tcl_AppendResult(interp,
		"compressed data after stream finalize in PNG data", NULL);
	return TCL_ERROR;
    }

    return CheckCRC(interp, pngPtr, crc);
}

/*
 *----------------------------------------------------------------------
 *
 * ApplyAlpha --
 *
 *	Applies an overall alpha value to a complete image that has been read.
 *	This alpha value is specified using the -format option to [image
 *	create photo].
 *
 * Results:
 *	N/A
 *
 * Side effects:
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static void
ApplyAlpha(
    PNGImage *pngPtr)
{
    if (pngPtr->alpha != 1.0) {
	register unsigned char *p = pngPtr->block.pixelPtr;
	unsigned char *endPtr = p + pngPtr->blockLen;
	int offset = pngPtr->block.offset[3];

	p += offset;

	if (16 == pngPtr->bitDepth) {
	    register int channel;

	    while (p < endPtr) {
		channel = (unsigned char)
			(((p[0] << 8) | p[1]) * pngPtr->alpha);

		*p++ = (unsigned char) (channel >> 8);
		*p++ = (unsigned char) (channel & 0xff);

		p += offset;
	    }
	} else {
	    while (p < endPtr) {
		p[0] = (unsigned char) (pngPtr->alpha * p[0]);
		p += 1 + offset;
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ParseFormat --
 *
 *	This function parses the -format string that can be specified to the
 *	[image create photo] command to extract options for postprocessing of
 *	loaded images. Currently, this just allows specifying and applying an
 *	overall alpha value to the loaded image (for example, to make it
 *	entirely 50% as transparent as the actual image file).
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the format specification is invalid.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static int
ParseFormat(
    Tcl_Interp *interp,
    Tcl_Obj *fmtObj,
    PNGImage *pngPtr)
{
    Tcl_Obj **objv = NULL;
    int objc = 0;
    static const char *const fmtOptions[] = {
	"png", "-alpha", NULL
    };
    enum fmtOptions {
	OPT_PNG, OPT_ALPHA
    };

    /*
     * Extract elements of format specification as a list.
     */

    if (fmtObj &&
	    Tcl_ListObjGetElements(interp, fmtObj, &objc, &objv) != TCL_OK) {
	return TCL_ERROR;
    }

    for (; objc>0 ; objc--, objv++) {
    	int optIndex;

        if (Tcl_GetIndexFromObj(interp, objv[0], fmtOptions, "option", 0,
		&optIndex) == TCL_ERROR) {
            return TCL_ERROR;
	}

	/*
	 * Ignore the "png" part of the format specification.
	 */

	if (OPT_PNG == optIndex) {
	    continue;
	}

    	if (objc < 2) {
	    Tcl_WrongNumArgs(interp, 1, objv, "value");
	    return TCL_ERROR;
    	}

	objc--;
	objv++;

	switch ((enum fmtOptions) optIndex) {
	case OPT_PNG:
	    break;

	case OPT_ALPHA:
	    if (Tcl_GetDoubleFromObj(interp, objv[0],
		    &pngPtr->alpha) == TCL_ERROR) {
		return TCL_ERROR;
	    }

	    if ((pngPtr->alpha < 0.0) || (pngPtr->alpha > 1.0)) {
		Tcl_SetResult(interp,
			"-alpha value must be between 0.0 and 1.0",
			TCL_STATIC);
		return TCL_ERROR;
	    }
	    break;
	}
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DecodePNG --
 *
 *	This function handles the entirety of reading a PNG file (or data)
 *	from the first byte to the last.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O error occurs or any problems are
 *	detected in the PNG file.
 *
 * Side effects:
 *	The access position in f advances. Memory may be allocated and image
 *	dimensions and contents may change.
 *
 *----------------------------------------------------------------------
 */

static int
DecodePNG(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    Tcl_Obj *fmtObj,
    Tk_PhotoHandle imageHandle,
    int destX,
    int destY)
{
    unsigned long chunkType;
    int chunkSz;
    unsigned long crc;

    /*
     * Parse the PNG signature and IHDR (header) chunk.
     */

    if (ReadIHDR(interp, pngPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Extract alpha value from -format object, if specified.
     */

    if (ParseFormat(interp, fmtObj, pngPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * The next chunk may either be a PLTE (Palette) chunk or the first of at
     * least one IDAT (data) chunks. It could also be one of a number of
     * ancillary chunks, but those are skipped for us by the switch in
     * ReadChunkHeader().
     *
     * PLTE is mandatory for color type 3 and forbidden for 2 and 6
     */

    if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
	    &crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    if (CHUNK_PLTE == chunkType) {
	/*
	 * Finish parsing the PLTE chunk.
	 */

	if (ReadPLTE(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	/*
	 * Begin the next chunk.
	 */

	if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
		&crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}
    } else if (PNG_COLOR_PLTE == pngPtr->colorType) {
	Tcl_SetResult(interp, "PLTE chunk required for indexed color",
		TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * The next chunk may be a tRNS (palette transparency) chunk, depending on
     * the color type. It must come after the PLTE chunk and before the IDAT
     * chunk, but can be present if there is no PLTE chunk because it can be
     * used for Grayscale and TrueColor in lieu of an alpha channel.
     */

    if (CHUNK_tRNS == chunkType) {
	/*
	 * Finish parsing the tRNS chunk.
	 */

	if (ReadTRNS(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	/*
	 * Begin the next chunk.
	 */

	if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
		&crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}
    }

    /*
     * Other ancillary chunk types could appear here, but for now we're only
     * interested in IDAT. The others should have been skipped.
     */

    if (CHUNK_IDAT != chunkType) {
	Tcl_SetResult(interp, "At least one IDAT chunk is required",
		TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Expand the photo size (if not set by the user) to provide enough space
     * for the image being parsed. It does not matter if width or height wrap
     * to negative here: Tk will not shrink the image.
     */

    if (Tk_PhotoExpand(interp, imageHandle, destX + pngPtr->block.width,
	    destY + pngPtr->block.height) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * A scan line consists of one byte for a filter type, plus the number of
     * bits per color sample times the number of color samples per pixel.
     */

    if (pngPtr->block.width > ((INT_MAX - 1) / (pngPtr->numChannels * 2))) {
	Tcl_SetResult(interp,
		"Line size is out of supported range on this architecture",
		TCL_STATIC);
	return TCL_ERROR;
    }

    if (16 == pngPtr->bitDepth) {
	pngPtr->lineSize = 1 + (pngPtr->numChannels * pngPtr->block.width*2);
    } else {
	pngPtr->lineSize = 1 + ((pngPtr->numChannels * pngPtr->block.width) /
		(8 / pngPtr->bitDepth));
	if (pngPtr->block.width % (8 / pngPtr->bitDepth)) {
	    pngPtr->lineSize++;
	}
    }

    /*
     * Allocate space for decoding the scan lines.
     */

    pngPtr->lastLineObj = Tcl_NewObj();
    Tcl_IncrRefCount(pngPtr->lastLineObj);
    pngPtr->thisLineObj = Tcl_NewObj();
    Tcl_IncrRefCount(pngPtr->thisLineObj);

    pngPtr->block.pixelPtr = attemptckalloc(pngPtr->blockLen);
    if (!pngPtr->block.pixelPtr) {
	Tcl_SetResult(interp, "Memory allocation failed", TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Determine size of the first phase if interlaced. Phase size should
     * always be <= line size, so probably not necessary to check for
     * arithmetic overflow here: should be covered by line size check.
     */

    if (pngPtr->interlace) {
	/*
	 * Only one pixel per block of 8 per line in the first phase.
	 */

	unsigned int pixels = (pngPtr->block.width + 7) >> 3;

	pngPtr->phase = 1;
	if (16 == pngPtr->bitDepth) {
	    pngPtr->phaseSize = 1 + pngPtr->numChannels*pixels*2;
	} else {
	    pngPtr->phaseSize = 1 +
		    ((pngPtr->numChannels*pixels*pngPtr->bitDepth + 7) >> 3);
	}
    } else {
	pngPtr->phaseSize = pngPtr->lineSize;
    }

    /*
     * All of the IDAT (data) chunks must be consecutive.
     */

    while (CHUNK_IDAT == chunkType) {
	if (ReadIDAT(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
		&crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}
    }

    /*
     * Ensure that we've got to the end of the compressed stream now that
     * there are no more IDAT segments. This sanity check is enforced by most
     * PNG readers.
     */

    if (!Tcl_ZlibStreamEof(pngPtr->stream)) {
	Tcl_AppendResult(interp, "unfinalized data stream in PNG data", NULL);
	return TCL_ERROR;
    }

    /*
     * Now skip the remaining chunks which we're also not interested in.
     */

    while (CHUNK_IEND != chunkType) {
	if (SkipChunk(interp, pngPtr, chunkSz, crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}

	if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType,
		&crc) == TCL_ERROR) {
	    return TCL_ERROR;
	}
    }

    /*
     * Got the IEND (end of image) chunk. Do some final checks...
     */

    if (chunkSz) {
	Tcl_SetResult(interp, "IEND chunk contents must be empty",
		TCL_STATIC);
	return TCL_ERROR;
    }

    /*
     * Check the CRC on the IEND chunk.
     */

    if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * TODO: verify that nothing else comes after the IEND chunk, or do we
     * really care?
     */

#if 0
    if (ReadData(interp, pngPtr, &c, 1, NULL) != TCL_ERROR) {
	Tcl_SetResult(interp, "Extra data following IEND chunk", TCL_STATIC);
	return TCL_ERROR;
    }
#endif

    /*
     * Apply overall image alpha if specified.
     */

    ApplyAlpha(pngPtr);

    /*
     * Copy the decoded image block into the Tk photo image.
     */

    if (Tk_PhotoPutBlock(interp, imageHandle, &pngPtr->block, destX, destY,
	    pngPtr->block.width, pngPtr->block.height,
	    TK_PHOTO_COMPOSITE_SET) == TCL_ERROR) {
	return TCL_ERROR;
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FileMatchPNG --
 *
 *	This function is invoked by the photo image type to see if a file
 *	contains image data in PNG format.
 *
 * Results:
 *	The return value is 1 if the first characters in file f look like PNG
 *	data, and 0 otherwise.
 *
 * Side effects:
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
FileMatchPNG(
    Tcl_Channel chan,
    const char *fileName,
    Tcl_Obj *fmtObj,
    int *widthPtr,
    int *heightPtr,
    Tcl_Interp *interp)
{
    PNGImage png;
    int match = 0;
    Tcl_SavedResult sya;

    Tcl_SaveResult(interp, &sya);

    InitPNGImage(interp, &png, chan, NULL, TCL_ZLIB_STREAM_INFLATE);

    if (ReadIHDR(interp, &png) == TCL_OK) {
	*widthPtr = png.block.width;
	*heightPtr = png.block.height;
	match = 1;
    }

    CleanupPNGImage(&png);
    Tcl_RestoreResult(interp, &sya);

    return match;
}

/*
 *----------------------------------------------------------------------
 *
 * FileReadPNG --
 *
 *	This function is called by the photo image type to read PNG format
 *	data from a file and write it into a given photo image.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	The access position in file f is changed, and new data is added to the
 *	image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
FileReadPNG(
    Tcl_Interp *interp,
    Tcl_Channel chan,
    const char *fileName,
    Tcl_Obj *fmtObj,
    Tk_PhotoHandle imageHandle,
    int destX,
    int destY,
    int width,
    int height,
    int srcX,
    int srcY)
{
    PNGImage png;
    int result = TCL_ERROR;

    result = InitPNGImage(interp, &png, chan, NULL, TCL_ZLIB_STREAM_INFLATE);

    if (TCL_OK == result) {
	result = DecodePNG(interp, &png, fmtObj, imageHandle, destX, destY);
    }

    CleanupPNGImage(&png);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringMatchPNG --
 *
 *	This function is invoked by the photo image type to see if an object
 *	contains image data in PNG format.
 *
 * Results:
 *	The return value is 1 if the first characters in the data are like PNG
 *	data, and 0 otherwise.
 *
 * Side effects:
 *	The size of the image is placed in widthPre and heightPtr.
 *
 *----------------------------------------------------------------------
 */

static int
StringMatchPNG(
    Tcl_Obj *pObjData,
    Tcl_Obj *fmtObj,
    int *widthPtr,
    int *heightPtr,
    Tcl_Interp *interp)
{
    PNGImage png;
    int match = 0;
    Tcl_SavedResult sya;

    Tcl_SaveResult(interp, &sya);
    InitPNGImage(interp, &png, NULL, pObjData, TCL_ZLIB_STREAM_INFLATE);

    png.strDataBuf = Tcl_GetByteArrayFromObj(pObjData, &png.strDataLen);

    if (ReadIHDR(interp, &png) == TCL_OK) {
	*widthPtr = png.block.width;
	*heightPtr = png.block.height;
	match = 1;
    }

    CleanupPNGImage(&png);
    Tcl_RestoreResult(interp, &sya);
    return match;
}

/*
 *----------------------------------------------------------------------
 *
 * StringReadPNG --
 *
 *	This function is called by the photo image type to read PNG format
 *	data from an object and give it to the photo image.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	New data is added to the image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
StringReadPNG(
    Tcl_Interp *interp,
    Tcl_Obj *pObjData,
    Tcl_Obj *fmtObj,
    Tk_PhotoHandle imageHandle,
    int destX,
    int destY,
    int width,
    int height,
    int srcX,
    int srcY)
{
    PNGImage png;
    int result = TCL_ERROR;

    result = InitPNGImage(interp, &png, NULL, pObjData,
	    TCL_ZLIB_STREAM_INFLATE);

    if (TCL_OK == result) {
	result = DecodePNG(interp, &png, fmtObj, imageHandle, destX, destY);
    }

    CleanupPNGImage(&png);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * WriteData --
 *
 *	This function writes a bytes from a buffer out to the PNG image.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the write fails.
 *
 * Side effects:
 *	File or buffer will be modified.
 *
 *----------------------------------------------------------------------
 */

static int
WriteData(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    const unsigned char *srcPtr,
    int srcSz,
    unsigned long *crcPtr)
{
    if (!srcPtr || !srcSz) {
	return TCL_OK;
    }

    if (crcPtr) {
	*crcPtr = Tcl_ZlibCRC32(*crcPtr, srcPtr, srcSz);
    }

    /*
     * TODO: is Tcl_AppendObjToObj faster here? i.e., does Tcl join the
     * objects immediately or store them in a multi-object rep?
     */

    if (pngPtr->objDataPtr) {
	int objSz;
	unsigned char *destPtr;

	Tcl_GetByteArrayFromObj(pngPtr->objDataPtr, &objSz);

	if (objSz > INT_MAX - srcSz) {
	    Tcl_SetResult(interp,
		    "Image too large to store completely in byte array",
		    TCL_STATIC);
	    return TCL_ERROR;
	}

	destPtr = Tcl_SetByteArrayLength(pngPtr->objDataPtr, objSz + srcSz);

	if (!destPtr) {
	    Tcl_SetResult(interp, "Memory allocation failed", TCL_STATIC);
	    return TCL_ERROR;
	}

	memcpy(destPtr+objSz, srcPtr, srcSz);
    } else if (Tcl_Write(pngPtr->channel, (const char *) srcPtr, srcSz) < 0) {
	/* TODO: reason */

	Tcl_SetResult(interp, "Write to channel failed", TCL_STATIC);
	return TCL_ERROR;
    }

    return TCL_OK;
}

static inline int
WriteByte(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned char c,
    unsigned long *crcPtr)
{
    return WriteData(interp, pngPtr, &c, 1, crcPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * WriteInt32 --
 *
 *	This function writes a 32-bit integer value out to the PNG image as
 *	four bytes in network byte order.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the write fails.
 *
 * Side effects:
 *	File or buffer will be modified.
 *
 *----------------------------------------------------------------------
 */

static inline int
WriteInt32(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned long l,
    unsigned long *crcPtr)
{
    unsigned char pc[4];

    pc[0] = (unsigned char) ((l & 0xff000000) >> 24);
    pc[1] = (unsigned char) ((l & 0x00ff0000) >> 16);
    pc[2] = (unsigned char) ((l & 0x0000ff00) >> 8);
    pc[3] = (unsigned char) ((l & 0x000000ff) >> 0);

    return WriteData(interp, pngPtr, pc, 4, crcPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * WriteChunk --
 *
 *	Writes a complete chunk to the PNG image, including chunk type,
 *	length, contents, and CRC.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the write fails.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static inline int
WriteChunk(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    unsigned long chunkType,
    const unsigned char *dataPtr,
    int dataSize)
{
    unsigned long crc = Tcl_ZlibCRC32(0, NULL, 0);
    int result = TCL_OK;

    /*
     * Write the length field for the chunk.
     */

    result = WriteInt32(interp, pngPtr, dataSize, NULL);

    /*
     * Write the Chunk Type.
     */

    if (TCL_OK == result) {
	result = WriteInt32(interp, pngPtr, chunkType, &crc);
    }

    /*
     * Write the contents (if any).
     */

    if (TCL_OK == result) {
	result = WriteData(interp, pngPtr, dataPtr, dataSize, &crc);
    }

    /*
     * Write out the CRC at the end of the chunk.
     */

    if (TCL_OK == result) {
	result = WriteInt32(interp, pngPtr, crc, NULL);
    }

    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * WriteIHDR --
 *
 *	This function writes the PNG header at the beginning of a PNG file,
 *	which includes information such as dimensions and color type.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the write fails.
 *
 * Side effects:
 *	File or buffer will be modified.
 *
 *----------------------------------------------------------------------
 */

static int
WriteIHDR(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    Tk_PhotoImageBlock *blockPtr)
{
    unsigned long crc = Tcl_ZlibCRC32(0, NULL, 0);
    int result = TCL_OK;

    /*
     * The IHDR (header) chunk has a fixed size of 13 bytes.
     */

    result = WriteInt32(interp, pngPtr, 13, NULL);

    /*
     * Write the IHDR Chunk Type.
     */

    if (TCL_OK == result) {
	result = WriteInt32(interp, pngPtr, CHUNK_IHDR, &crc);
    }

    /*
     * Write the image width, height.
     */

    if (TCL_OK == result) {
	result = WriteInt32(interp, pngPtr, (unsigned long) blockPtr->width,
		&crc);
    }

    if (TCL_OK == result) {
	result = WriteInt32(interp, pngPtr, (unsigned long) blockPtr->height,
		&crc);
    }

    /*
     * Write bit depth. Although the PNG format supports 16 bits per channel,
     * Tk supports only 8 in the internal representation, which blockPtr
     * points to.
     */

    if (TCL_OK == result) {
	result = WriteByte(interp, pngPtr, 8, &crc);
    }

    /*
     * Write out the color type, previously determined.
     */

    if (TCL_OK == result) {
	result = WriteByte(interp, pngPtr, pngPtr->colorType, &crc);
    }

    /*
     * Write compression method (only one method is defined).
     */

    if (TCL_OK == result) {
	result = WriteByte(interp, pngPtr, PNG_COMPRESS_DEFLATE, &crc);
    }

    /*
     * Write filter method (only one method is defined).
     */

    if (TCL_OK == result) {
	result = WriteByte(interp, pngPtr, PNG_FILTMETH_STANDARD, &crc);
    }

    /*
     * Write interlace method as not interlaced.
     *
     * TODO: support interlace through -format?
     */

    if (TCL_OK == result) {
	result = WriteByte(interp, pngPtr, PNG_INTERLACE_NONE, &crc);
    }

    /*
     * Write out the CRC at the end of the chunk.
     */

    if (TCL_OK == result) {
	result = WriteInt32(interp, pngPtr, crc, NULL);
    }

    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * WriteIDAT --
 *
 *	Writes the IDAT (data) chunk to the PNG image, containing the pixel
 *	channel data. Currently, image lines are not filtered and writing
 *	interlaced pixels is not supported.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the write fails.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static int
WriteIDAT(
    Tcl_Interp *interp,
    PNGImage *pngPtr,
    Tk_PhotoImageBlock *blockPtr)
{
    int rowNum, flush = TCL_ZLIB_NO_FLUSH, outputSize, result;
    Tcl_Obj *outputObj;
    unsigned char *outputBytes;

    /*
     * Filter and compress each row one at a time.
     */

    for (rowNum=0 ; rowNum < blockPtr->height ; rowNum++) {
	int colNum;
	unsigned char *srcPtr, *destPtr;

	srcPtr = blockPtr->pixelPtr + (rowNum * blockPtr->pitch);
	destPtr = Tcl_SetByteArrayLength(pngPtr->thisLineObj,
		pngPtr->lineSize);

	/*
	 * TODO: use Paeth filtering.
	 */

	*destPtr++ = PNG_FILTER_NONE;

	/*
	 * Copy each pixel into the destination buffer after the filter type
	 * before filtering.
	 */

	for (colNum = 0 ; colNum < blockPtr->width ; colNum++) {
	    /*
	     * Copy red or gray channel.
	     */

	    *destPtr++ = srcPtr[blockPtr->offset[0]];

	    /* 
	     * If not grayscale, copy the green and blue channels.
	     */

	    if (pngPtr->colorType & PNG_COLOR_USED) {
		*destPtr++ = srcPtr[blockPtr->offset[1]];
		*destPtr++ = srcPtr[blockPtr->offset[2]];
	    }

	    /*
	     * Copy the alpha channel, if used.
	     */

	    if (pngPtr->colorType & PNG_COLOR_ALPHA) {
		*destPtr++ = srcPtr[blockPtr->offset[3]];
	    }

	    /*
	     * Point to the start of the next pixel.
	     */

	    srcPtr += blockPtr->pixelSize;
	}

	/*
	 * Compress the line of pixels into the destination. If this is the
	 * last line, finalize the compressor at the same time. Note that this
	 * can't be just a flush; that leads to a file that some PNG readers
	 * choke on. [Bug 2984787]
	 */

	if (rowNum + 1 == blockPtr->height) {
	    flush = TCL_ZLIB_FINALIZE;
	}
	if (Tcl_ZlibStreamPut(pngPtr->stream, pngPtr->thisLineObj,
		flush) != TCL_OK) {
	    Tcl_SetResult(interp, "deflate() returned error", TCL_STATIC);
	    return TCL_ERROR;
	}

	/*
	 * Swap line buffers to keep the last around for filtering next.
	 */

	{
	    Tcl_Obj *temp = pngPtr->lastLineObj;

	    pngPtr->lastLineObj = pngPtr->thisLineObj;
	    pngPtr->thisLineObj = temp;
	}
    }

    /*
     * Now get the compressed data and write it as one big IDAT chunk.
     */

    outputObj = Tcl_NewObj();
    (void) Tcl_ZlibStreamGet(pngPtr->stream, outputObj, -1);
    outputBytes = Tcl_GetByteArrayFromObj(outputObj, &outputSize);
    result = WriteChunk(interp, pngPtr, CHUNK_IDAT, outputBytes, outputSize);
    Tcl_DecrRefCount(outputObj);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * WriteExtraChunks --
 *
 *	Writes an sBIT and a tEXt chunks to the PNG image, describing a bunch
 *	of not very important metadata that many readers seem to need anyway.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if the write fails.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static int
WriteExtraChunks(
    Tcl_Interp *interp,
    PNGImage *pngPtr)
{
    static const unsigned char sBIT_contents[] = {
	8, 8, 8, 8
    };
    int sBIT_length = 4;
    Tcl_DString buf;

    /*
     * Each byte of each channel is always significant; we always write RGBA
     * images with 8 bits per channel as that is what the photo image's basic
     * data model is.
     */

    switch (pngPtr->colorType) {
    case PNG_COLOR_GRAY:
	sBIT_length = 1;
	break;
    case PNG_COLOR_GRAYALPHA:
	sBIT_length = 2;
	break;
    case PNG_COLOR_RGB:
    case PNG_COLOR_PLTE:
	sBIT_length = 3;
	break;
    case PNG_COLOR_RGBA:
	sBIT_length = 4;
	break;
    }
    if (WriteChunk(interp, pngPtr, CHUNK_sBIT, sBIT_contents, sBIT_length)
	    != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Say that it is Tk that made the PNG. Note that we *need* the NUL at the
     * end of "Software" to be transferred; do *not* change the length
     * parameter to -1 there!
     */

    Tcl_DStringInit(&buf);
    Tcl_DStringAppend(&buf, "Software", 9);
    Tcl_DStringAppend(&buf, "Tk Toolkit v", -1);
    Tcl_DStringAppend(&buf, TK_PATCH_LEVEL, -1);
    if (WriteChunk(interp, pngPtr, CHUNK_tEXt,
	    (unsigned char *) Tcl_DStringValue(&buf),
	    Tcl_DStringLength(&buf)) != TCL_OK) {
	Tcl_DStringFree(&buf);
	return TCL_ERROR;
    }
    Tcl_DStringFree(&buf);

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * EncodePNG --
 *
 *	This function handles the entirety of writing a PNG file (or data)
 *	from the first byte to the last. No effort is made to optimize the
 *	image data for best compression.
 *
 * Results:
 *	TCL_OK, or TCL_ERROR if an I/O or memory error occurs.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static int
EncodePNG(
    Tcl_Interp *interp,
    Tk_PhotoImageBlock *blockPtr,
    PNGImage *pngPtr)
{
    int greenOffset, blueOffset, alphaOffset;

    /*
     * Determine appropriate color type based on color usage (e.g., only red
     * and maybe alpha channel = grayscale).
     *
     * TODO: Check whether this is doing any good; Tk might just be pushing
     * full RGBA data all the time through here, even though the actual image
     * doesn't need it...
     */

    greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
    blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
    alphaOffset = blockPtr->offset[3];
    if ((alphaOffset >= blockPtr->pixelSize) || (alphaOffset < 0)) {
	alphaOffset = 0;
    } else {
	alphaOffset -= blockPtr->offset[0];
    }

    if ((greenOffset != 0) || (blueOffset != 0)) {
	if (alphaOffset) {
	    pngPtr->colorType = PNG_COLOR_RGBA;
	    pngPtr->bytesPerPixel = 4;
	} else {
	    pngPtr->colorType = PNG_COLOR_RGBA;
	    pngPtr->bytesPerPixel = 3;
	}
    } else {
	if (alphaOffset) {
	    pngPtr->colorType = PNG_COLOR_GRAYALPHA;
	    pngPtr->bytesPerPixel = 2;
	} else {
	    pngPtr->colorType = PNG_COLOR_GRAY;
	    pngPtr->bytesPerPixel = 1;
	}
    }

    /*
     * Allocate buffers for lines for filtering and compressed data.
     */

    pngPtr->lineSize = 1 + (pngPtr->bytesPerPixel * blockPtr->width);
    pngPtr->blockLen = pngPtr->lineSize * blockPtr->height;

    if ((blockPtr->width > (INT_MAX - 1) / (pngPtr->bytesPerPixel)) ||
	    (blockPtr->height > INT_MAX / pngPtr->lineSize)) {
	Tcl_SetResult(interp, "Image is too large to encode pixel data",
		TCL_STATIC);
	return TCL_ERROR;
    }

    pngPtr->lastLineObj = Tcl_NewObj();
    Tcl_IncrRefCount(pngPtr->lastLineObj);
    pngPtr->thisLineObj = Tcl_NewObj();
    Tcl_IncrRefCount(pngPtr->thisLineObj);

    /*
     * Write out the PNG Signature that all PNGs begin with.
     */

    if (WriteData(interp, pngPtr, pngSignature, PNG_SIG_SZ,
	    NULL) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Write out the IHDR (header) chunk containing image dimensions, color
     * type, etc.
     */

    if (WriteIHDR(interp, pngPtr, blockPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Write out the extra chunks containing metadata that is of interest to
     * other programs more than us.
     */

    if (WriteExtraChunks(interp, pngPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Write out the image pixels in the IDAT (data) chunk.
     */

    if (WriteIDAT(interp, pngPtr, blockPtr) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Write out the IEND chunk that all PNGs end with.
     */

    return WriteChunk(interp, pngPtr, CHUNK_IEND, NULL, 0);
}

/*
 *----------------------------------------------------------------------
 *
 * FileWritePNG --
 *
 *	This function is called by the photo image type to write PNG format
 *	data to a file.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	The specified file is overwritten.
 *
 *----------------------------------------------------------------------
 */

static int
FileWritePNG(
    Tcl_Interp *interp,
    const char *filename,
    Tcl_Obj *fmtObj,
    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Channel chan;
    PNGImage png;
    int result = TCL_ERROR;

    /*
     * Open a Tcl file channel where the image data will be stored. Tk ought
     * to take care of this, and just provide a channel, but it doesn't.
     */

    chan = Tcl_OpenFileChannel(interp, filename, "w", 0644);

    if (!chan) {
	return TCL_ERROR;
    }

    /*
     * Initalize PNGImage instance for encoding.
     */

    if (InitPNGImage(interp, &png, chan, NULL,
	    TCL_ZLIB_STREAM_DEFLATE) == TCL_ERROR) {
	goto cleanup;
    }

    /*
     * Set the translation mode to binary so that CR and LF are not to the
     * platform's EOL sequence.
     */

    if (Tcl_SetChannelOption(interp, chan, "-translation",
	    "binary") != TCL_OK) {
	goto cleanup;
    }

    /*
     * Write the raw PNG data out to the file.
     */

    result = EncodePNG(interp, blockPtr, &png);

  cleanup:
    Tcl_Close(interp, chan);
    CleanupPNGImage(&png);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringWritePNG --
 *
 *	This function is called by the photo image type to write PNG format
 *	data to a Tcl object and return it in the result.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static int
StringWritePNG(
    Tcl_Interp *interp,
    Tcl_Obj *fmtObj,
    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Obj *resultObj = Tcl_NewObj();
    PNGImage png;
    int result = TCL_ERROR;

    /*
     * Initalize PNGImage instance for encoding.
     */

    if (InitPNGImage(interp, &png, NULL, resultObj,
	    TCL_ZLIB_STREAM_DEFLATE) == TCL_ERROR) {
	goto cleanup;
    }

    /*
     * Write the raw PNG data into the prepared Tcl_Obj buffer. Set the result
     * back to the interpreter if successful.
     */

    result = EncodePNG(interp, blockPtr, &png);

    if (TCL_OK == result) {
	Tcl_SetObjResult(interp, png.objDataPtr);
    }

  cleanup:
    CleanupPNGImage(&png);
    return result;
}

/*
 * Local Variables:
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */