# What's wrong with my M-ary ASK modulation demodulation MATLAB code?

My MATLAB code linked below implements ASK modulation of an M-ary signal, impresses it on a carrier, adds AWG noise of various SNRs. Then, for each SNR, demodulates the signal and calculates the Symbol Error Rate (SER). Finally, it plots two $$10\log_{10}(E_{bav}/N_0)$$ vs. SER graphs, as shown in the image. One of the graphs (red) is obtained from the the theoretically calculated SER from the equation, $$\text{SER} = \frac{2(M-1)}{M}Q\left( \sqrt{\frac{6 \log_2(M)E_{bav}}{(M^2-1)N_0}} \right)$$ $$E_{bav}$$ being the average energy per bit and $$N_0/2$$ being the variance of the added noise. Another graph (blue) is obtained by plotting the SER obtained from the code's demodulation scheme.

My questions are

1. What's wrong with my code that the two graphs are way apart?
2. Why even the theoretical curve does not give accurate values? (I checked it from a book)
3. Is my calculation of $$N_0$$ (Line 41, 42) correct?
4. Is my calculation of the basis function $$\psi(t)$$ (Line 35) and the expected cross correlator output (Line 36) correct? I calculated $$E_g=T_s$$ in these cases from $$E_g = \int_0^{T_s}g_T^2(t) dt = \int_0^{T_s}dt=T_s$$ by assuming the arbitrary pulse $$g_T(t)$$ based on which the the modulated waveforms are created is given by $$g_T(t)= \begin{cases} 1 ~\text{for}~ 0 \le t \le T_s\\ 0 ~\text{otherwise}\end{cases}$$ Wrong assumption ?