#include <iostream.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#define BUF_SIZE 2048
#define MAX_FEATURES 100
#define MIN_LEN 5
#define SPACE " "


// #define DEBUG 1

#include "CEncode.h"
#include "CSupport.h"

void writeBinList(FILE *fd, float *list, int  len, char *sep = SPACE)
{
	int i;
	CEncode E;
	for(i=0;i<len;i++)
	{
		fprintf(fd, "%s%s",
			E.BinEncode16((double)list[i], -1, 1), sep);
	}

}


void writeBin6List(FILE *fd, float *list, int  len, char *sep = SPACE)
{
	int i, j;
	const int bits = 7;
	double* temp = new double[bits];
	CSupport S;
	for(i=0;i<len;i++)
	{
		temp = S.Int2BinVector(temp, (int) ((list[i]+1)*63), bits);
		for(j=0;j<bits-1;j++)
		{
			fprintf(fd, "%i ", (int) temp[j]);
		}
		fprintf(fd, "%i%s", (int) temp[bits-1], sep);
	}

	delete [] temp;

}


void writeList(FILE *fd, float *list, int  len, char *sep = SPACE)
{
	int i;
	for(i=0;i<len;i++)
	{
		fprintf(fd, "%f%s", list[i], sep);
	}
}


int main()
{
	char in_file[30], out_file1[30], buf[BUF_SIZE],
	     result[BUF_SIZE], restStr[BUF_SIZE];
	char *firstStr, *rest;
	int i, cl_no,  sets=0, wrongs=0;
	float feature[MAX_FEATURES];
	FILE *in, *out1;

	cout << "\nin file: ";
	cin >> in_file;

	cout << "\nBIN-out file: ";
	cin >> out_file1;


	if ((in = fopen(in_file, "rt"))
		    == NULL)
	{
	   cout << ERR_MSG << "Cannot open " << in_file << " !!!\n";
	   return -1;
	}

	if ((out1 = fopen(out_file1, "wt"))
		    == NULL)
	{
	   cout << ERR_MSG << "Cannot open " << out_file1 << " !!!\n";
	   return -1;
	}


	do
	{
	   strcpy(buf,"");
	   fgets(buf,BUF_SIZE, in);
	   strcpy(restStr,buf);

	   if(strlen(buf) > MIN_LEN)
	   {
	     for(i=0;i<34;i++)
	     {

		   /* strtok places a NULL terminator
		   in front of the token, if found */
		   firstStr = strtok(restStr, ",");
		   sscanf(firstStr, "%f", &feature[i]);
		   #if DEBUG
			printf("firstStr: %s\n", firstStr);
			printf("%f", feature[i]);
		   #endif

		   strcpy(restStr, restStr+(strlen(firstStr)+1));
		   #if DEBUG
			     printf("%s", restStr);
		   #endif

	     }

	     sscanf(restStr, "%s\n", result);

	     #if DEBUG
		     printf("\n result for %i: >%c<\n", i, result[0]);
	     #endif
	   }
	   else result[0] ='-';

	   if (result[0] != 'g' && result[0] != 'b')
	   {

		cout << WARN_MSG << " Wrong result type !!!\n";
		wrongs ++;
	   }
	   else
	   {

		// writeList(out1, feature, 34);
		// writeBinList(out1, feature, 34);
		writeBin6List(out1, feature, 34);

		if (result[0] == 'g') cl_no = 0;
		else cl_no = 1;
		fprintf(out1, ": %i ;\n", cl_no);

		sets ++;
	   }

	}
	while (!feof(in));

	fclose(out1);
	fclose(in);
	cout << "\n\n" << sets << " records read from file!";
	cout << "\n" << wrongs << " are not ok! (not written)\n\n";
	return 0;
}
