// pngrewrite.c - part of pngrewrite
// Copyright (C) 2010 by Jason Summers

//#define PNGRW_SUPPORT_1_ARG_MODE
#define PNGRW_PALSORT_BY_FREQUENCY

#if defined(_WIN32) && !defined(__GNUC__) && !defined(PNGRW_WINDOWS)
#define PNGRW_WINDOWS
#endif

#ifdef PNGRW_WINDOWS
#include <tchar.h>
#endif

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

#ifdef PNGRW_WINDOWS
#include <io.h>
#include <fcntl.h>
#else
#include <unistd.h>
#endif

#include "libpngrewrite.h"

#ifndef PNGRW_WINDOWS
#define TCHAR char
#define _T
#define _ftprintf fprintf
#define _tcscmp   strcmp
#define _fileno   fileno
#define _tmain    main
#define _isatty   isatty
#endif

static void my_error_fn(struct pngrw_ctx *ctx, const PNGRW_CHAR *msg)
{
	_ftprintf(stderr,_T("%s\n"),msg);
}

static void my_print_fn(struct pngrw_ctx *ctx, const PNGRW_CHAR *msg)
{
	_ftprintf(stderr,_T("%s\n"),msg);
}

// For stdin/stdout, pass "-" as the filename.
static int run(const TCHAR *in_filename, const TCHAR *out_filename)
{
	struct pngrw_ctx *ctx = NULL;
	int retval=0;

	ctx = pngrw_create();
	if(!ctx) goto done;
	pngrw_set_print_fn(ctx,my_print_fn);
	pngrw_set_error_fn(ctx,my_error_fn);

#ifdef PNGRW_PALSORT_BY_FREQUENCY
	pngrw_set_sort_by_frequency(ctx,1);
#else
	pngrw_set_sort_by_frequency(ctx,0);
#endif

	// Prepare input file.
	if(!_tcscmp(in_filename,_T("-"))) {
#ifdef PNGRW_WINDOWS
		_setmode(_fileno(stdin), O_BINARY);
#endif
		if(!pngrw_read_stdio(ctx,stdin)) {
			goto done;
		}
	}
	else {
		if(!pngrw_read_filename(ctx,in_filename)) {
			goto done;
		}
	}

	if(!pngrw_optimize_image(ctx)) {
		goto done;
	}

	// Prepare output file.
	if(!_tcscmp(out_filename,_T("-"))) {
#ifdef PNGRW_WINDOWS
		_setmode(_fileno(stdout), O_BINARY);
#endif
		if(!pngrw_write_stdio(ctx,stdout)) {
			goto done;
		}
	}
	else {
		if(!pngrw_write_filename(ctx,out_filename)) {
			goto done;
		}
	}

	retval = 1;

done:
	if(ctx) pngrw_destroy(ctx);
	return retval;
}

int _tmain(int argc, TCHAR **argv)
{
	TCHAR *out_filename;
	TCHAR *in_filename;
	int ret;
	TCHAR specstamp[38]=_T("");

	if(argc==3) {
		in_filename = argv[1];
		out_filename = argv[2];
	}
#ifdef PNGRW_SUPPORT_1_ARG_MODE
	else if( argc==2 && !_isatty(_fileno(stdin)) ) {
		in_filename = _T("-");
		out_filename = argv[1];
	}
#endif
	else {
		_ftprintf(stderr, _T("pngrewrite v%s: PNG image palette optimizer%s\n"),
			pngrw_get_version_string(),
			specstamp);
#ifdef PNGRW_SUPPORT_1_ARG_MODE
        _ftprintf(stderr, _T("Usage: %s infile.png outfile.png OR |%s outfile.png\n"), argv[0], argv[0]);
#else
		_ftprintf(stderr, _T("Usage: %s infile.png outfile.png\n"), argv[0]);
#endif
		return 1;
	}

	ret = run(in_filename,out_filename);
	if(!ret) return 1;
	return 0;
}
