/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "image.h"

#ifndef  STB_IMAGE_IMPLEMENTATION
  #define STB_IMAGE_IMPLEMENTATION
  #include <stb_image.h>
#endif

#ifndef  STB_IMAGE_RESIZE_IMPLEMENTATION
  #define STB_IMAGE_RESIZE_IMPLEMENTATION
  #include <stb_image_resize.h>
#endif

#ifndef  STB_IMAGE_WRITE_IMPLEMENTATION
  #define STB_IMAGE_WRITE_IMPLEMENTATION
  #include <stb_image_write.h>
#endif

void imageCopy(
  uint8_t *source, int32_t sourceWidth, int32_t sourceHeight,
  uint8_t *dest, int32_t destWidth, int32_t destHeight,
  int32_t cropX, int32_t cropY, int32_t cropWidth, int32_t cropHeight,
  int32_t pasteX, int32_t pasteY,
  int32_t channels
) {
  int32_t x, y, c;
  int32_t absX, absY;
  int32_t sourceIndex, targetIndex;

  if(cropX == -1) cropX = 0;
  if(cropY == -1) cropY = 0;
  if(cropWidth == -1) cropWidth = sourceWidth;
  if(cropHeight == -1) cropHeight = sourceHeight;
  if(pasteX == -1) pasteX = 0;
  if(pasteY == -1) pasteY = 0;

  for(x = cropX; x < cropX + cropWidth; x++) {
    for(y = cropY; y < cropY + cropHeight; y++) {
      absX = x - cropX + pasteX;
      absY = y - cropY + pasteY;
      if(absX >= destWidth || absY >= destHeight || absX < 0 || absY < 0)continue;
      targetIndex = absY * destWidth + absX;
      sourceIndex = y * sourceWidth + x;
      for(c = 0; c < channels; c++) {
        dest[(targetIndex*channels) + c] = source[(sourceIndex*channels) + c];
      }
    }
  }
}