/*
 *				**** CHANNEL ****
 *
 * This file contains routines dealing with channels
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "scantv.h"

static struct Channel Chan[500];
static int num_channels = 0;

static void init_channels(void);

int
find_channel(char *code)
{
	int i;

	if (code == NULL) return -1;
	if (num_channels == 0)
	{ /* first time - read channels file */
		init_channels();
		if (num_channels == 0)
		{
			fprintf(stderr, "Can't open channels file\n");
			exit(11);
		}
	}

	for (i=0; i < num_channels; i++)
	{
   	if (Chan[i].ch_code == NULL)
      {
      	fprintf(stderr, "Invalid channel in position %d\n", i);
      }
      else
      {
      	/* printf("Code=%s, Chan[%d].ch_code=%s\n", code, i, Chan[i].ch_code); */
			if (strcmp(code, Chan[i].ch_code) == 0) return i;
      }
	}
	return -2;
}

static void
init_channels(void)
{
	FILE *fp;
	char buf[BUFSIZ], *flds[4];
	int nflds;

	if ((fp = fopen("chan.txt", "r")) == NULL)
	{
		perror("Can't open chan.txt");
		return ;
	}

	while (fgets(buf, sizeof(buf), fp) != NULL)
	{ /* read and parse lines in file */
		nflds = split_flds(buf, flds, '|', 0, 4);
		if (nflds != 4) continue;
		Chan[num_channels].ch_code = strdup(flds[0]);
		Chan[num_channels].ch_name = strdup(flds[1]);
		Chan[num_channels].ch_num = strdup(flds[2]);
		num_channels++;
	}
   Chan[num_channels].ch_code = NULL;


	fclose(fp);
}

char *
get_channel_name(int loc)
{
	if (loc < 0 || loc > num_channels) return "*ERR*";
	return Chan[loc].ch_name;
}

char *
get_channel_num(int loc)
{
	if (loc < 0 || loc > num_channels) return "*ERR*";
	return Chan[loc].ch_num;
}

char *
get_channel_code(int loc)
{
	if (loc < 0 || loc > num_channels) return "*ERR*";
	return Chan[loc].ch_code;
}
