% 12.215 Script M-file to look at GPS correlations
%
% setup a dialog box with the parameters we need
clear all
prompt = {'Seed', 'Signal GPS1', 'Signal GPS2', ...
	'Noise Level', 'Delay 1', ...
	'Delay 2', };
name = 'GPS Code Simulator';
nlines = 1;
defaults = {'1','1','1','1.0','10','-20'};
% Get user inputs and save in the appropriate valuyes
result = inputdlg(prompt,name,nlines, defaults,'on');
seed = eval(result{1});
S1 = eval(result{2}) ; % Signal strength of GPS1
S2 = eval(result{3}) ; % Signal strength of GPS2
Noise = eval(result{4}) ;  % Level of the Noise (Gaussian)
% If the noise is >15 time the signal the correlation will tend to fail.

% In this version of the code the lag is an integer value
% A more complete simulation would allow fractional lags
D1 = eval(result{5}); % Lag of GPS signal 1
D2 = eval(result{6}); % Lag of GPS signal 2
%
% reset the state of the random number generator
randn('state',seed);
% Fake C/A code on GPS 1 (bi-mode)
C1 = randn(1,1024);
for i = 1:1024;
    if( C1(i) < 0 ) 
        C1(i) = -S1;
    else
        C1(i) = +S1;
    end
end
% Generate Fake signal on GPS 2
C2 = randn(1,1024);
for i = 1:1024;
    if( C2(i) < 0 ) 
        C2(i) = -S2;
    else
        C2(i) = +S2;
    end
end
% Now generate the signals from GPS (Repeating code eveb 1024 chips)
X1 = [ C1 C1 C1 C1 C1 C1];
X2 = [ C2 C2 C2 C2 C2 C2];

% Now generate the signals
% Generate a noise vector (Noise is the amplitude of the noise)
% (Generate at half the length of the repeated codes so that we can get the
% sigmal lags (both positive and negative)
N = randn(1,length(X1)/2)*Noise;
signal = N + X1(2048+D1:2047+D1+length(N)) + X2(2048+D2:2047+D2+length(N));
%
% Correlate the signal with the code values
figure(1)
lenS = length(signal);
corr1 = xcor(X1(1024:1023+lenS),signal,lenS/2,'coeff');

plot([-lenS/2:lenS/2],corr1);
xlabel('Lag time'); ylabel('Correlation');
% Get the time of maxiumum correlation
[MaxC1 LagC1] = max(corr1);
Lag1 = LagC1 - lenS/2 -1;  % Index is from -num_lags to +num_lags
titl1 = sprintf('Code 1 Estimated Lag %d Input Lag %d Noise %6.1f', ...
    Lag1, D1, Noise)
title(titl1);
%print -dpng -r72 GPSSim_fig1.png

figure(2)
corr2 = xcor(X2(1024:1023+lenS),signal,lenS/2,'coeff');

plot([-lenS/2:lenS/2],corr2,'g');
xlabel('Lag time'); ylabel('Correlation');
% Get the time of maxiumum correlation
[MaxC2 LagC2] = max(corr2);
Lag2 = LagC2 - lenS/2 -1;
titl2 = sprintf('Code 2: Estimated Lag %d Input Lag %d Noise %6.1f', ...
    Lag2, D2, Noise)
title(titl2);
%print -dpng -r72 GPSSim_fig2.png

% As an example now plot the signal
figure(3)
plot(signal,'r'); hold on; plot(X1(1024:1023+lenS),'k');
ylabel('Time'); xlabel('Signal'); title('Data and GPS code signal');
hold off;
%print -dpng -r72 GPSSim_fig3.png


