/*
 * Kangaroo Punch MultiPlayer Game Server Mark II
 * Copyright (C) 2020-2021  Scott Duensing
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */


#include "util.h"


char *utilAppNameWithNewExtensionGet(char *appName, char *extension) {
	char     *c       = NULL;
	char     *newName = NULL;
	int16_t   x       = strlen(appName);
	uint16_t  len     = 2 + strlen(extension);  // 2 = dot in extension and 0 terminator.

	// Find last portion of filename.
	while (x > 0) {
		if (appName[x] == '/' || appName[x] == '\\') break;
		x--;
		len++;
	}

	// We use this + length of new extension for new string length.
	newName = (char *)malloc(len);
	if (newName) {
		if (strlen(appName) - x < len) {
			// Replace extension
			strncpy(newName, &appName[x + 1], len - 1);
			c = strstr(newName, ".");
			if (c) *c = 0;
			strncat(newName, ".", len - 1);
			strncat(newName, extension, len - 1);
		}
	}

	return newName;
}


void utilBitsPrint(uint8_t byte) {
	int i = 0;

	for (i = 7; 0 <= i; i--) {
		printf("%c", (byte & (1 << i)) ? '1' : '0');
	}
}


char *utilCreateString(char *format, ...) {
	va_list  args;
	char    *string;

	va_start(args, format);
	string = utilCreateStringVArgs(format, args);
	va_end(args);

	return string;
}


__attribute__((__format__(__printf__, 1, 0)))
char *utilCreateStringVArgs(char *format, va_list args) {
	va_list  argsCopy;
	int32_t  size     = 0;
	char    *buffer   = NULL;

	va_copy(argsCopy, args);
	size = vsnprintf(NULL, 0, format, argsCopy) + 1;
	va_end(argsCopy);
	buffer = calloc(1, (size_t)size);
	if (buffer) {
		vsnprintf(buffer, (size_t)size, format, args);
	}

	return buffer;
}


void utilDie(const char *why, ...) {
	va_list args;
	char    msg[2048];

	va_start(args, why);
	vsprintf(msg, why, args);
	va_end(args);

	logWrite("DIE:  %s", msg);
	exit(1);
}
