#ifndef SUPPORT_H
#define SUPPORT_H

/*
 * @(#)Support.h
 *
 * This file is part of webCDwriter - Network CD/DVD Writing.
 *
 * Copyright (C) 1999-2004 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 */

#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "Exception.h"
#include "Types.h"

inline int
max(int a, int b) {
	if (a > b)
		return a;
	else
		return b;
}

inline int
min(int a, int b) {
	if (a < b)
		return a;
	else
		return b;
}

inline void
setCloseOnExec(int fd) {
	int oldflags = fcntl(fd, F_GETFD, 0);
	if (oldflags < 0)
		return;
	oldflags |= FD_CLOEXEC;
	fcntl(fd, F_SETFD, oldflags);
}

inline char *
replace(char *str, const char *key, const char *by) {
	char *str2 = strstr(str, key);
	if (str2 == NULL)
		return NULL;
	char *str3 = str2 + strlen(key);
	int diff = strlen(by) - strlen(key);
	memmove(str3 + diff, str3, strlen(str3) + 1);
	strncpy(str2, by, strlen(by));
	return str;
}

inline char *
replace(char *str, const char *key, int by) {
	char byStr[20];
	sprintf(byStr, "%d", by);
	return replace(str, key, byStr);
}

inline const char *
secondsToString(time_t t, char *str) {
	struct tm *tm = gmtime(&t);
	sprintf(str, "%02d:%02d:%02d",
		tm->tm_hour, tm->tm_min, tm->tm_sec);
	return str;
}

inline char *
strCat(const char *str1, const char *str2) {
	char *newStr = new char[strlen(str1) + strlen(str2) + 1];
	strcpy(newStr, str1);
	strcat(newStr, str2);
	return newStr;
}

inline char *
strDup(const char *str) {
	char *newStr = new char[strlen(str) + 1];
	strcpy(newStr, str);
	return newStr;
}

inline long int toInteger(const char *str, int base = 10) {
	char *endPtr;
	int n = strtol(str, &endPtr, base);
	if (*endPtr == '\0')
		return n;
	else
		throw new Exception("invalid integer value");
}

boolean
toBoolean(const char *str);

void
makeDirs(const char *fileName);

#endif
