/*
 *  Load N images. Find the largest one. Create an image that size.
 *  The overlay, in order, the loaded images, centred in that image.
 *  Save that image to a new name.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "app.h"

int main(int argc, char *argv[])
{
	int i;
	Image *img = NULL;
	Image *img2;
	Image *tmp;
	Image **images;
	int x, y, dx, dy, scale;
	Rect largest, area, centred;
	Graphics *src, *dst;
	char *filename;

	images = app_zero_alloc(sizeof(Image *) * argc);

	/* Load all the images and find the largest. */
	largest = rect(0,0,0,0);
	for (i = 1; argv[i] != NULL; i++)
	{
		/* Skip command-line parameters. */
		if ((argv[i][0] == '-') && (argv[i][1] == '-')) {
			images[i] = NULL;
			continue;
		}

		/* Read the image. */
		img = app_read_image(argv[i], 32);
		images[i] = img;
		if (! img)
			continue;

		/* Update the largest image rectangle. */
		area = app_get_image_area(img);
		if (area.width > largest.width)
			largest.width = area.width;
		if (area.height > largest.height)
			largest.height = area.height;
	}
	if (largest.width == 0 || largest.height == 0)
		return 1;

	/* Create a transparent image which is large enough. */
	img2 = app_new_image(largest.width, largest.height, 32);
	if (img2 == NULL)
		return 2;

	for (y = 0; y < largest.height; y++)
	{
	 for (x = 0; x < largest.width; x++)
	 {
		img2->data32[y][x] = CLEAR;
	 }
	}

	/* Now composite the images centred. */
	dst = app_get_image_graphics(img2);
	dx = dy = 0;
	scale = 100;
	for (i = 1; argv[i] != NULL; i++)
	{
		img = images[i];
		if (img == NULL) {
			if (argv[i] == NULL)
				continue;
			if (strncmp(argv[i], "--offset=", 9) == 0)
			{
				char *comma = strstr(argv[i], ",");
				dx = atoi(argv[i]+9);
				if (comma)
					dy = atoi(comma+1);
			}
			else if (strncmp(argv[i], "--scale=", 8) == 0)
			{
				scale = atoi(argv[i]+8);
			}
			continue;
		}

		area = app_get_image_area(img);
		tmp = img;
		if (scale != 100)
		{
			tmp = app_scale_image(img,
				rect(0, 0,
					area.width * scale / 100,
					area.height * scale / 100),
				area);
			area = app_get_image_area(tmp);
		}

		x = dx + (largest.width - area.width) / 2;
		y = dy + (largest.height - area.height) / 2;

		src = app_get_image_graphics(tmp);
		app_copy_rect(dst, pt(x,y), src, area);
		app_del_graphics(src);

		if (tmp != img)
			app_del_image(tmp);

		dx = dy = 0;
		scale = 100;
	}
	app_del_graphics(dst);

	/* Save the image. */
	i = argc - 1;
	filename = app_alloc(strlen(argv[i])+20);
	sprintf(filename, "%s_composite.png", argv[i]);
	if (app_write_image(img2, filename))
		printf("Created image file: %s\n", filename);
	app_free(filename);

	return 0;
}
