function S = S_KdV(q,L)

% function S = S_KdV(q)
% Pseudospectrally calculates the KdV spatial derivative term 6qq_x + q_xxx
% where q is assumed to be given as a row-vector of values at equally
% spaced gridpoints x(j) = (j-1)*L/N, j = 1,...,N, for some N, and q has 
% period L in x.

  N = length(q);
  qhat = fft(q);
  M = [0:(N/2-1) (-N/2):(-1)];  
  k = 2*pi*M/L;  % Wavenumbers [1xN].  
  qx = real(ifft(1i*k.*qhat));
  qxxx = real(ifft(-1i*k.^3.*qhat));
  S = 6*q.*qx + qxxx;
