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


#define MAX 10000000

#define NUM 2000000

void header(void);


FILE *pFile[5];
char filename[5][FILENAME_MAX];

char prefix[20];
char prefixn[20];
char nnn[20];

int nh;

unsigned long i,j,k;
unsigned long cells,lines,columns;

float ffff;

float x[NUM];
float t[NUM];

double sr,dt;


void main()
{

    printf("\n io_conv_large.cpp, ver 1.0,  March 16, 2006");
	printf("\n\n by Tom Irvine ");
	printf("\n Email:  tomirvine@aol.com \n");

	printf("\n This program divides a file with multiple channels ");
	printf("\n so that each channel is in its own file. \n");

	

    printf( "\n Enter the input filename: \n");
			              
	scanf("%s",filename[0]);
	pFile[0]=fopen(filename[0], "rb");


	if(pFile[0] == NULL )
	{
		printf(" Failed to open file: %s \n", filename[0]);
		fclose(pFile[0]);
	}
	else
	{
		printf(" File: %s opened. \n", filename[0]);
	}

	printf("\n Enter the number of header lines. \n");
	scanf("%d",&nh);


	printf( "\n\n Enter the output filename prefix. \n");
			              
	scanf("%s",prefix);


	printf( "\n\n Enter the samping rate (samples per second). \n");
			              
	scanf("%lf",&sr);

	dt=1./sr;


	i=0;

	header();
	
	while( fscanf(pFile[0], "%f ", &ffff) > 0 )
	{
		i++;

		if(i==MAX)
		{
			printf("\n Error: maximum cell limit reached. \n");

			exit(1);
		}

	}
	rewind(pFile[0]);

	cells=i;

	printf("\n\n %ld samples read \n",cells);

//******************************************

	i=0;

	long numBytes = 20000;

	char string[20000];

    header();

	while(1)
	{
		if( fgets(string,numBytes,pFile[0] ) <=0 ){break;}

		i++;
	}

	lines=i;

	printf("\n\n %ld lines read \n",lines);

	if(lines>MAX)
	{
		lines=MAX;

		printf("\n\n Warning: maximum number of lines = %ld \n",lines);
	}

//******************************************

	unsigned long columns = unsigned long(double(cells)/double(lines));

	printf("\n\n %ld columns \n",columns);

	if( columns > 1000 )
	{
		printf("\n Error: maximum column limit reached. \n");

		exit(1);
	}

	printf("\n");

	float y[2000];

	printf("\n\n Output files: \n");

	for(k=0;k<columns;k++)
	{
		rewind(pFile[0]);

		header();

		for(i=0;i<lines;i++)
		{
			for(j=0;j<columns;j++)
			{
				fscanf(pFile[0],"%f",&ffff);

				y[j]=ffff;
			}
		
			x[i]=y[k];

		}


		if(k>=0)
		{

			strcpy(prefixn,prefix);

			sprintf(nnn,".%ld",k);
        
			strcat(prefixn,nnn);

			printf("%s \n",prefixn);


			pFile[1]=fopen(prefixn,"w");

			for(i=0;i<lines;i++)
			{
				fprintf(pFile[1]," %14.7e  %12.5e\n",dt*i,x[i]);
			}
			fclose(pFile[1]);
		}
	}
	
	printf("\n\n Calculation complete. \n\n Press any key to exit.");
	getch();
}
void header(void)
{
	long h_numBytes = 20000;

	char h_string[20000];

	long ijk;

	for(ijk=0;ijk<nh;ijk++)
	{
		if( fgets(h_string,h_numBytes,pFile[0] ) <=0 ){break;}
	}

}
