#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "FASTA.h"
#include "util.h"
#include <ctype.h>

char Buf[65535];

FASTA::FASTA()
{
	CodeTable=(char *)Malloc(13*sizeof(char));
	strcpy(CodeTable,"ATCGNatcgn-");
}

FASTA::~FASTA()
{
	free(CodeTable);
}

void FASTA::OpenRead(const char *filename)
{
	if ((fhandle=fopen(filename,"r"))==NULL)
	{
		fprintf(stderr,"FASTA Open File Failed\n");
		exit(1);
	}
}

void FASTA::OpenWrite(const char *filename)
{
	if ((fhandle=fopen(filename,"w"))==NULL)
	{
		fprintf(stderr,"FASTA Create File Failed\n");
		exit(1);
	}
}


void FASTA::Close()
{
	fclose(fhandle);	
}

int FASTA::GetFastaSeq(char **label,char ** seq,int del_N,int trim_space)
{ 
	char *temp;
	int ptr=0;
	int tag_N=0;

	int c = fgetc(fhandle);
	if (EOF == c)
		return 0;
		
	if ('>' != c)
	{
		fprintf(stderr,"Invalid file format, expected '>' to start FASTA label\n");
		return 0;
	}
	
	for (;;)
		{
		 c = fgetc(fhandle);
		if ('\r' == c || '\n' == c)
			break;
		if (trim_space==0 || ' ' !=c)	
			Buf[ptr++]=(char) c;	
		}
		
	Buf[ptr]=0;
	temp=(char *)Malloc((ptr+1)*sizeof(char));
	strcpy(temp,Buf);
	*label=temp;
	
	ptr=0;
	for (;;)
		{
		 c = fgetc(fhandle);
		if ('>' == c || EOF == c)
			break;
		if (strchr(CodeTable,c)!=NULL)
			Buf[ptr++]=(char) toupper((char)c);	
		if ('N' == c && del_N)
			tag_N=1;	             		
		}
	ungetc(c,fhandle);
	Buf[ptr]=0;
	temp=(char *)Malloc((ptr+1)*sizeof(char));
	strcpy(temp,Buf);
	if (tag_N)
		temp[0]=0;
	*seq=temp; 
	return ptr;
}

void FASTA::WriteFastaSeq(const char *label,const char *seq)
{
	fprintf(fhandle,">%s\n",label);
	fprintf(fhandle,"%s\n",seq);
}
