// Copyright 2001-2003, Danger, Inc.  All Rights Reserved.
// This file is subject to the Danger, Inc. Sample Code License,
// which is provided in the file SAMPLE_CODE_LICENSE.
// Copies are also available from http://developer.danger.com/

/* The Signal object is a data state machine generator.  */

package com.danger.rocks;

import danger.system.*;
import danger.audio.*;
import danger.app.*;
import danger.ui.*;
import danger.util.*;

public class Signal
{
	static final int kSine		=	0;
	static final int kSquare	=	1;
	static final int kTriangle	=	2;

	// Create a Signal object, using an obove type and integer control values
	public Signal(int type, int startingValue, int min, int max, int step, int scale)
	{
		mType = type;

		mStartingValue = startingValue;
		mMin = Fixed.fromInt(min);
		mMax = Fixed.fromInt(max);
		mMid = Fixed.fromInt(min + ((max - min) / 2));
		mStep = Fixed.fromInt(step);
		mScale = Fixed.fromInt(scale);
		Reset();
	}

	public void Reset()
	{
		mValue = Fixed.fromInt(mStartingValue);
	}

	int Generate()
	{
		int result = 0;

		switch (mType)
		{
			case kSine:
				result = Fixed.sin(Fixed.toInt(mValue - mMin));
				result = Fixed.multiply(result, mScale) + mMin;
				break;
			case kSquare:
				if (mValue > mMid)
				{
					result = mMax;
				}
				else
				{
					result = mMin;
				}
				break;
			case kTriangle:
				if (mValue > mMid)
				{
					result = mMax - mValue;
					result = Fixed.multiply(result, Fixed.fromInt(4));
					result = result - mMax;
				}
				else
				{
					result = Fixed.multiply(mValue, Fixed.fromInt(4));
					result = result - mMax;
				}
				break;
		}
		mValue = mValue + mStep;
		if (mValue > mMax)
		{
			mValue = mMin;
		}
		return result;
	}

	public int GetIntValue()
	{
		return Fixed.toInt(Generate());
	}
	
	public int GetFixedValue()
	{
		return Generate();
	}

	// variables
	int		mType;
	int		mMin, mMax;
	int		mMid;
	int		mScale;
	int		mValue, mStep;
	int		mStartingValue;
}
