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


#define WARN_MSG        "\n>>> Warning: "
#define ERR_MSG         "\n>>> ERROR: "


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


// #define DEBUG 1

// Attation !!! len = 2 time the number of bits (Spacees!!!!)
char *code(char *ret, float con, int len)
{
	int len0, i;
	len0 = len - (int)ceil(con*len);
	for(i=0;i<len;i+=2) 
	{
		if (i < len0) ret[i] = '0';
		else ret[i] ='1';
		ret[i+1] = ' ';
	}

	cout << "\n " << con << " --> "; 
	for(i=0;i<len;i++) cout << " " << ret[i]; 
	
	return ret;
}

void writeBinList(FILE *fd, float *list, int  len, char *sep = SPACE)
{
	int i;
	char *Str = new char[1000];

	for(i=0;i<len;i++)
	{
		fprintf(fd, "%s%s",
			code(Str, ((float)list[i]+1)/2.0, 2*10),   sep);
	}

	delete [] Str;
}


int main()
{
	char in_file[30], out_file1[30], buf[BUF_SIZE],
	     restStr[BUF_SIZE];
	char *firstStr, *rest;
	int i, cl_no,  sets=0, wrongs=0;
	float feature[MAX_FEATURES], result;
	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<8;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, "%f\n", &result);

	     #if DEBUG
		     printf("\n result for %i: >%f<\n", i, result);
	     #endif
	   }
	   else result =-1;

	   if (result != 1 && result != 2)
	   {

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

		writeBinList(out1, feature, 8);

		if (result == 1) 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;
}

