/* program utility to convert fasta text files to binary files */

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

int main(int,char *[]);
int totestMode(void);

FILE *fInputp;
FILE *fp;
FILE *fTmReadp;
FILE *fTmWritep;

static char chrSet[40] = "";
static char chrBinFn[100] = "";
static char tmWFn[100] = "";
static char bin[10] = ".bin";
static char test[10] = ".test";

main (int argc,char *argv[])
{
	int  hstrLen, feofFlg, testMode;
	long int  contigPos;
	char base, contig[500];
	
	if(argc != 2)
		{
		printf("argc %d; syntax faToBin chrNo\n");
		exit(0);
		}
	strcpy(chrSet,argv[1]);
	strcpy(chrBinFn,chrSet);
	strcat(chrBinFn,bin);
	strcpy(tmWFn,chrSet);
	strcat(tmWFn,test);
	
	fInputp = fopen(chrSet,"r");
		if (fInputp == NULL)
		{
		printf("Infile chromosome test command failed.\n");
		exit(0);
		}
		
	fp = fopen(chrBinFn,"wb");
		if (fp == NULL)
		{
		printf("chrBinFn wb test command failed.\n");
		exit(0);
		}

	contigPos = 0;
	hstrLen = 0;
	feofFlg = 1;
	
	testMode = 0;
	
	base = getc(fInputp);	
	do	
		{
		if (base == '>')
			{
			fscanf(fInputp," %400[^\n]\n",contig);
			hstrLen = strlen(contig);
			if(hstrLen >= 400)
				{
				printf("\nhstrLen %d\n",hstrLen);
				printf("header array length exceeded; contig base count may be inaccurate\n");
				printf("%s\n",contig);
				exit(0);
				}
			contigPos = 0;

			base = getc(fInputp);	
			}
		if (feof(fInputp))
			{
			feofFlg = 0;
			}
		if (base == 'A' || base == 'G' || base == 'C' || base == 'T' || base == 'N' ||
			base == 'a' || base == 'g' || base == 'c' || base == 't' || base == 'n')
			{
			contigPos++;
			putc(base,fp);
			}
		base = getc(fInputp);
		}while(feofFlg);

	printf("bases written to binary file: %ld\n\n",contigPos);
	
	fclose(fInputp);
	fclose(fp);
	
	if(testMode)
		{
		totestMode();
		}

	return 0;
}

totestMode(void)
{
	int linPtr, ctr;
	char bbase;
	
	fTmReadp = fopen(chrBinFn,"rb");
		if (fTmReadp == NULL)
		{
		printf("chrBinFn rb test command failed.\n");
		exit(0);
		}
		
	fTmWritep = fopen(tmWFn,"w");
		if (fTmWritep == NULL)
		{
		printf("fTmFn w test command failed.\n");
		exit(0);
		}

	linPtr = 0;
	ctr = 0;
	
	fprintf(fTmWritep,">%s\n",chrBinFn);
	do
		{
		bbase = toupper(getc(fTmReadp));
		if (bbase == 'A' || bbase == 'G' || bbase == 'C' || bbase == 'T' || bbase == 'N')
			{
			fprintf(fTmWritep,"%c",bbase);
			linPtr++;
			if (linPtr == 59)
				{
				fprintf(fTmWritep,"\n");
				linPtr = 0;
				}
			}
		ctr++;
		}while(!feof(fTmReadp) && ctr < 4000);

	fprintf(fTmWritep,"\n");
	
	fclose(fTmReadp);
	fclose(fTmWritep);

	return 0;
}
