package ru.r2cloud.jradio.blocks;

import java.io.IOException;

import ru.r2cloud.jradio.Context;
import ru.r2cloud.jradio.FloatInput;
import ru.r2cloud.jradio.util.MathUtils;

public class FrequencyModulator implements FloatInput {

	private final FloatInput input;
	private final float sensitivity;
	private final Context context;

	private final float[] complex = new float[2];
	private int complexIndex;
	private float phase = 0;

	public FrequencyModulator(FloatInput input, float sensitivity) {
		this.input = input;
		this.sensitivity = sensitivity;
		this.context = new Context(input.getContext());
		this.context.setChannels(2);
		this.complexIndex = complex.length;
	}

	@Override
	public float readFloat() throws IOException {
		if (complexIndex >= complex.length) {
			complexIndex = 0;

			phase = phase + sensitivity * input.readFloat();
			phase = (float) ((phase + Math.PI) % (2 * Math.PI) - Math.PI);

			int angle = MathUtils.floatToFixed(phase);
			MathUtils.sincos(angle, complex);
		}

		float result = complex[complexIndex];
		complexIndex++;
		return result;
	}

	@Override
	public void close() throws IOException {
		input.close();
	}

	@Override
	public Context getContext() {
		return context;
	}

}

@@ -57,16 +57,60 @@
 ption;%0A%0A
+import ru.r2cloud.jradio.ComplexFloatInput;%0A
 import r
@@ -250,19 +250,23 @@
 tor 
-implement
+extend
 s 
+Complex
 Floa
@@ -426,35 +426,8 @@
 2%5D;%0A
-%09private int complexIndex;%0A
 %09pri
@@ -656,46 +656,8 @@
 2);%0A
-%09%09this.complexIndex = complex.length;%0A
 %09%7D%0A%0A
@@ -684,18 +684,22 @@
 loat
+%5B%5D
  read
-Float
+Complex
 () t
@@ -722,71 +722,8 @@
 n %7B%0A
-%09%09if (complexIndex %3E= complex.length) %7B%0A%09%09%09complexIndex = 0;%0A%0A%09
 %09%09ph
@@ -769,17 +769,16 @@
 loat();%0A
-%09
 %09%09phase 
@@ -837,17 +837,16 @@
 PI);%0A%0A%09%09
-%09
 int angl
@@ -886,121 +886,154 @@
 ;%0A%09%09
-%09MathUtils.sincos(angle, complex);%0A%09%09%7D%0A%0A%09%09float result = complex%5BcomplexIndex%5D;%0A%09%09complexIndex++;%0A%09%09return result
+// for angle=0, it will produce: %5B1.0000024, 7.2191946E-9%5D%0A%09%09// outside %5B-1.0f;1.0f%5D interval%0A%09%09MathUtils.sincos(angle, complex);%0A%09%09return complex
 ;%0A%09%7D

refactor a bit