/*
 * imageTrigTable.cpp
 *
 *  Created on: 12/06/2013
 *      Author: timothyw
 */

#include "thermal_blobber/imageTrigTable.h"

namespace casualty {

_ImageTrigTable::_ImageTrigTable(unsigned int width, unsigned int height, Size2D fov) :
		width(width), height(height), fov(fov.width, fov.height)
{
	// Location of the central pixel
	double cx = ((double)width)/2.0;
	double cy = ((double)height)/2.0;

	// Field of view (deflection) in each dimension (note that these are measured from the centerline).
	// Note that the aspect ratio of the field of view is OPPOSITE to that of the actual pixels.
//	double xView = 25;//22.5;
//	double yView = 22;//19.5;
//	double xd = (double)xView*3.14156/180.0;
//	double yd = (double)yView*3.14156/180.0;

	double xd = fov.width / 2;
	double yd = fov.height / 2;

	if (width == 0) {
		tx = sintx = costx = NULL;
	} else {
		tx = (double *)malloc(width * sizeof(double));
		sintx = (double *)malloc(width * sizeof(double));
		costx = (double *)malloc(width * sizeof(double));
		tantx = (double *)malloc(width * sizeof(double));

		// Determine the horizontal angle from the centre that each image column
		// represents and pre-calculates sine and cosine
		unsigned int ix;
		for (ix = 0; ix < width; ix++)
		{
			double fd = (width-cx)/tan(xd);
			tx[ix] = atan2((ix-cx),fd);
			sintx[ix] = sin(tx[ix]);
			costx[ix] = cos(tx[ix]);
			tantx[ix] = tan(tx[ix]);
		}
	}

	if (height == 0) {
		ty = sinty = costy = NULL;
	} else {
		ty = (double *)malloc(height * sizeof(double));
		sinty = (double *)malloc(height * sizeof(double));
		costy = (double *)malloc(height * sizeof(double));
		tanty = (double *)malloc(height * sizeof(double));

		// Determine the vertical angle from the centre that each image row
		// represents and pre-calculates sine and cosine
		unsigned int iy;
		for (iy = 0; iy < height; iy++)
		{
			double fd = (height-cy)/tan(yd);
			ty[iy] = atan2((iy-cy),fd);
			sinty[iy] = sin(ty[iy]);
			costy[iy] = cos(ty[iy]);
			tanty[iy] = tan(ty[iy]);
		}
	}
}

_ImageTrigTable::~_ImageTrigTable() {
	if (sintx != NULL)
		free(sintx);
	if (costx != NULL)
		free(costx);
	if (sinty != NULL)
		free(sinty);
	if (costy != NULL)
		free(costy);
	if (tx != NULL)
		free(tx);
	if (ty != NULL)
		free(ty);
}

} // namespace casualty
