/* pixel.c
 * This file is part of Amsam photo cropping program
 * Copyright 2021, 2023, 2024, 2025, 2026 Nandakumar Edamana
 * Distributed under GNU General Public License, version 3
 */ 

#include <assert.h>
#include <stdarg.h>
#include <stdbool.h>

#include "pixel.h"


Pixel pixel_default()
{
	return (Pixel) { { 0, 0, 0, 0 } };
}

LinearPixel linear_pixel_default()
{
	return (LinearPixel) { { 0, 0, 0, 0 } };
}

void linear_pixel_assert(LinearPixel pixel)
{
	#ifdef DEBUG
	for (int i = 0; i < 4; i += 1) {
		assert(pixel.rgb[i] <= 1 && pixel.rgb[i] >= 0);
	}

	#endif
}

LinearPixel linear_rgbapixel_from_linear_rgbpixel(LinearPixel pixel, double a)
{
	linear_pixel_assert(pixel);
	for (int i = 0; i < 3; i += 1) {
		pixel.rgb[i] = pixel.rgb[i] * a;
	}

	pixel.rgb[3] = a;

	linear_pixel_assert(pixel);
	return pixel;
}

double linear2srgb(double clin)
{
	double _tmp_1;
	if (clin <= 0.0031308) {
		_tmp_1 = clin * 12.92;
	} else {
		_tmp_1 = pow(clin, 1 / 2.4) * 1.055 - 0.055;
	}

	return _tmp_1;
}

double srgb2linear(double csrgb)
{
	double _tmp_1;
	if (csrgb <= 0.04045) {
		_tmp_1 = csrgb / 12.92;
	} else {
		_tmp_1 = pow((csrgb + 0.055) / 1.055, 2.4);
	}

	return _tmp_1;
}

Pixel linearpixel2srgb(LinearPixel lpx)
{
	Pixel spx = (Pixel) { { 0, 0, 0, lpx.rgb[3] } };

	for (int i = 0; i < 3; i += 1) {
		spx.rgb[i] = linear2srgb(lpx.rgb[i]);
	}

	return spx;
}

LinearPixel srgbpixel2linear(Pixel spx)
{
	LinearPixel lpx = (LinearPixel) { { 0, 0, 0, spx.rgb[3] } };

	for (int i = 0; i < 3; i += 1) {
		lpx.rgb[i] = srgb2linear(spx.rgb[i]);
	}

	return lpx;
}
