/*  $Id: init_linux.cpp,v 1.35 2003/09/19 10:33:02 mbn Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  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., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
**
*/

#include "Core/precomp.h"

#include <libgen.h>
#include <unistd.h>
#include <dlfcn.h>
#include <errno.h>
#include <dirent.h>
#include <signal.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include "implementation.h"
#include "appconf.h"
#include "init_linux.h"
// note: this cannot be replaced by <ctime>! (timeval needs to be defined)
#include <sys/time.h>
#include "API/Core/System/setupcore.h"
#include "API/Core/System/system.h"

static int init_ref_count = 0;
long _begin_time;

void init_system()
{
	init_ref_count++;
	if (init_ref_count > 1) return;

	timeval tv;
	gettimeofday(&tv, NULL);
	_begin_time = (long) tv.tv_sec*(long) 1000+(long) tv.tv_usec/(long) 1000;

	#ifdef NDEBUG
	signal(SIGSEGV, deinit);
	#endif
}

void deinit_system()
{
	init_ref_count--;
	if (init_ref_count > 0) return;

	#ifdef NDEBUG
	signal(SIGSEGV,SIG_DFL); //restore default behavior
	#endif
}

unsigned int CL_System::sys_time()
{
	timeval tv;
	gettimeofday(&tv, NULL);

	return (long) tv.tv_sec*(long) 1000 + (long) tv.tv_usec/(long) 1000 - _begin_time;
}

void CL_System::sleep(int millis)
{
	timeval tv;
	tv.tv_sec = millis/1000;
	tv.tv_usec = (millis%1000)*1000;
	select(0, 0, 0, 0, &tv);
}

std::string CL_System::get_exe_path()
{
	char exe_file[PATH_MAX];
	if (readlink("/proc/self/exe", exe_file, PATH_MAX) < 0)
	{
		throw CL_Error(strerror(errno));
	}
	else
	{
		return std::string(dirname(exe_file)) + "/";
	}
}

/* EOF */
