/*
    Tucnak - VHF contest log
    Copyright (C) 2013-2014 Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#ifndef __SDR_H
#define __SDR_H

#include "header.h"

#ifdef USE_SDR

#include "fft.h"

#include <fftw3.h>

#define SDR_BAL_N 1024

struct sdr;

struct sdr_filter{
	double zero, low, high;
	fftw_complex *fbins;
	double *window; 
	fftw_complex *window_iq;
	int window_size;
	int zero_bin;
};

struct sdr_filter *init_sdr_filter(struct sdr *, double zero, double low, double high, double samplerate, int size);
void free_sdr_filter(struct sdr_filter *f);
void sdr_filter_tune(struct sdr *sdr, double zero);



struct sdr {
    fftw_complex *iq, *bins, *iout, *qout;
	fftw_plan plan_f, plan_bi, plan_bq;
	short *sndbuf;				// buffer for soundcard, uses stereo with same channel data
    size_t samples, frames;
    int samplerate;
    int n;
    int pal[FFT_COLORS];
    int grpal[FFT_COLORS];
#ifdef Z_HAVE_SDL    
    SDL_Surface *screen;
    MUTEX_DEFINE(screen);
    int screeny; 
#endif   
    double *amp, *nea_amp;
	int amplen;
#ifdef HAVE_SNDFILE
    SNDFILE *sndfileout;
#endif
    GThread *thread;
    int thread_break;
	struct sdr_filter *filter;
    MUTEX_DEFINE(filter);
	double bfo_phase;
	double bfo_inc;
	int load;
	int butbg;
	int agc_period_ms;
	int agc_n, agc_ign, agc_ign_i;
	double agc_gain, agc_last_power;
	struct dsp *iqdsp; // SDR side
	struct dsp *afdsp; // audio
	int *wfvec;
	int wfveclen;

	double bal_gain, bal_phase;
	fftw_complex *bal_iq, *bal_bins;
	fftw_plan bal_plan;
};

extern struct sdr *gsdr;

struct sdr *init_sdr(void);
void free_sdr(struct sdr *sdr);

struct sdr *sdr_start(struct sdr *sdr);
void sdr_stop(struct sdr *sdr);

gpointer sdr_thread_func(gpointer data);

int sw_sdr_kbd_func(struct subwin *sw, struct event *ev, int fw);
int sw_sdr_mouse_func(struct subwin *sw, struct event *ev, int fw);
void sw_sdr_redraw(struct subwin *sw, struct band *band, int flags);
void sw_sdr_check_bounds(struct subwin *sw);
void sw_sdr_raise(struct subwin *sw);
void sdr_read_handler(struct sdr *sdr, gchar *str, gchar *arg);
void sdr_resize(struct sdr *sdr, struct subwin *sw);
void sdr_ssb(void *xxx);
void sdr_cw(void *xxx);
void sdr_usb(void *xxx);
void sdr_lsb(void *xxx);
void sdr_iqcomp(void *xxx);

void sdr_balance(struct sdr *sdr);
void sdr_bal_adjust(struct sdr *sdr, fftw_complex *iq, int len, double gain, double phase);


#endif
#endif
