text: #include <math.h>
  #include <uWS/uWS.h>
  #include <iostream>
  #include <fstream>
  #include <string>
  #include <vector>
  #include <ctime>
  #include <chrono>
  #include "json.hpp"
  #include "PID.h"
  
  // for convenience
  using nlohmann::json;
  using std::string;
  using namespace std;
  using namespace std::chrono;
  
  // For converting back and forth between radians and degrees.
  constexpr double pi() { return M_PI; }
  double deg2rad(double x) { return x * pi() / 180; }
  double rad2deg(double x) { return x * 180 / pi(); }
  
  // Checks if the SocketIO event has JSON data.
  // If there is data the JSON object in string format will be returned,
  // else the empty string "" will be returned.
  string hasData(string s) {
    auto found_null = s.find("null");
    auto b1 = s.find_first_of("[");
    auto b2 = s.find_last_of("]");
    if (found_null != string::npos) {
      return "";
    }
    else if (b1 != string::npos && b2 != string::npos) {
      return s.substr(b1, b2 - b1 + 1);
    }
    return "";
  }
  
  int main() {
    uWS::Hub h;
  
    PID pid;
    PID pid_speed;
    /**
     * TODO: Initialize the pid variable.
     */
    //pid.Init(0.1, 0.1, 4);
    
    pid.Init(0.0525, 0.003, 0.525);
    pid_speed.Init(0.01, 0.0, 0.0);
    
    int rec_count = 0;
    vector<double> rec;
    std::ofstream rec_cte;
    std::ofstream rec_wp;
    std::ofstream rec_act;
    rec_cte.open ("record_cte.csv");
    rec_wp.open ("record_waypoints.csv");
    rec_act.open ("record_actuators.csv");
    clock_t time_req;
    time_req = clock();
    auto start = std::chrono::high_resolution_clock::now();
  
    h.onMessage([&pid, &pid_speed, &rec_count, &rec, &rec_cte, &rec_wp, &rec_act, &time_req, &start](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, 
                       uWS::OpCode opCode) {
      // "42" at the start of the message means there's a websocket message event.
      // The 4 signifies a websocket message
      // The 2 signifies a websocket event
      if (length && length > 2 && data[0] == '4' && data[1] == '2') {
        auto s = hasData(string(data).substr(0, length));
  
        if (s != "") {
          auto j = json::parse(s);
  
          string event = j[0].get<string>();
  
          if (event == "telemetry") {
            // j[1] is the data JSON object
            //std::vector<double> ptsx = j[1]["ptsx"];
            double cte = std::stod(j[1]["cte"].get<string>());
            double speed = std::stod(j[1]["speed"].get<string>());
            double angle = std::stod(j[1]["steering_angle"].get<string>());
            double steer_value;
            //double speed_val;
            //double speed_error;
            double ref_speed;
            
            /**
             * TODO: Calculate steering value here, remember the steering value is
             *   [-1, 1].
             * NOTE: Feel free to play around with the throttle and speed.
             *   Maybe use another PID controller to control the speed!
             */
            ref_speed = 0.3;
            //speed_error = ref_speed - speed;
            
            pid.UpdateError(cte);
            steer_value = pid.TotalError();
            
            //pid_speed.UpdateError(speed_error);
            //speed_val = pid_speed.TotalError();
            
            //if (steer_value > 1.0){
            //  steer_value = 1.0;
            //}
            //else if (steer_value < -1.0){
            //  steer_value = -1.0;
            //}
            
            //if (speed_val > ref_speed + 0.2){
            //  speed_val = ref_speed + 0.2;
            //}
            //else if (speed_val < ref_speed - 0.2){
            //  speed_val = ref_speed - 0.2;
            //}
           
            // DEBUG
            std::cout << "CTE: " << cte << " Steering Value: " << steer_value 
                      << std::endl;
            
            auto finish = std::chrono::high_resolution_clock::now();
            auto duration = duration_cast<milliseconds>(finish - start);
            if (rec_count < 500){
            	rec_cte << duration.count() << "," << cte <<",\n";
            	rec_act << duration.count() << "," << steer_value << ",\n";
            	rec_count += 1;
            }
            else{
            	rec_cte.close();
            	rec_wp.close();
            	rec_act.close();
            	std::cout << "Files closed \n";
            }
  
            json msgJson;
            msgJson["steering_angle"] = steer_value;
            msgJson["throttle"] = ref_speed;
            auto msg = "42[\"steer\"," + msgJson.dump() + "]";
            std::cout << msg << std::endl;
            ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
          }  // end "telemetry" if
        } else {
          // Manual driving
          string msg = "42[\"manual\",{}]";
          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
        }
      }  // end websocket message if
    }); // end h.onMessage
  
    h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
      std::cout << "Connected!!!" << std::endl;
    });
  
    h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, 
                           char *message, size_t length) {
      ws.close();
      std::cout << "Disconnected" << std::endl;
    });
  
    int port = 4567;
    if (h.listen(port)) {
      std::cout << "Listening to port " << port << std::endl;
    } else {
      std::cerr << "Failed to listen to port" << std::endl;
      return -1;
    }
    
    h.run();
  }
  