/*
** gather_ad is a simple program to collect data from the eight channel
** analog digital converter. It is far from being perfect and is
** intended as a skeleton for own developments of the readers.
**
** 19-APR-2003, B. Ulmann fecit.
*/

#include <stdio.h>
#include <time.h>

#undef VERBOSE

#define STRING_LENGTH 81
#define MAX_CHANNELS 8

int main (int argc, char **argv)
{
    int samples_per_second, seconds_per_file, channels, i, j, value;

    time_t time_value;

    char filename [STRING_LENGTH], date_time [STRING_LENGTH],
	line [STRING_LENGTH], scratch [STRING_LENGTH];

    FILE *input_handle, *output_handle;

    if (argc != 5)
    {
	printf ("Usage: gather_ad <serial_line_device> \
<samples_per_second> <seconds_per_file> <channels>\n");
	return -1;
    }

    if (!(input_handle = fopen (argv [1], "r")))
    {
	printf ("Unable to open input device >>%s<<!\n", argv [1]);
	return -2;
    }

    if ((samples_per_second = atoi (argv [2])) < 1)
    {
	printf ("samples_per_second has to be greater than 0.\n");
	return -3;
    }

    if ((seconds_per_file = atoi (argv [3])) < 1)
    {
	printf ("seconds_per_file has to be greater than 0.\n");
	return -4;
    }

    if ((channels = atoi (argv [4])) < 1)
    {
	printf ("channels has to be greater than 0.\n");
	return -5;
    }
    else if (channels > MAX_CHANNELS)
    {
	printf ("channels has to be less or equal than %d.\n", MAX_CHANNELS);
	return -6;
    }

    for (; !feof (input_handle);)
    {
	time_value = time (NULL);
	strftime (filename, STRING_LENGTH, "ad_%Y%m%d_%H%M%S.raw", 
		  localtime (&time_value));
	strftime (date_time, STRING_LENGTH, "%Y%m%d %H%M%S", 
		  localtime (&time_value));

	printf ("Opening output file >>%s<<.\n", filename);
	if (!(output_handle = fopen (filename, "w")))
	{
	    printf ("Unable to open output file >>%s<<!\n", filename);
	    return -7;
	}

	fprintf (output_handle, "%s\n", date_time);
	for (i = 0; i < samples_per_second * seconds_per_file && 
		    !feof (input_handle); i++)
	{
	    fgets (line, STRING_LENGTH, input_handle);
	    if (strlen (line) == 1 && line [0] == (char) 10)
		continue;
	    else if (strlen (line) != channels * 4 + 1)
	    {
		printf ("Illegal datagram read, len: %d. Write default.\n",
			strlen (line));
		strcpy (line, "00000000000000000000000000000000");
	    }
		
	    for (j = 0; j < channels; j++)
	    {
		strncpy (scratch, line + j * 4, 4);
		scratch [4] = (char) 0;
		sscanf (scratch, "%x", &value);
		fprintf (output_handle, "%f ", 
			 (float) ((value << 16) >> 16) / 32768.);
#ifdef VERBOSE
		printf ("%f ", (float) ((value << 16) >> 16) / 32768.);
#endif
	    }
#ifdef VERBOSE
	    printf ("\n");
#endif
	    fprintf (output_handle, "\n");
	}
	printf ("Closing output file, %d records written.\n", i);
	fclose (output_handle);
    }

    printf ("End of file on input data detected, abort!\n");
    fclose (input_handle);

    return 0;
}




