/*
// Copyright 2005 Robert Edele.

// e-mail: yartrebo@earthlink.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 Public License for more
// details.

// You should have reveived 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

// __________________________________________________________________________
// | Robert Edele                                           Fri. 4-Feb-2005 |
// | This program loads a .tga file from the trainer program and applies    |
// | the inverse transform needed to remove the tv logo.                    |
// |________________________________________________________________________|
*/

#include <stdlib.h>
#include <stdio.h>

#define max(x,y) (x>y?x:y)
#define min(x,y) (x>y?y:x)
#define correct_gamma(x) (pow(x / 256, GAMMA_POWER) * 256)
#define get_red(image, x, y) ((double) (image->red[((y) * image->width) + (x)]))
#define get_green(image, x, y) ((double) (image->green[((y) * image->width) + (x)]))
#define get_blue(image, x, y) ((double) (image->blue[((y) * image->width) + (x)]))
#define get_alpha(image, x, y) ((double) (image->alpha[((y) * image->width) + (x)]))
#define get_char_red(image, x, y) ((unsigned char) (image->red[((y) * image->width) + (x)]))
#define GAUSSIAN_SIZE 9
#define GAUSSIAN_MASK_SIZE ((GAUSSIAN_SIZE * 2) + 1)
#define GAUSSIAN_DECAY_RATE .98
#define hypot(x, y) (sqrt(((x) * (x)) + ((y) * (y))))

double gaussian_mask[GAUSSIAN_MASK_SIZE][GAUSSIAN_MASK_SIZE];

void initialize_gaussian_mask()
{
  int i;
  int n;
  double x;
  /* Generate unnormalized gaussian mask. Because we will always exclude some pixels, it will have to be normalized every time anyway, so why lose precision? */
  for (i = 0; i <= GAUSSIAN_SIZE; i++)
  {
    for (n = 0; n <= i; n++)
    {
      x = pow(GAUSSIAN_DECAY_RATE, hypot((double) i, (double) n) * hypot((double) i, (double) n));
      gaussian_mask[GAUSSIAN_SIZE + i][GAUSSIAN_SIZE + n] = x;
      gaussian_mask[GAUSSIAN_SIZE + i][GAUSSIAN_SIZE - n] = x;
      gaussian_mask[GAUSSIAN_SIZE - i][GAUSSIAN_SIZE + n] = x;
      gaussian_mask[GAUSSIAN_SIZE - i][GAUSSIAN_SIZE - n] = x;
      gaussian_mask[GAUSSIAN_SIZE + n][GAUSSIAN_SIZE + i] = x;
      gaussian_mask[GAUSSIAN_SIZE - n][GAUSSIAN_SIZE + i] = x;
      gaussian_mask[GAUSSIAN_SIZE + n][GAUSSIAN_SIZE - i] = x;
      gaussian_mask[GAUSSIAN_SIZE - n][GAUSSIAN_SIZE - i] = x;
    }
  }

  return;
}

void error(const char * message)
{
  fprintf(stderr, message);
  exit(1);
}

void write_tga_header (FILE * output, unsigned short int width, unsigned short int height)
{
  fputc(0, output);
  fputc(0, output);
  fputc(2, output);
  fputc(0, output);
  fputc(0, output);
  fputc(0, output);
  fputc(0, output);
  fputc(0, output);
  fputc(0, output);
  fputc(0, output);
  fputc(0, output);
  fputc(0, output);
  fputc(width & 0xFF, output);
  fputc(width >> 8, output);
  fputc(height & 0xFF, output);
  fputc(height >> 8, output);
  fputc(32, output);
  fputc(0, output);

  return;
}

typedef struct
{
  unsigned short int width;
  unsigned short int height;

  unsigned char * red;
  unsigned char * green;
  unsigned char * blue;
  unsigned char * alpha;

} tga_structure;

void get_gaussian_color(double * red_out, double * green_out, double * blue_out, const tga_structure * logo_mask, const tga_structure * image, const int x, const int y)
{
  if (get_char_red(logo_mask, x, y))
  { /* This pixel does indeed need to get its value from its neighbors using a masked gaussian blur. */
    int start_posx, start_posy, end_posx, end_posy;
    int i, j;
    double red = 0, green = 0, blue = 0, divisor = 0;
    /* Prepare our bounding rectangle and clip it if need be. */
    start_posx = max(0, x - GAUSSIAN_SIZE);
    start_posy = max(0, y - GAUSSIAN_SIZE);
    end_posx = min(image->width - 1, x + GAUSSIAN_SIZE);
    end_posy = min(image->height - 1, y + GAUSSIAN_SIZE);

    for (i = start_posx; i <= end_posx; i++)
    {
      for (j = start_posy; j <= end_posy; j++)
      {
        if (!get_char_red(logo_mask, i, j)) /* Check to see if this pixel is in the logo or not. Only use the pixel if it is not. */
        {
          double mask_value = gaussian_mask[i - start_posx][j - start_posy];

          red += mask_value * get_red(image, i, j);
          green += mask_value * get_green(image, i, j);
          blue += mask_value * get_blue(image, i, j);
          divisor += mask_value;
        }
      }
    }

    if (divisor == 0) /* This means that not a single pixel is outside of the logo, so we have no data. */
    { /* We should put some eye catching value here, to indicate the flaw to the user. */
      red = 255; /* Hot pink. Nothing more catching than this. */
      green = 0;
      blue = 255;
    }
    else /* Else we need to normalise the data using the divisor. */
    {
      *red_out = red /divisor;
      *green_out = green / divisor;
      *blue_out = blue / divisor;
    }
  }
  else /* This pixel is not supported masked, so we just copy the current pixel data without changing it. */
  {
    *red_out = get_red(image, x, y);
    *green_out = get_green(image, x, y);
    *blue_out = get_blue(image, x, y);
  }

  return;
}

tga_structure * load_tga(const char * file_name)
{
  unsigned char flags;
  int x, y;
  tga_structure * new_tga = (tga_structure *) malloc (sizeof(tga_structure));

  if (new_tga == NULL)
  {
    fprintf(stderr, "Unable to allocate memory in load_tga().\n");
    exit(1);
  }

  FILE * input;
  if((input = fopen(file_name, "rb")) == NULL)
  {
    fprintf(stderr, "Unable to open targa file %s.\n", file_name);
    exit(1);
  }

  if (fgetc(input) != 0)
    error("Identsize field in targa file must be 0.\n");
  if (fgetc(input) != 0)
    error("Indexed targa files not supported.\n");
  if (fgetc(input) != 2)
    error("Only RGB targa files are supported.\n");
  if (fgetc(input) || fgetc(input) || fgetc(input) || fgetc(input) || fgetc(input))
    error("Palletes not supported in targa files.\n");
  if (fgetc(input) || fgetc(input) || fgetc(input) || fgetc(input))
    error("Origin must be at (0, 0)\n");
  new_tga->width = fgetc(input) | (fgetc(input) << 8);
  new_tga->height = fgetc(input) | (fgetc(input) << 8);
  if (fgetc(input) != 32)
    error("Only 32 bbp images supported.\n");
  flags = fgetc(input);

  new_tga->red = (unsigned char *) malloc (sizeof(unsigned char) * new_tga->width * new_tga->height);
  new_tga->green = (unsigned char *) malloc (sizeof(unsigned char) * new_tga->width * new_tga->height);
  new_tga->blue = (unsigned char *) malloc (sizeof(unsigned char) * new_tga->width * new_tga->height);
  new_tga->alpha = (unsigned char *) malloc (sizeof(unsigned char) * new_tga->width * new_tga->height);

  if (new_tga->red == NULL || new_tga->green == NULL || new_tga->blue == NULL || new_tga->alpha == NULL)
  {
    fprintf (stderr, "Unable to malloc memory in load_tga().\n");
    exit(1);
  }

  /* Load the pixels. */
  if (flags & 0x20)
  {
    for (y = new_tga->height - 1; y >= 0; y--)
    {
      for (x = 0; x < new_tga->width; x++)
      {
        new_tga->blue[(y * new_tga->width) + x] = fgetc(input);
        new_tga->green[(y * new_tga->width) + x] = fgetc(input);
        new_tga->red[(y * new_tga->width) + x] = fgetc(input);
        new_tga->alpha[(y * new_tga->width) + x] = fgetc(input);
      }
    }
  }
  else
  {
    for (y = 0; y < new_tga->height; y++)
    {
      for (x = 0; x < new_tga->width; x++)
      {
        new_tga->blue[(y * new_tga->width) + x] = fgetc(input);
        new_tga->green[(y * new_tga->width) + x] = fgetc(input);
        new_tga->red[(y * new_tga->width) + x] = fgetc(input);
        new_tga->alpha[(y * new_tga->width) + x] = fgetc(input);
      }
    }
  }

  return new_tga;
}

int main (int argc, char * argv[])
{
  tga_structure * input;
  tga_structure * filter;
  tga_structure * filter_alpha;
  tga_structure * filter_beta;
  FILE * output;
  unsigned int x, y;

  initialize_gaussian_mask();

  if (argc != 6)
  {
    fprintf(stderr, "Usage: main filter_image.tga filter_alpha_image.tga filter_beta_image.tga input_image.tga output_image.tga\n");
    return 10;
  }

  filter = load_tga(argv[1]);
  filter_alpha = load_tga(argv[2]);
  filter_beta = load_tga(argv[3]);
  input = load_tga(argv[4]);
  output = fopen (argv[5], "wb");
  if (output == NULL)
  {
    fprintf(stderr, "Unable to open output file %s.\n", argv[3]);
    exit(2);
  }

  if (input->width != filter->width || input->height != filter->height)
    error("Filter and input images must be the same dimensions.\n");
  write_tga_header(output, input->width, input->height);

  for (y = 0; y < input->height; y++)
    for (x = 0; x < input->width; x++)
    {
      double input_red;
      double input_green;
      double input_blue;
      double right, down, left, up, down_right, down_left, up_left, up_right;
      int right_i, down_i, left_i, up_i, down_right_i, down_left_i, up_left_i, up_right_i;
      double output_red;
      double output_green;
      double output_blue;

      /* Load our input values. */
      input_red = input->red[(y * input->width) + x];
      input_green = input->green[(y * input->width) + x];
      input_blue = input->blue[(y * input->width) + x];
      right_i = filter_alpha->red[(y * input->width) + x];
      down_i = filter_alpha->green[(y * input->width) + x];
      left_i = filter_alpha->blue[(y * input->width) + x];
      up_i = filter_alpha->alpha[(y * input->width) + x];
      down_right_i = filter_beta->red[(y * input->width) + x];
      down_left_i = filter_beta->green[(y * input->width) + x];
      up_left_i = filter_beta->blue[(y * input->width) + x];
      up_right_i = filter_beta->alpha[(y * input->width) + x];

      if (filter->red[(y * input->width) + x]) /* Only process if we are in the logo. */
      {
        get_gaussian_color(&output_red, &output_green, &output_blue, filter, input, x, y);
      }
      else /* Else just copy the data. */
      {
        output_red = input_red;
        output_green = input_green;
        output_blue = input_blue;
      }

      /* Save the results. */
      fputc(output_blue, output);
      fputc(output_green, output);
      fputc(output_red, output);
      fputc(255, output);
    }

  fclose(output);

  return 0;
}
