/*
 * sendtlm.c
 *
 * Copyright (C) 2000 Klaus Kudielka
 *
 * Soundcard-based telemetry source, simulating the experimental
 * laser source on AO-40
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/soundcard.h>
#include <stdlib.h>
#include <stdint.h>
#include "crc16.h"
#include "random.h"

#define BLOCK_LENGTH 512
#define MAX_SPEED    50000

struct param {
  int audio_fd, speed, amplitude, sigma;
  crc16_table_t crc_table;
};

int open_audio(char *name, int mode, int format, int channels, int *speed) {
  int audio_fd, tmp;

  audio_fd = open(name, mode, 0);
  if (audio_fd == -1) {
    perror(name);
    exit(1);
  }

  tmp = format;
  if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &tmp) == -1) {
    perror("SNDCTL_DSP_SETFMT");
    exit(1);
  }
  if (tmp != format) {
    fprintf(stderr, "Requested format not supported by %s.\n", name);
    exit(1);
  }

  tmp = channels;
  if (ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &tmp) == -1) {
    perror("SNDCTL_DSP_CHANNELS");
    exit(1);
  }
  if (tmp != channels) {
    fprintf(stderr, "Requested number of channels not supported by %s.\n",
	    name);
    exit(1);
  }

  if (ioctl(audio_fd, SNDCTL_DSP_SPEED, speed) == -1) {
    perror("SNDCTL_DSP_SPEED");
    exit(1);
  }

  return audio_fd;
}

void transmit_word(struct param *p, uint16_t word) {
  static int data = 0, sample = 0, slot = 0;
  int bit, clock, phase, signal;
  int index = 0;
  int16_t buffer[MAX_SPEED*16/400+1];
  double random1, random2, noisy_signal;

  for (bit = 15; bit >= 0; bit--) {
    data ^= (word >> bit) & 1;
    for (clock = 1; clock >= 0; clock--) {
      for (phase = 0; phase < 4; phase++) {
	signal = (2 * (data ^ clock ^ (phase & 1)) - 1) * p->amplitude;
	do {
	  if (index % 2) random1 = random2;
	  else randomGaussian(&random1, &random2);
	  noisy_signal = signal + random1 * p->sigma;
	  if (noisy_signal > INT16_MAX || noisy_signal < INT16_MIN) {
	    printf("Overflow!\n");
	  }
	  buffer[index++] = noisy_signal;
	  sample++;
	} while (sample * 3200 < (slot + 1) * p->speed);
	slot++;
      }
    }
  }
  sample %= p->speed;
  slot %= 3200;
  write(p->audio_fd, buffer, 2*index);
}

void transmit_block(struct param *p, uint8_t block[BLOCK_LENGTH]) {
  uint16_t crc;
  int i;

  crc = crc16(block, BLOCK_LENGTH, 0xFFFF, p->crc_table);

  for (i = 0; i < 50; i++) transmit_word(p, 0x5050);
  transmit_word(p, 0x3915);
  transmit_word(p, 0xED30);
  for (i = 0; i < BLOCK_LENGTH; i += 2)
    transmit_word(p, (block[i] << 8) | block[i+1]);
  transmit_word(p, crc);
  for (i = 0; i < 50; i++) transmit_word(p, 0x5050);
}

void usage(char *s) {
  fprintf(stderr, "Usage: %s <sampling rate> <amplitude> <sigma> <seed>\n", s);
  exit(1);
}

int main(int argc, char **argv) {
  struct param p;
  uint8_t block[BLOCK_LENGTH];
  int i, n;

  if (argc != 5) usage(argv[0]);
  p.speed = atoi(argv[1]);
  p.amplitude = atoi(argv[2]);
  p.sigma = atoi(argv[3]);
  p.audio_fd = open_audio("/dev/dsp", O_WRONLY, AFMT_S16_NE, 1, &p.speed);
  if (p.speed < 3200 || p.speed > MAX_SPEED) {
    fprintf(stderr, "Sampling rate out of range.\n");
    exit(1);
  }
  printf("Sampling rate = %d Hz; SNR(matched filter) = %.1f\n.", p.speed,
	 p.speed / 400.0 * p.amplitude * p.amplitude / p.sigma / p.sigma);

  crc16_init(CCITT_CRC16, p.crc_table);
  seedRandom(atoi(argv[4]));

  do {
    for (i = 1, n = 0; i > 0 && n < BLOCK_LENGTH; n += i) {
      i = read(STDIN_FILENO, block+n, BLOCK_LENGTH-n);
    }
    if (i > 0 && n == BLOCK_LENGTH) {
      transmit_block(&p, block);
    }
  } while (i > 0);

  close(p.audio_fd);
  return 0;
}
