
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "png.h"
#include "fractal.h"
#include "parse-fractal.h"

#define DEFAULT_PARAMSFILE "fractal.data"
#define DEFAULT_OUTFILE "fractal.png"

int main(int argc, char **argv)
{
	struct fractal_params *fractal;
	const char *outfile, *paramsfile;
	int opt;

	/* set up default arguments */
	paramsfile = DEFAULT_PARAMSFILE;
	outfile = DEFAULT_OUTFILE;

	/* parse arguments into datafile and outfile  */
	while ((opt = getopt(argc, argv, "p:o:")) != -1) {
		switch (opt) {
		case 'p':
			paramsfile = optarg;
			break;
		case 'o':
			outfile = optarg;
			break;
		default:
			fprintf(stderr, "Usage: %s [-p paramsfile] "
						"[-o outfile]\n", argv[0]);
			return EXIT_FAILURE;
		}
	}

	/* parse the input datafile */
	fractal = parse_fractal(paramsfile);
	if (!fractal)
		return EXIT_FAILURE;

	/* allocate our image buffer */
	fractal->imgbuf = malloc(sizeof(*fractal->imgbuf)
			* fractal->rows * fractal->cols);

	if (!fractal->imgbuf) {
		perror("malloc");
		return EXIT_FAILURE;
	}

	/* render the fractal, storing the result in the image buffer */
	render_fractal(fractal);

	/* compress and write to outfile */
	if (write_png(outfile, fractal->rows, fractal->cols, fractal->imgbuf))
		return EXIT_FAILURE;

	return EXIT_SUCCESS;
}
