#-------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
#-------------------------------------------------------------

# The Image Rotate function rotates the input image counter-clockwise around the center.
# Uses nearest neighbor sampling.
#
# INPUT:
# -----------------------------------------------------------------------------------------------
# img_in      Input image as 2D matrix with top left corner at [1, 1]
# radians     The value by which to rotate in radian.
# fill_value  The background color revealed by the rotation
# -----------------------------------------------------------------------------------------------
#
# OUTPUT:
# ---------------------------------------------------------------------------------------------
# img_out   Output image as 2D matrix with top left corner at [1, 1]
# ---------------------------------------------------------------------------------------------

m_img_rotate = function(Matrix[Double] img_in, Double radians, Double fill_value) return (Matrix[Double] img_out) {
  # Translation matrix for moving the origin to the center of the image
  t1 = matrix("1 0 0 0 1 0 0 0 1", rows=3, cols=3)
  t1[1, 3] = -ncol(img_in) / 2
  t1[2, 3] = -nrow(img_in) / 2

  # Translation matrix for moving the origin back to the top left corner
  t2 = matrix("1 0 0 0 1 0 0 0 1", rows=3, cols=3)
  t2[1, 3] = ncol(img_in) / 2
  t2[2, 3] = nrow(img_in) / 2

  # The rotation matrix around the origin
  rot = matrix("1 0 0 0 1 0 0 0 1", rows=3, cols=3)
  c = cos(radians)
  s = sin(radians)
  rot[1, 1] = c
  rot[1, 2] = s
  rot[2, 1] = -s
  rot[2, 2] = c

  # Combined transformation matrix
  m = t2 %*% rot %*% t1

  # Transform image
  img_out = img_transform(img_in, ncol(img_in), nrow(img_in), as.scalar(m[1,1]), as.scalar(m[1,2]), as.scalar(m[1,3]), as.scalar(m[2,1]), as.scalar(m[2,2]), as.scalar(m[2,3]), fill_value)
}
