function [velocity_raw, velocity_real,throttle_setting] = getRawVelocity(x,old_velocity,P,throttle_setting)

% u initial throttle setting as whole percentage
global sim_step u 
h = sim_step;
throttle_setting = (u/300) + throttle_setting;
persistent d v_dot x_v v_dot_last x_v_old 

if isempty (d) % this just Initializes
    d = 1;
    x_v = 0.25;
    x_v_old = 0.25;
    v_dot_last = 0;
end

% parameters
gear = 1.2;
final_drive = 2.82;
rs_to_rpm = 9.549; % rad/s to rpm
mps_to_mph = 2.2369;
radius = 0.3;
cd = 0.29;
roh = 1.23;
area = 2;
mass = 1854;

if abs(throttle_setting) > 100 % limit throttle to +/-100%
    throttle_setting = 100;
end

if throttle_setting < 0
    brake = abs(throttle_setting);%P;
    throttle_setting = 0;    
else
    brake = 0;
end

wheel_speed  = (old_velocity / mps_to_mph) / radius; % rad/s
engSpeedRPM = wheel_speed * rs_to_rpm * gear * final_drive;

x_v_dot = (-10 * x_v_old + 0.05 * (throttle_setting)); %internal dynamics of throttle actuator
x_v = x_v_old + x_v_dot*h; % numerical integration
x_v_old = x_v;

engSpeedRPM = 528.7 + (engSpeedRPM * 0.152) + (-0.0000217 * engSpeedRPM^2);
engine_torque = x_v * engSpeedRPM*gear * final_drive; 

%v_dot = ((engine_torque / radius) - (cd * roh * area* 0.5 * velocity^2) - (0.05 * mass * 9.81) -(brake * mass * 9.81)) / mass;
         % N wheel force                 % - aero force N
v_dot = ((engine_torque / radius) - (cd * roh * area* 0.5 * old_velocity^2) ...
    - (0.05 * mass * 9.81) -(brake * mass * 9.81)) / mass;

acc = v_dot + (h / 2) * (v_dot - v_dot_last);
v_dot_last = v_dot;
velocity = old_velocity + acc;
% old_velocity = velocity;

if velocity < 0 || isnan(velocity)
    velocity = 0;
end
if velocity > 150
    velocity = 150;
end
throttle_setting = throttle_setting + brake; % gives negative output to plot if braking
% convert into binary signal
velocity_raw = dec2bin((2^x*(velocity))/150);
velocity_real = velocity;