/*
   Copyright (C) 2004 by James Gregory
   Part of the GalaxyHack project
 
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.
 
   See the COPYING file for more details.
*/

#ifndef GUARD_Inlines
#define GUARD_Inlines

#include "GlobalConstants.h"

#include <cstdlib>
#include <cctype>
#include <string>
#include <cmath>
#include <algorithm>

using std::string;
using std::find_if;

//the passed argument must be a reference if this is to work with handles
//as well as pointers
template <class PointerClass>
inline void SafeDelete(PointerClass& p) {
	if (p) {
		delete p;
		p = 0;
	}
}

inline int NotSpace(char c) {
	return !std::isspace(c);
}

template <class Input_Iter>
inline int IterToInt(Input_Iter& iter, const Input_Iter& lineEnd) {
	//make a maxScriptDigits digit c-style string
	char tempArray[maxScriptDigits] = {0};

	for (int i = 0; iter != lineEnd && isdigit(static_cast<int>(*iter)) && i != maxScriptDigits; ++i) {
		tempArray[i] = *iter;
		++iter;
	}

	return atoi(tempArray);
}

//function never gets used
template <class Input_Iter>
inline int IterToLargeInt(Input_Iter& iter, const Input_Iter& lineEnd) {
	//make a 20 digit c-style string
	char tempArray[20] = {0};

	for (int i = 0; isdigit(static_cast<unsigned char>(*iter)) && iter != lineEnd && i != 20; ++i) {
		tempArray[i] = *iter;
		++iter;
	}

	return atoi(tempArray);
}

template <class Input_Iter>
inline int FindNotComment(Input_Iter& iter, const Input_Iter& lineEnd) {
	iter = find_if(iter, lineEnd, NotSpace);

	//ignore empty lines and comments and labels
	if (iter == lineEnd || *iter == '#')
		return 0;
	else
		return 1;
}

inline int Min(int a, int b) {
	return a < b ? a : b;
}

inline int Max(int a, int b) {
	return a > b ? a : b;
}

//used by projectiles because for them working out distance is only for visual effect
//and so accuracy is not so important as speed of execution
inline float FastDist(float xf, float yf) {
	int x = abs(static_cast<int>(xf));
	int y = abs(static_cast<int>(yf));

	int min = Min(x, y);

	return static_cast<float>((x + y - (min >> 1) - (min >> 2) + (min >> 4)));
}

inline int SlowDist(int x, int y) {
	float z = static_cast<float>(x*x + y*y);
	return static_cast<int>(std::sqrt(z));
}

inline char* c_strNC(const string& theString) {
	char* ret = new char[theString.length()+1];
	ret[theString.copy(ret, string::npos)] = 0;

	return ret;
}

#endif


