clear;
pkg load signal;

% To be included in an other file
function sig = modulate(msg, syms)
	nb_sample = columns(syms);
	sig  = zeros(1, nb_sample * length(msg));
	for i = 1:length(msg)
		sym_index = msg(i);
		l_index = 1 + (i-1) * nb_sample;
		h_index = i * nb_sample;
		sig(l_index:h_index) = syms(sym_index,:);
	end
endfunction

% To be included in an other file
% Generate a signal with power 1 by default
function sym_array = gen_sym_array(nb_freq, FS, freq_step, nb_sample, tx_offset)
	sym_array = zeros(nb_freq, nb_sample);
	t = (1:nb_sample);
	for i = 1:nb_freq
		fstart = 0 - (nb_freq-1) / 2;
		findex = (fstart + i) * freq_step;
		sym_freq = exp(j*2*pi*((findex+tx_offset)/FS)*t);
		sym_array(i,1:nb_sample) = sym_freq;
	end
endfunction

% This function return the  a "least square calculation" of two sequence
% seq 1 <= seq2
function res = lsq(seq1, seq2)
	lseq1 = length(seq1);
	lseq2 = length(seq2);
	totlen = 2*lseq1 - 1 + lseq2;

	tmpseq2 = zeros(1, totlen);
	tmpseq2(lseq1+1:lseq1+lseq2) = seq2;
	
	nbres = lseq2 - lseq1 + 1;

	res = zeros(1, nbres);
	for i = 1:nbres
		res(i) = sum(abs(seq2(i:i-1+lseq1) .- seq1).^2);
	end
endfunction

function np = gennoise(power, len)
	np = (sqrt(1/2)*randn(1,len)+j*sqrt(1/2)*randn(1,len)) * sqrt(power);
endfunction

%function symlist = symgen()

freq_step = 6.25; % 50Hz / 8
nb_freq = 8;

FS = 100;
nb_sample = 16; % Some information talk about 160ms symbol duration

% TX Offset
tx_offset = 0;

% Generating the 8 frequencies
sym_array = gen_sym_array(nb_freq, FS, freq_step, nb_sample, tx_offset);

% FT8 is 79 symbol: 7 + 29 + 7 + 29 + 7
costas = [2 5 6 0 4 1 3];
costas = costas + 1; % Avoid 0 indexing
msg_len = 79;
data_block = 29;
msg = floor(rand(1, msg_len) * nb_freq + 1);

msg(1:7) = costas;
msg(37:43) = costas;
msg(73:79) = costas;

total_samples = msg_len * nb_sample;

signal = zeros(1,total_samples);
signal = modulate(msg, sym_array);

% Generating the 8 frequencies with 0 offset
sym_array = gen_sym_array(nb_freq, FS, freq_step, nb_sample, 0);
costas_mod = modulate(costas, sym_array);

% signal is now containing a fake frame of FT8
% needs to add noise power calculation
Pn = 0.8; % Noise power relative to signal power
signoise = signal + gennoise(Pn, length(signal));

corresigcost = xcorr(signoise, costas_mod);
plot(abs(corresigcost));

figure

lsqsig = lsq(costas_mod, signoise);
plot(lsqsig);