#include <math.h>
#include "imageedit.h"
#include "bitimage.h"

const double MaxColor = 255.0 ;

void GammaCorrect (BitmapImage &image, double gamma)
{
  if (image.BitCount () == 24)
  {
    for (unsigned int ii = 0 ; ii < image.Height () ; ++ ii)
    {
      for (unsigned int jj = 0 ; jj < 3 * image.Width () ; ++ jj)
      {
        if (image [ii][jj] != 0)
        {
          double value = image [ii][jj] ;
          value = MaxColor * exp (gamma * log (image [ii][jj]/MaxColor)) ;
          image [ii][jj] = value + 0.5 ;
        }
      }
    }
  }
  else
  {
    for (unsigned int ii = 0 ; ii < image.ColorCount () ; ++ ii)
    {
      double value ;
      if (image.ColorMap (ii).red != 0)
      {
        value = MaxColor * exp (gamma * log (image.ColorMap (ii).red/MaxColor)) ;
        image.ColorMap (ii).red = value + 0.5 ;
      }
      if (image.ColorMap (ii).green != 0)
      {
        value = MaxColor * exp (gamma * log (image.ColorMap (ii).green/MaxColor)) ;
        image.ColorMap (ii).green = value + 0.5 ;
      }
      if (image.ColorMap (ii).blue != 0)
      {
        value = MaxColor * exp (gamma * log (image.ColorMap (ii).blue/MaxColor)) ;
        image.ColorMap (ii).blue = value + 0.5 ;
      }
    }
  }
}
