using System.Collections.Generic;
using Newtonsoft.Json.Linq;

public class Graph {
	private List<Tuple<float, float>> list;

	public Graph(JObject json, string key) {
		list = new List<Tuple<float, float>>();

		JToken token;
		if (json.TryGetValue(key, out token)) {
			foreach(JObject point in json[key]) {
				addPoint((float)point["x"], (float)point["y"]);
			}
		}
	}

	private void addPoint(float x, float y) {
		list.Add(new Tuple<float, float>(x, y));
	}

	public float evaluate(float x) {
		if (list.Count == 0) {
			return 1.0f;
		}
		else if (list.Count == 1) {
			return list[0]._2;
		}
		else if (x < list[0]._1){
			return list[0]._2;
		}
		else if (x > list[list.Count-1]._1){
			return list[list.Count-1]._2;
		}
		else {
			for (int i = 0; i < list.Count - 1; i++) {
				if (x >= list[i]._1 && x <= list[i + 1]._1) {
					return ((list[i]._2 + list[i + 1]._2) / 2) * ((x - list[i]._1) / (list[i + 1]._1 - list[i]._1));
				}
			}

			return list[list.Count-1]._2; //will never happen
		}
	}
}
