/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 * Copyright (C) 2024  Thomas Kolb
 */

#include <stdio.h>

#include <layer1/correlator.h>

#define ARRAY_LEN(x) (sizeof(x) / sizeof(x[0]))

static const float complex SEARCH_SEQ[5] = {-1, 1, 1, -1, 1};
static const float complex INPUT_SEQ[10] = {1, 1, -1, 1, -1, 1, 1, -1, 1, -1};

int main(void)
{
	correlator_ctx_t c;

	float complex output_seq[ARRAY_LEN(INPUT_SEQ)];

	if(!correlator_init(&c, SEARCH_SEQ, ARRAY_LEN(SEARCH_SEQ))) {
		fprintf(stderr, "Failed to initialize the correlator!\n");
		return 1;
	}

	for(size_t i = 0; i < ARRAY_LEN(INPUT_SEQ); i++) {
		output_seq[i] = correlator_step(&c, INPUT_SEQ[i]);
		printf("%3zu   %.3f+%.3fj    %.3f+%.3fj", i,
				creal(INPUT_SEQ[i]), cimag(INPUT_SEQ[i]),
				creal(output_seq[i]), cimag(output_seq[i]));

		if(cabsf(output_seq[i]) > ((size_t)ARRAY_LEN(SEARCH_SEQ) - 0.5f)) {
			printf(" <<< found!\n");

			const complex float *search_seq_conj = correlator_get_conj_search_sequence(&c);

			complex float history[ARRAY_LEN(SEARCH_SEQ)];
			correlator_get_input_history(&c, history);

			printf("    Search sequence: ");
			for(size_t i = 0; i < ARRAY_LEN(SEARCH_SEQ); i++) {
				printf("%.3f%+.3fj ", crealf(search_seq_conj[i]), cimagf(search_seq_conj[i]));
			}
			printf("\n    Input history:   ");
			for(size_t i = 0; i < ARRAY_LEN(SEARCH_SEQ); i++) {
				printf("%.3f%+.3fj ", crealf(history[i]), cimagf(history[i]));
			}
		}

		printf("\n");
	}

	correlator_free(&c);

	return 0;
}