
// epimgconv: Enterprise 128 image converter utility
// Copyright (C) 2008-2016 Istvan Varga <istvanv@users.sourceforge.net>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// The Enterprise 128 program files generated by this utility are not covered
// by the GNU General Public License, and can be used, modified, and
// distributed without any restrictions.

#include "epimgconv.hpp"
#include "imageconv.hpp"
#include "pixel16_2.hpp"

#include <vector>

namespace Ep128ImgConv {

  void ImageConv_Pixel16_2::initializePalettes()
  {
    for (int i = 0; i < 256; i++)
      convertEPColorToYUV(i, paletteY[i], paletteU[i], paletteV[i]);
  }

  void ImageConv_Pixel16_2::setFixBias(int n)
  {
    fixBiasValue = n & 31;
    for (int yc = 0; yc < height; yc++) {
      for (int i = 8; i < 16; i++)
        palette[yc][i] = (unsigned char) ((fixBiasValue << 3) | (i & 7));
    }
  }

  void ImageConv_Pixel16_2::randomizePalette(int yc, int seedValue)
  {
    int     tmp = 0;
    setRandomSeed(tmp, uint32_t(seedValue));
    for (int i = 0; i < 8; i++) {
      unsigned char c = (unsigned char) (getRandomNumber(tmp) & 0xFF);
      if (!fixedColors[i])
        palette[yc][i] = c;
    }
  }

  double ImageConv_Pixel16_2::calculateLineError(
      int yc, int colorChanged, unsigned char *colorIndexCache,
      double *errorCache, double maxError)
  {
    float   tmpPaletteY[136];
    float   tmpPaletteU[136];
    float   tmpPaletteV[136];
    unsigned char tmpPaletteI[136];
    unsigned char paletteMap[256];
    for (int i = 0; i < 16; i++) {
      tmpPaletteY[i] = paletteY[palette[yc][i]];
      tmpPaletteU[i] = paletteU[palette[yc][i]];
      tmpPaletteV[i] = paletteV[palette[yc][i]];
      tmpPaletteI[i] = (unsigned char) ((i << 4) | i);
      paletteMap[(i << 4) | i] = (unsigned char) i;
    }
    int     n = 16;
    for (int c0 = 0; c0 < 15; c0++) {
      for (int c1 = c0 + 1; c1 < 16; c1++) {
        tmpPaletteY[n] =
            0.5 * (paletteY[palette[yc][c0]] + paletteY[palette[yc][c1]]);
        tmpPaletteU[n] =
            0.5 * (paletteU[palette[yc][c0]] + paletteU[palette[yc][c1]]);
        tmpPaletteV[n] =
            0.5 * (paletteV[palette[yc][c0]] + paletteV[palette[yc][c1]]);
        tmpPaletteI[n] = (unsigned char) ((c0 << 4) | c1);
        paletteMap[(c0 << 4) | c1] = (unsigned char) n;
        paletteMap[c0 | (c1 << 4)] = (unsigned char) n;
        n++;
      }
    }
    double  totalError = 0.0;
    float   tmpY = 0.0;
    float   tmpU = 0.0;
    float   tmpV = 0.0;
    for (int xc = 0; xc < width && totalError < (maxError * 1.00001); xc++) {
      float   y = inputImage.y(xc, yc) + ditherErrorImage.y(xc, yc);
      float   u = inputImage.u(xc, yc) + ditherErrorImage.u(xc, yc);
      float   v = inputImage.v(xc, yc) + ditherErrorImage.v(xc, yc);
      limitYUVColor(y, u, v);
      tmpY += (y * 0.5f);
      tmpU += (u * 0.5f);
      tmpV += (v * 0.5f);
      bool    searchFlag = true;
      if (colorChanged >= 0) {
        if (int(colorIndexCache[xc]) != colorChanged) {
          double  err =
              Ep128ImgConv::calculateYUVErrorSqr(tmpPaletteY[colorChanged],
                                                 tmpPaletteU[colorChanged],
                                                 tmpPaletteV[colorChanged],
                                                 y, u, v, colorErrorScale);
          double  minErr = errorCache[xc];
          if (err < minErr) {
            minErr = err;
            colorIndexCache[xc] = (unsigned char) colorChanged;
            errorCache[xc] = err;
          }
          totalError += minErr;
          searchFlag = false;
        }
      }
      if (searchFlag) {
        double  minErr = 1000000000.0;
        int     ci = 0;
        for (int i = 0; i < 16; i++) {
          double  err =
              Ep128ImgConv::calculateYUVErrorSqr(tmpPaletteY[i],
                                                 tmpPaletteU[i],
                                                 tmpPaletteV[i],
                                                 y, u, v, colorErrorScale);
          if (err < minErr) {
            minErr = err;
            ci = i;
          }
        }
        if (colorIndexCache) {
          colorIndexCache[xc] = (unsigned char) ci;
          errorCache[xc] = minErr;
        }
        totalError += minErr;
      }
      if (!(xc & int(bool(ditherType))))
        continue;
      searchFlag = true;
      if (colorChanged >= 0) {
        if (int(colorIndexCache[width + (xc - 1)]) != colorChanged &&
            int(colorIndexCache[width + xc]) != colorChanged) {
          double  minErr2 = 1000000000.0;
          int     ci = 0;
          for (int i = 0; i < 16; i++) {
            int     tmp = paletteMap[(colorChanged << 4) | i];
            double  err =
                Ep128ImgConv::calculateYUVErrorSqr(
                    tmpPaletteY[tmp], tmpPaletteU[tmp], tmpPaletteV[tmp],
                    tmpY, tmpU, tmpV, colorErrorScale);
            if (err < minErr2) {
              minErr2 = err;
              ci = i;
            }
          }
          double  minErr = errorCache[width + (xc >> 1)];
          if (minErr2 < minErr) {
            minErr = minErr2;
            colorIndexCache[width + (xc - 1)] = (unsigned char) colorChanged;
            colorIndexCache[width + xc] = (unsigned char) ci;
            errorCache[width + (xc >> 1)] = minErr2;
          }
          totalError += (minErr * 1.4142136);
          searchFlag = false;
        }
      }
      if (searchFlag) {
        double  minErr = 1000000000.0;
        int     ci = 0;
        for (int i = 0; i < 136; i += 2) {
          double  err = Ep128ImgConv::calculateYUVErrorSqr(tmpPaletteY[i],
                                                           tmpPaletteU[i],
                                                           tmpPaletteV[i],
                                                           tmpY, tmpU, tmpV,
                                                           colorErrorScale);
          if (err < minErr) {
            minErr = err;
            ci = i;
          }
          err = Ep128ImgConv::calculateYUVErrorSqr(tmpPaletteY[i + 1],
                                                   tmpPaletteU[i + 1],
                                                   tmpPaletteV[i + 1],
                                                   tmpY, tmpU, tmpV,
                                                   colorErrorScale);
          if (err < minErr) {
            minErr = err;
            ci = i + 1;
          }
        }
        if (colorIndexCache) {
          colorIndexCache[width + (xc - 1)] = (tmpPaletteI[ci] >> 4) & 0x0F;
          colorIndexCache[width + xc] = tmpPaletteI[ci] & 0x0F;
          errorCache[width + (xc >> 1)] = minErr;
        }
        totalError += (minErr * 1.4142136);
      }
      tmpY = 0.0f;
      tmpU = 0.0f;
      tmpV = 0.0f;
    }
    return totalError;
  }

  double ImageConv_Pixel16_2::calculateTotalError(
      int colorChanged, unsigned char *colorIndexCache, double *errorCache,
      double maxError)
  {
    double  totalError = 0.0;
    for (int yc = 0; yc < height && totalError < (maxError * 1.000001); yc++) {
      unsigned char *colorIndexPtr = colorIndexCache;
      if (colorIndexPtr)
        colorIndexPtr = &(colorIndexCache[yc * (width * 2)]);
      double  *errorPtr = errorCache;
      if (errorPtr)
        errorPtr = &(errorCache[yc * (width * 3 / 2)]);
      totalError += calculateLineError(yc,
                                       colorChanged, colorIndexPtr, errorPtr);
    }
    return totalError;
  }

  double ImageConv_Pixel16_2::optimizeLinePalette(int yc, int optimizeLevel)
  {
    bool    colorUsed[256];
    for (int i = 0; i < 256; i++)
      colorUsed[i] = true;
    for (int i = 8; i < 16; i++)
      colorUsed[palette[yc][i]] = false;
    std::vector< unsigned char >  colorIndexCache(size_t(width * 2), 0x00);
    std::vector< double >   errorCache(size_t(width * 3 / 2), 1000000000.0);
    double  bestError = 1000000000.0;
    int     bestPalette[8];
    for (int l = 0; l < optimizeLevel; l++) {
      randomizePalette(yc, l + 1);
      double  minErr = calculateLineError(yc);
      bool    doneFlag = true;
      do {
        doneFlag = true;
        for (int i = 0; i < 8; i++) {
          int     bestColor = palette[yc][i];
          if (!fixedColors[i]) {
            (void) calculateLineError(yc, -1, &(colorIndexCache.front()),
                                      &(errorCache.front()));
            for (int c = 0; c < 256; c++) {
              if (!colorUsed[c])
                continue;
              palette[yc][i] = (unsigned char) c;
              double  err = calculateLineError(yc,
                                               i, &(colorIndexCache.front()),
                                               &(errorCache.front()), minErr);
              if (err < (minErr * 0.999999)) {
                bestColor = c;
                doneFlag = false;
                minErr = err;
              }
            }
          }
          palette[yc][i] = (unsigned char) bestColor;
          colorUsed[bestColor] = false;
        }
        for (int i = 0; i < 8; i++)
          colorUsed[palette[yc][i]] = true;
      } while (!doneFlag);
      if (minErr < bestError) {
        for (int i = 0; i < 8; i++)
          bestPalette[i] = palette[yc][i];
        bestError = minErr;
      }
    }
    for (int i = 0; i < 8; i++)
      palette[yc][i] = (unsigned char) bestPalette[i];
    sortLinePalette(yc);
    return bestError;
  }

  double ImageConv_Pixel16_2::optimizeImagePalette(int optimizeLevel,
                                                   bool optimizeFixBias)
  {
    std::vector< unsigned char >  colorIndexCache(size_t(height * (width * 2)),
                                                  0x00);
    std::vector< double >   errorCache(size_t(height * (width * 3 / 2)),
                                       1000000000.0);
    bool    colorUsed[256];
    for (int i = 0; i < 256; i++)
      colorUsed[i] = true;
    for (int i = 8; i < 16; i++)
      colorUsed[palette[0][i]] = false;
    double  bestError = 1000000000.0;
    int     bestPalette[8];
    int     bestFixBias = fixBiasValue;
    int     progressCnt = 0;
    int     progressMax = optimizeLevel * 3 * ((8 * 256) + 32);
    for (int l = 0; l < optimizeLevel; l++) {
      randomizePalette(0, l + 1);
      setFixedPalette();
      double  minErr = calculateTotalError();
      bool    doneFlag = true;
      int     loopCnt = 0;
      do {
        doneFlag = true;
        if (++loopCnt > 3)
          progressCnt -= ((8 * 256) + 32);
        if (optimizeFixBias && !(l == 0 && loopCnt == 1)) {
          int     bestBias = fixBiasValue;
          for (int c = 0; c < 32; c++) {
            if (!setProgressPercentage(progressCnt * 100 / progressMax))
              return -1.0;
            progressCnt++;
            setFixBias(c);
            double  err = calculateTotalError(-1, (unsigned char *) 0,
                                              (double *) 0, minErr);
            if (err < (minErr * 0.999999)) {
              bestBias = c;
              doneFlag = false;
              minErr = err;
            }
          }
          setFixBias(bestBias);
        }
        else {
          if (!setProgressPercentage(progressCnt * 100 / progressMax))
            return -1.0;
          progressCnt += 32;
        }
        for (int i = 8; i < 16; i++)
          colorUsed[palette[0][i]] = false;
        for (int i = 0; i < 8; i++) {
          int     bestColor = palette[0][i];
          if (!fixedColors[i]) {
            setFixedPalette();
            (void) calculateTotalError(-1, &(colorIndexCache.front()),
                                       &(errorCache.front()));
            for (int c = 0; c < 256; c++) {
              if (!setProgressPercentage(progressCnt * 100 / progressMax))
                return -1.0;
              progressCnt++;
              if (!colorUsed[c])
                continue;
              palette[0][i] = (unsigned char) c;
              setFixedPalette();
              double  err = calculateTotalError(i, &(colorIndexCache.front()),
                                                &(errorCache.front()), minErr);
              if (err < (minErr * 0.999999)) {
                bestColor = c;
                doneFlag = false;
                minErr = err;
              }
            }
          }
          else {
            if (!setProgressPercentage(progressCnt * 100 / progressMax))
              return -1.0;
            progressCnt += 256;
          }
          palette[0][i] = (unsigned char) bestColor;
          colorUsed[bestColor] = false;
        }
        setFixedPalette();
        for (int i = 0; i < 16; i++)
          colorUsed[palette[0][i]] = true;
      } while (!doneFlag);
      if (loopCnt < 3)
        progressCnt += ((3 - loopCnt) * ((8 * 256) + 32));
      if (minErr < bestError) {
        for (int i = 0; i < 8; i++)
          bestPalette[i] = palette[0][i];
        bestFixBias = fixBiasValue;
        bestError = minErr;
      }
    }
    setFixBias(bestFixBias);
    for (int i = 0; i < 8; i++)
      palette[0][i] = (unsigned char) bestPalette[i];
    sortLinePalette(0);
    setFixedPalette();
    return bestError;
  }

  void ImageConv_Pixel16_2::sortLinePalette(int yc)
  {
    // sort palette colors by bit-reversed color value
    for (int i = 0; i < 8; i++) {
      unsigned char tmp = palette[yc][i];
      tmp = ((tmp & 0x55) << 1) | ((tmp & 0xAA) >> 1);
      tmp = ((tmp & 0x33) << 2) | ((tmp & 0xCC) >> 2);
      tmp = ((tmp & 0x0F) << 4) | ((tmp & 0xF0) >> 4);
      palette[yc][i] = tmp;
    }
    for (int i = 0; i < 7; i++) {
      for (int j = i + 1; j < 8; j++) {
        if (fixedColors[i] || fixedColors[j] ||
            palette[yc][i] <= palette[yc][j]) {
          continue;
        }
        unsigned char tmp = palette[yc][i];
        palette[yc][i] = palette[yc][j];
        palette[yc][j] = tmp;
      }
    }
    for (int i = 0; i < 8; i++) {
      unsigned char tmp = palette[yc][i];
      tmp = ((tmp & 0x55) << 1) | ((tmp & 0xAA) >> 1);
      tmp = ((tmp & 0x33) << 2) | ((tmp & 0xCC) >> 2);
      tmp = ((tmp & 0x0F) << 4) | ((tmp & 0xF0) >> 4);
      palette[yc][i] = tmp;
    }
  }

  void ImageConv_Pixel16_2::setFixedPalette()
  {
    for (int yc = 1; yc < height; yc++) {
      for (int i = 0; i < 8; i++)
        palette[yc][i] = palette[0][i];
    }
  }

  void ImageConv_Pixel16_2::optimizeLinePalette_fast(int yc)
  {
    double  tmpPaletteY[16];
    double  tmpPaletteU[16];
    double  tmpPaletteV[16];
    int     colorWeights[16];
    for (int i = 0; i < 16; i++) {
      int     c = palette[yc][i];
      tmpPaletteY[i] = paletteY[c];
      tmpPaletteU[i] = paletteU[c];
      tmpPaletteV[i] = paletteV[c];
      colorWeights[i] = 0;
    }
    int     k = 2;
    while ((k >> 1) < width)
      k = k << 1;
    for (int xc = 0; k > 1; xc += k) {
      if (xc >= width) {
        k = k >> 1;
        xc = k >> 1;
        continue;
      }
      double  bestError = 1000000000.0;
      int     bestColor = 0;
      float   y = inputImage.y(xc, yc);
      float   u = inputImage.u(xc, yc);
      float   v = inputImage.v(xc, yc);
      for (int i = 0; i < 16; i++) {
        double  err = 0.0;
        if (i < 8 && !fixedColors[i]) {
          double  tmp1 = double(colorWeights[i]);
          double  tmp2 = 1.0 / double(colorWeights[i] + 1);
          double  tmpY = ((tmpPaletteY[i] * tmp1) + y) * tmp2;
          double  tmpU = ((tmpPaletteU[i] * tmp1) + u) * tmp2;
          double  tmpV = ((tmpPaletteV[i] * tmp1) + v) * tmp2;
          err = Ep128ImgConv::calculateYUVErrorSqr(tmpY, tmpU, tmpV, y, u, v,
                                                   colorErrorScale);
          err += (colorWeights[i] > 0 ? 0.000001 : 0.00001);
        }
        else {
          err = Ep128ImgConv::calculateYUVErrorSqr(tmpPaletteY[i],
                                                   tmpPaletteU[i],
                                                   tmpPaletteV[i],
                                                   y, u, v, colorErrorScale);
        }
        if (err < bestError) {
          bestError = err;
          bestColor = i;
        }
      }
      colorWeights[bestColor] = colorWeights[bestColor] + 1;
      if (bestColor < 8 && !fixedColors[bestColor]) {
        double  tmp1 = double(colorWeights[bestColor] - 1);
        double  tmp2 = 1.0 / double(colorWeights[bestColor]);
        tmpPaletteY[bestColor] = ((tmpPaletteY[bestColor] * tmp1) + y) * tmp2;
        tmpPaletteU[bestColor] = ((tmpPaletteU[bestColor] * tmp1) + u) * tmp2;
        tmpPaletteV[bestColor] = ((tmpPaletteV[bestColor] * tmp1) + v) * tmp2;
      }
    }
    for (int i = 0; i < 8; i++) {
      if (!fixedColors[i]) {
        double  y = tmpPaletteY[i];
        double  u = tmpPaletteU[i];
        double  v = tmpPaletteV[i];
        double  bestError = 1000000000.0;
        int     bestColor = 0;
        for (int c = 0; c < 256; c++) {
          double  err =
              Ep128ImgConv::calculateYUVErrorSqr(
                  paletteY[c], paletteU[c], paletteV[c],
                  y, u, v, colorErrorScale);
          if (err < bestError) {
            bestError = err;
            bestColor = c;
          }
        }
        palette[yc][i] = (unsigned char) bestColor;
      }
    }
    sortLinePalette(yc);
  }

  void ImageConv_Pixel16_2::pixelStoreCallback(void *userData, int xc, int yc,
                                               float y, float u, float v)
  {
    ImageConv_Pixel16_2&  this_ =
        *(reinterpret_cast<ImageConv_Pixel16_2 *>(userData));
    xc = xc >> 2;
    yc = yc >> 1;
    if (xc < 0 || xc >= this_.width || yc < 0 || yc >= this_.height)
      return;
    limitYUVColor(y, u, v);
    this_.inputImage.y(xc, yc) += (y * 0.125f);
    this_.inputImage.u(xc, yc) += (u * 0.125f);
    this_.inputImage.v(xc, yc) += (v * 0.125f);
  }

  void ImageConv_Pixel16_2::pixelStoreCallbackI(void *userData, int xc, int yc,
                                                float y, float u, float v)
  {
    ImageConv_Pixel16_2&  this_ =
        *(reinterpret_cast<ImageConv_Pixel16_2 *>(userData));
    xc = xc >> 2;
    if (xc < 0 || xc >= this_.width || yc < 0 || yc >= this_.height)
      return;
    limitYUVColor(y, u, v);
    this_.inputImage.y(xc, yc) += (y * 0.25f);
    this_.inputImage.u(xc, yc) += (u * 0.25f);
    this_.inputImage.v(xc, yc) += (v * 0.25f);
  }

  ImageConv_Pixel16_2::ImageConv_Pixel16_2()
    : ImageConverter(),
      width(1),
      height(1),
      colorErrorScale(0.5f),
      fixBiasValue(0x00),
      inputImage(1, 1),
      ditherErrorImage(1, 1),
      convertedImage(1, 1),
      palette(16, 1),
      conversionQuality(3),
      borderColor(0x00),
      ditherType(1),
      ditherDiffusion(0.95f)
  {
    for (int i = 0; i < 8; i++)
      fixedColors[i] = false;
    initializePalettes();
  }

  ImageConv_Pixel16_2::~ImageConv_Pixel16_2()
  {
  }

  bool ImageConv_Pixel16_2::processImage(
      ImageData& imgData, const char *infileName,
      YUVImageConverter& imgConv, const ImageConvConfig& config)
  {
    width = config.width << 2;
    height = ((imgData[5] & 0x80) == 0 ? config.height : (config.height << 1));
    colorErrorScale = float(config.colorErrorScale);
    conversionQuality = config.conversionQuality;
    borderColor = config.borderColor & 0xFF;
    float   borderY = 0.0f;
    float   borderU = 0.0f;
    float   borderV = 0.0f;
    convertEPColorToYUV(borderColor, borderY, borderU, borderV);
    inputImage.setBorderColor(borderY, borderU, borderV);
    ditherType = config.ditherType;
    limitValue(ditherType, 0, 5);
    ditherDiffusion = float(config.ditherDiffusion);

    inputImage.resize(width, height);
    ditherErrorImage.resize(width, height);
    convertedImage.resize(width, height);
    palette.resize(16, height);
    inputImage.clear();
    ditherErrorImage.clear();
    convertedImage.clear();
    palette.clear();

    initializePalettes();
    setFixBias(0);
    for (int i = 0; i < 8; i++)
      fixedColors[i] = (config.paletteColors[i] >= 0);
    for (int yc = 0; yc < height; yc++) {
      randomizePalette(yc, yc + 1000);
      for (int i = 0; i < 8; i++) {
        if (fixedColors[i])
          palette[yc][i] = (unsigned char) (config.paletteColors[i] & 0xFF);
      }
    }

    if (!(imgData[5] & 0x80))
      imgConv.setPixelStoreCallback(&pixelStoreCallback, (void *) this);
    else
      imgConv.setPixelStoreCallback(&pixelStoreCallbackI, (void *) this);
    if (!imgConv.convertImageFile(infileName))
      return false;

    progressMessage("Converting image");
    setProgressPercentage(0);
    int     optimizeLevel = 1 + ((conversionQuality - 1) >> 1);
    if (config.paletteResolution != 0) {
      // generate optimal palette independently for each line
      int     progressCnt = 0;
      int     progressMax =
          (config.fixBias < 0 ?
           (height * (((optimizeLevel + 1) * optimizeLevel) / 2))
           : (height * optimizeLevel));
      for (int l = (config.fixBias < 0 ? 0 : (optimizeLevel - 1));
           l < optimizeLevel;
           l++) {
        ditherErrorImage.clear();
        int     bestFixBias = 0;
        if (config.fixBias < 0) {
          double  bestError = 1000000000.0;
          for (int fb = 0; fb < 32; fb++) {
            setFixBias(fb);
            double  err = 0.0;
            for (int yc = 0;
                 yc < height && err < (bestError * 1.000001);
                 yc++) {
              if (l == 0)
                optimizeLinePalette_fast(yc);
              err += calculateLineError(yc);
            }
            if (err < bestError) {
              bestFixBias = fb;
              bestError = err;
            }
          }
        }
        else {
          bestFixBias = config.fixBias & 0x1F;
        }
        setFixBias(bestFixBias);
        for (int yc = 0; yc < height; yc++) {
          if (!setProgressPercentage((progressCnt * 100) / progressMax))
            return false;
          optimizeLinePalette(yc, l + 1);
          ditherLine(convertedImage, inputImage, ditherErrorImage, yc,
                     ditherType, ditherDiffusion,
                     colorErrorScale, &(palette[yc][0]), 16,
                     paletteY, paletteU, paletteV);
          progressCnt += (l + 1);
        }
      }
    }
    else {
      // generate optimal palette for the whole image
      if (config.fixBias >= 0) {
        setFixBias(config.fixBias & 0x1F);
      }
      else {
        int     bestFixBias = 0;
        double  bestError = 1000000000.0;
        for (int fb = 0; fb < 32; fb++) {
          setFixBias(fb);
          double  err = calculateTotalError(-1, (unsigned char *) 0,
                                            (double *) 0, bestError);
          if (err < bestError) {
            bestFixBias = fb;
            bestError = err;
          }
        }
        setFixBias(bestFixBias);
      }
      if (optimizeImagePalette(optimizeLevel, (config.fixBias < 0)) < -0.5)
        return false;
      for (int yc = 0; yc < height; yc++) {
        ditherLine(convertedImage, inputImage, ditherErrorImage, yc,
                   ditherType, ditherDiffusion,
                   colorErrorScale, &(palette[0][0]), 16,
                   paletteY, paletteU, paletteV);
      }
    }
    imgData.setBorderColor(borderColor);
    for (int yc = 0; yc < height; yc++) {
      imgData.setFixBias(yc, fixBiasValue);
      for (int i = 0; i < 8; i++)
        imgData.setPaletteColor(yc, i, palette[yc][i]);
      for (int xc = 0; xc < width; xc++)
        imgData.setPixel(xc, yc, convertedImage[yc][xc]);
    }
    setProgressPercentage(100);
    progressMessage("");
    char    tmpBuf[64];
    if (config.paletteResolution != 0) {
      std::sprintf(&(tmpBuf[0]), "Done; bias = %d", fixBiasValue);
    }
    else {
      std::sprintf(&(tmpBuf[0]),
                   "Done; bias = %d, palette = %d %d %d %d %d %d %d %d",
                   fixBiasValue, int(palette[0][0]), int(palette[0][1]),
                   int(palette[0][2]), int(palette[0][3]), int(palette[0][4]),
                   int(palette[0][5]), int(palette[0][6]), int(palette[0][7]));
    }
    progressMessage(&(tmpBuf[0]));
    return true;
  }

}       // namespace Ep128ImgConv

