//----------------------------------------------------------------------------
//	Copyright (C) 2002, 2003, 2004 Humboldt-Universitaet zu Berlin
//
//	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
//
//----------------------------------------------------------------------------
/**	\file Dist.cpp

	\author Ralf Gerstenberger

	\date created at 2003/05/09

	\brief Implementation of odemx::random::Dist

	\sa Dist.h

	\since 1.0
*/

#include <odemx/random/Dist.h>
#include <odemx/random/DistContext.h>
#include <odemx/base/Simulation.h>

namespace odemx {
namespace random {

Dist::Dist( base::Simulation& sim, const data::Label& label )
:	Producer( sim, label )
,	context( sim )
,	u( 0 )
,	ustart( 0 )
,	antithetics( 0 )
{
	u = ustart = context.getNextSeed();
}

Dist::~Dist()
{
}

void Dist::setSeed( int n )
{
	if( n < 0 )
	{
		n= -n;
	}
	if( n >= (int)zyqmodulo )
	{
		n = n - ( (int)( n / zyqmodulo ) ) * zyqmodulo;
	}
	if( n == 0 )
	{
		n = (int)( zyqmodulo / 2 );
	}
	u = ustart = n;
}

unsigned long Dist::getSeed()
{
	return ustart;
}

double Dist::getSample()
{
	int k;

	k = 32;
	u = k * u;
	if( u >= zyqmodulo )
	{
		u =  u- ((int)( u / zyqmodulo ) ) * zyqmodulo;
	}

	// yes, this is needed twice
	k = 32;
	u = k * u;
	if( u >= zyqmodulo )
	{
		u =  u- ((int)( u / zyqmodulo ) ) * zyqmodulo;
	}

	k = 8;
	u = k * u;
	if( u >= zyqmodulo )
	{
		u =  u- ((int)( u / zyqmodulo ) ) * zyqmodulo;
	}

	double help = (double)u / (double)zyqmodulo;

	double zyqSample = antithetics ? 1.0 - help : help;

	return zyqSample;
}

} } // namespace odemx::random
