/* jpeg-write.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 "jpeg-write.h"


VaraFileIOError write_raw_jpeg_document_to_fp(RawJpegDocument *rawjpeg, int offx, int offy, int outw, int outh, FILE *fp, const char *path)
{
	fprintf(stderr, "TODO FIXME IMPORTANT define a custom error handler or libjpeg will call exit()\n");

	struct jpeg_compress_struct jcomp;
	struct jpeg_error_mgr jerr;

	jcomp.err = jpeg_std_error(&jerr);
	jpeg_create_compress(&jcomp);
	jpeg_stdio_dest(&jcomp, fp);

	jcomp.image_width = (unsigned int) outw;
	jcomp.image_height = (unsigned int) outh;
	jcomp.input_components = 3;

	jcomp.in_color_space = JCS_RGB;

	jpeg_set_defaults(&jcomp);
	jpeg_set_quality(&jcomp, 100, true);

	jpeg_start_compress(&jcomp, true);

	unsigned char *outline = (unsigned char *) calloc((size_t) (3 * outw), sizeof(unsigned char));
	if (outline == NULL) {
		perror(NULL);
		exit(EXIT_FAILURE);
	}

	unsigned char *outlines[1] = { outline };

	for (int y = offy; y < offy + outh; y += 1) {
		unsigned char *srcline = rawjpeg->lines[y];
		memcpy(outline, srcline + 3 * offx, (size_t) (3 * outw));
		jpeg_write_scanlines(&jcomp, outlines, 1);
	}

	jpeg_finish_compress(&jcomp);
	jpeg_destroy_compress(&jcomp);

	if (outline) {
		free(outline);
	}

	return VARA_FILE_IO_ERROR_SUCCESS;
}
