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

#include <X11/Intrinsic.h>

#include "viewlog.h"
#include "wdlogdisp.h"

char writebuf[500];

int wdlogdisp(FILE *pFile)
{
	unsigned char *buffer1;
	unsigned short *buffer2;
	char buffer[100];
	struct CHANNEL_INFO *channels;
	struct WOD_HEADER wod_header;
	double value;
	int channel;
	char title[40];
	double a, b, c;
	FILE *fp;
	int i, n;

	if ((fp = fopen("tlm.cfg", "r")) == NULL)
	{
		fprintf(stderr, "Cannot open tlm.cfg\n");
		return(1);
	}

	if (fread(&wod_header, sizeof(wod_header), 1, pFile) != 1)
		return(1);
		
	sprintf(writebuf, "Whole Orbit Data\n\nStart: %s",
		ctime(&wod_header.start_time));
	writetext(writebuf);

	sprintf(writebuf, "End:   %sPeriod: %d seconds\n\n",
		ctime(&wod_header.end_time),
		(int)wod_header.sample_period);
	writetext(writebuf);

	if ((channels = (struct CHANNEL_INFO *)XtCalloc(wod_header.number_of_channels, sizeof(struct CHANNEL_INFO))) == NULL)
		return(1);

	if ((buffer1 = (unsigned char *)XtCalloc(wod_header.number_of_channels, 1)) == NULL)
		return(1);

	fread(buffer1, 1, wod_header.number_of_channels, pFile);

	while (fgets(buffer, 100, fp) != NULL)
	{
		if (*buffer == 'A')
		{
			sscanf(buffer, "%*c %d , %[^,], %lf , %lf , %lf , %*d ,",
				&channel, title, &a, &b, &c);

			for (i = 0; i < wod_header.number_of_channels; i++)
			{
				if (buffer1[i] == channel)
				{
					sprintf(writebuf, "%2d: %s\n", channel, title);
					writetext(writebuf);

					channels[i].channel = channel;
					channels[i].a = a;
					channels[i].b = b;
					channels[i].c = c;
				}
			}
		}
	}

	fclose(fp);

	writetext("\n");

	for (n = 0, i = 0; i < wod_header.number_of_channels; i++)
		n += sprintf(writebuf + n, " %-9d", channels[i].channel);

	strcat(writebuf, "\n");
	writetext(writebuf);

	XtFree(buffer1);

	if ((buffer2 = (unsigned short *)XtCalloc(wod_header.number_of_channels, 2)) == NULL)
		return(1);

	while (fread(buffer2, 2, wod_header.number_of_channels, pFile) > 0)
	{
		for (n = 0, i = 0; i < wod_header.number_of_channels; i++)
		{
			value = (double)buffer2[i];
			n += sprintf(writebuf + n, "%-10.2f",
				value * value * channels[i].a +
				value * channels[i].b +
				channels[i].c);
		}

		strcat(writebuf, "\n");
		writetext(writebuf);
	}

	XtFree((char *)buffer2);

	XtFree((char *)channels);

	return(0);
}

