/*
 *       File name:  tools/spike2sdf.cc
 *         Project:  cnrun
 *          Author:  Andrei Zavada <johnhommer@gmail.com>
 * Initial version:  2008-11-11
 *
 *         Purpose:  A remedy against forgetting to pass -d to cnrun
 *
 *         License:  GPL-2+
 */

#if HAVE_CONFIG_H && !defined(VERSION)
#  include "config.h"
#endif

#include <iostream>
#include <fstream>
#include <vector>
#include <limits>
#include <cstdlib>
#include <cstring>
#include <cmath>

using namespace std;

int
main( int argc, char *argv[])
{
        if ( argc != 5 ) {
                cerr << "Expecting <fname> <period> <sigma> <restrict_window_size\n";
                return -1;
        }

        string fname( argv[1]);

        double  sxf_sample = strtod( argv[2], nullptr),
                sdf_sigma = strtod( argv[3], nullptr),
                restrict_window = strtod( argv[4], nullptr);

        ifstream is( fname.c_str());
        if ( !is.good() ) {
                cerr << "Can't read from file " << fname << endl;
                return -1;
        }
        is.ignore( numeric_limits<streamsize>::max(), '\n');

        if ( fname.rfind( ".spikes") == fname.size() - 7 )
                fname.erase( fname.size() - 7, fname.size());
        fname += ".sdf";

        ofstream os( fname.c_str());
        if ( !os.good() ) {
                cerr << "Can't open " << fname << " for writing\n";
                return -1;
        }
        os << "#<t>\t<sdf>\t<nspikes>\n";


        vector<double> _spike_history;
        while ( true ) {
                double datum;
                is >> datum;
                if ( is.eof() )
                        break;
                _spike_history.push_back( datum);
        }

        double  at, len = _spike_history.back(), dt,
                sdf_var = sdf_sigma * sdf_sigma;
        cout << fname << ": " << _spike_history.size() << " spikes (last at " << _spike_history.back() << ")\n";
        for ( at = sxf_sample; at < len; at += sxf_sample ) {
                double result = 0.;
                unsigned nspikes = 0;
                for ( auto &T : _spike_history ) {
                        dt = T - at;
                        if ( restrict_window > 0 && dt < -restrict_window/2 )
                                continue;
                        if ( restrict_window > 0 && dt >  restrict_window/2 )
                                break;

                        nspikes++;
                        result += exp( -dt*dt/sdf_var);

                }
                os << at << "\t" << result << "\t" << nspikes << endl;
        }

        return 0;
}


// Local Variables:
// Mode: c++
// indent-tabs-mode: nil
// tab-width: 8
// c-basic-offset: 8
// End:
