#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 "my_strings.h"

#ifndef true
#define true 1
#endif
#ifndef false
#define false 0
#endif

char* addSlashes(char* buf,long bufSize){
	char* newBuf;
	char* p,*d,c;
	long i,cnt=0;

	p = buf;
	for(i=0;i<bufSize;i++){
		if(*p++ == '\'' || '\\'){
			cnt++;
		}
	}
	newBuf = (char*)malloc(bufSize+cnt);
	d = newBuf;
	p = buf;

	for(i=0;i<bufSize;i++){
		c = *p++;
		if(c == '\'' || c == '\\'){
			*d++ = '\\';
		}
		*d++ = c;
	}
	return newBuf;
}
// Return true or false is the given char can be one of email addr string
int isValidChar(char c){
	char validMailAddrChars[]="qwertyuiopasdfghjklzxcvbnm.-_1234567890";
	int i;
	int len;
	len = strlen(validMailAddrChars);
	for(i=0;i<len;i++){
		if(c == validMailAddrChars[i]){
			return true;
		}
	}
	return false;
}

char* extractMailFromString(char* field){
	char* dup;
	char* domain;
	char* user;
	char* ret;

	if(field == NULL)	return NULL;
	dup = strdup(field);
	if(dup == NULL)	return NULL;
	if( ((domain = strstr(dup,"@")) == NULL) || domain == dup){
		free(dup);
		return NULL;
	}
	user = domain - 1;
	if(!isValidChar(*user)){	free(dup);return NULL;}
	while( 1 ){
		if(user == dup)	break;
		if( !isValidChar(*user) ){
			user++;
			break;
		}
		user--;
	}
	domain++;
	if(!isValidChar(*domain)){	free(dup);return NULL;}
	while( 1 ){
		if( !isValidChar(*domain) ){
			*domain=0;
			break;
		}
		domain++;
	}
	ret = strdup(user);
	free(dup);
	return ret;
}
