#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/time.h>

#include "header.h"

tErr initHeader(header* head,char** zeMsg,long unsigned* curSize){
	tErr err;
	head->m_msgbuf = zeMsg;
	head->m_msgsize = curSize;

	head->m_buffer=NULL;
	head->m_From_feild=NULL;
	head->m_To_feild=NULL;
	head->m_Cc_feild=NULL;
	head->m_Bcc_feild=NULL;
	head->m_ReturnPath_feild=NULL;
	head->m_DeliveredTo_feild=NULL;
	head->m_Subject_feild=NULL;
	head->m_fetchmail_server_addr=NULL;
	head->m_fetchmail_username=NULL;
	head->m_Subject_feild=NULL;

	if( (err = countLines(head,*zeMsg,*curSize)) != noErr) return err;
	if( (err = getHeaderFields(head)) != noErr) return err;
	return noErr;
}

tErr countLines(header* head,char* zeMsg,long unsigned size){
	unsigned long i;
	unsigned int curLine=0;
	unsigned int curLineSize=0;

	head->m_headerLines[0]=0;
	for(i=2;i<size-2;i++){
		if(zeMsg[i-2] =='\r' && zeMsg[i-1] =='\n' &&
		zeMsg[i] =='\r' && zeMsg[i+1] =='\n'){
			head->m_headerLinesSize[curLine]=curLineSize;
			head->m_headerSize = i;
			head->m_headerNumLines = curLine+1;
			return noErr;
		}
		if(zeMsg[i-2] =='\r' && zeMsg[i-1] =='\n'){
			head->m_headerLines[curLine+1]=i;
			head->m_headerLinesSize[curLine]=curLineSize;
			curLine++;
			if(curLine>=MAX_HEADER_LINE-2)	return INCONSISTENT_MESSAGE;
			curLineSize=0;
		}
		curLineSize++;
	}
	return INCONSISTENT_MESSAGE;
}
void destroyHeader(header* head){
	if(head->m_fetchmail_server_addr!=NULL)		free(head->m_fetchmail_server_addr);
	if(head->m_fetchmail_username!=NULL)		free(head->m_fetchmail_username);
	if(head->m_iWall_user!=NULL)				free(head->m_iWall_user);
	if(head->m_fetchmail_email_addr!=NULL)		free(head->m_fetchmail_email_addr);
}
