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

struct head
{
	char ChunkID[4];
	long int ChunkSize;
	char Format[4];

	char SubChunkID[4];
	long int SubChunkSize;
	short int AudioFormat;
	short int NumChannels;
	long int SampleRate;
	long int BytesRate;
	short int  BlockAlign;
	short int BitsPerSample;

	char SubChunk2ID[4];
	long int SubChunk2Size;
}head;

char * jump_commented_lines(char * ptr)
{
	while (*ptr == '#')
	{
		while ((*ptr != '\n')||(*ptr != EOF))
		{
			ptr++;
		}
		ptr++;
	}
	return ptr;
}

int find_end_of_sample(char * ptr)
{
	int ccnt = 0;
	int got = 0;
	//while ((*(ptr+cnt) != ' ')||(*(ptr+cnt) != '\n')||(*(ptr+cnt) != EOF))
	while (got == 0)
	{
		if ((*(ptr+ccnt) == ' ')||(*(ptr+ccnt) == '\n')||(*(ptr+ccnt) == EOF))
		{
			got = 1;
		}
		else
		{
			ccnt++;
		}
	}
	return ccnt;
}

int get_channel(char * ptr, int fin)
{
	int cccnt = 0;
	int got = 0;
	//while ((*(ptr+cccnt) != ':')||(cccnt != fin))
	while (got == 0)
	{
		if ((*(ptr+cccnt) == ':')||(cccnt == fin))
		{
			got = 1;
		}
		else
		{
			cccnt++;
		}
	}
	return cccnt;
}

int bitsrate = 8;
int leap_size = 8000;


int main(void)
{
	int current_size = leap_size;
	char * array = malloc(current_size);
	int cnt = 0;
	char input = '~';
	while(input != EOF)
	{
		//get the entire input on memory
		if (cnt >= current_size)
		{
								//printf("realloc %d \n",current_size);
			current_size += leap_size;
			array = realloc(array,current_size);
								//printf("reallocated %d \n",current_size);
			if (array == 0)
			{
				printf("reached memory limit!!!\n");
				return 0;
			}
											//printf("%d",(int)input);
		}
		input = getchar();
		*(array + cnt) = input;
		cnt++;
	}	
	
printf("%d\n",cnt);
	//now work with samples
	char * start = jump_commented_lines(array);
	int start_of_sample = 0;
	int end_of_sample = find_end_of_sample(start);
printf("%d\n",cnt);
	//while (*(start + end_of_sample) != EOF)
	while (end_of_sample < cnt-1)
	{
		//get one sample
		int len = end_of_sample - start_of_sample;
		char * sample = malloc(len+1);
		int i;
		for (i=0;i<=len;i++)
		{
			*(sample+i) = *(start+start_of_sample+i);
		}
		//now work with channels
		int mini_cnt = 0;
		while (mini_cnt < len)
		{
			//isolate one channel
			int mini_end = get_channel(sample+mini_cnt,len);
			//convert string to double
			double volume = strtod(sample+mini_cnt,(char*)sample+mini_cnt+mini_end);
			//jump to next channel
			mini_cnt += (mini_end+1);
			//convert double to desired bitsrate
			int volulume = (int)(volume * (2<<(bitsrate-1)));
			//now output it in desired bitsrate
			char * vovolume = (char*)&volulume;
			int i;
			for (i=0;i<(bitsrate/8);i++)
			{
				char euh = *(vovolume + i);
				putchar(euh);
			}
		}
		free(sample);
		
		start_of_sample = end_of_sample + 1;
		end_of_sample = start_of_sample + find_end_of_sample(start + start_of_sample);
		//printf("%d\n",end_of_sample);
	}


	return 0;
}
