// 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.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;

using Hiperscan.Spectroscopy;


namespace Hiperscan.Spectroscopy.IO
{

    public static class AdcCharacteristic
    {
        public static DataSet Read(string fname)
        {
            CultureInfo culture = CultureInfo.CurrentCulture;
            Regex regex = new Regex(culture.TextInfo.ListSeparator);

            var x = new List<double>();
            var y = new List<double>();
            
            using (StreamReader reader = new StreamReader(fname))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (string.IsNullOrEmpty(line.Trim()) || line.StartsWith("#", StringComparison.InvariantCulture))
                        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);
            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);
        }
    }
}