// Created with MonoDevelop
//
//    Copyright (C) 2012 Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program 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 General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.



using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Globalization;

using Hiperscan.Spectroscopy;
using Hiperscan.Unix;


namespace Hiperscan.FileIO
{

	public class AdcCharacteristic
	{
		public static DataSet Read(string fname)
		{
			CultureInfo culture = CultureInfo.CurrentCulture;
			Regex regex = new Regex(culture.TextInfo.ListSeparator);
			
			List<double> x = new List<double>();
			List<double> y = new List<double>();
			
			using (StreamReader reader = new StreamReader(fname))
			{
				string line;
				while ((line = reader.ReadLine()) != null)
				{
					if (string.IsNullOrEmpty(line.Trim()) || line.StartsWith("#"))
						continue;
					
					string[] s = regex.Split(line);
					x.Add(Double.Parse(s[0],
					                   NumberStyles.AllowDecimalPoint|
					                   NumberStyles.AllowExponent,
					                   culture)
					      );
					
					y.Add(Double.Parse(s[1],
					                   NumberStyles.AllowDecimalPoint|
					                   NumberStyles.AllowExponent|
					                   NumberStyles.AllowLeadingSign,
					                   culture)
					      );
				}
			}
			
			return new DataSet(x, y);
		}
		
		public static void Write(DataSet ds, string header, string fname)
		{
			CSV.Write(ds, header, fname);
		}
		
		public static DataSet Interpolate(DataSet characteristic)
		{
			DataSet sg = characteristic.Filter(2, characteristic.Count / 3);
			// FIXME: SG-Algorithm broken?
			sg = new DataSet(characteristic.X, sg.Y);
			
			List<double> xi = new List<double>();
			for (int ix=0; ix <= 4096; ix += 512)
			{
				xi.Add((double)ix);
			}
			
			return sg.Interpolate(xi, InterpolationType.Linear);
		}
	}
}