/*
 *                            COPYRIGHT
 *
 *  cschem - modular/flexible schematics editor - libcschem (core library)
 *  Copyright (C) 2022 Tibor 'Igor2' Palinkas
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.*
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 31 Milk Street, # 960789 Boston, MA 02196 USA
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/sch-rnd
 *    contact lead developer: http://www.repo.hu/projects/sch-rnd/contact.html
 *    mailing list: http://www.repo.hu/projects/sch-rnd/contact.html
 */

#include "config.h"

#include <librnd/core/unit.h>
#include <librnd/core/rnd_printf.h>
#include <librnd/core/error.h>

#include "csch_printf.h"

rnd_aft_ret_t RND_AFT_csch_coord = RND_AFT_error;

rnd_aft_ret_t csch_printf_app_format(gds_t *string, gds_t *spec, const char **fmt, rnd_unit_allow_t mask, rnd_unit_suffix_t suffix, rnd_aft_arg_t *arg, rnd_aft_arg_t *cookie)
{
	csch_coord_t c;
	rnd_coord_t rc;

	if (RND_AFT_csch_coord == RND_AFT_error) {
		if (sizeof(int)== sizeof(csch_coord_t))
			RND_AFT_csch_coord = RND_AFT_INT;
		else if (sizeof(long) == sizeof(csch_coord_t))
			RND_AFT_csch_coord = RND_AFT_LONG;
		else {
			rnd_message(RND_MSG_ERROR, "Can't find matching integer type for sizeof(csch_coord_t)\n");
			return RND_AFT_error;
		}
	}

	switch(**fmt) {
		case 'r':
			if (arg == NULL) return RND_AFT_csch_coord;
			rc = (RND_AFT_csch_coord == RND_AFT_INT) ? arg->i : arg->l;
			c = rc >> 10;
			goto print_coord;

		case 'c':
			if (arg == NULL) return RND_AFT_csch_coord;
			c = (RND_AFT_csch_coord == RND_AFT_INT) ? arg->i : arg->l;
			print_coord:;
			if ((suffix != RND_UNIT_NO_SUFFIX) && ((c % 1000) == 0)) {
				c /= 1000;
				switch(suffix) {
					case RND_UNIT_NO_SUFFIX: break;
					case RND_UNIT_SUFFIX: gds_append_str(spec, "ld k"); break;
					case RND_UNIT_FILE_MODE: gds_append_str(spec, "ldk"); break;
				}
			}
			else
				gds_append_str(spec, "ld");

			if (rnd_append_printf(string, spec->array, (long)c) < 0)
				return RND_AFT_error;

			return RND_AFT_csch_coord;
	}
	return RND_AFT_error;
}
