/*
    Tucnak - VHF contest log
    Copyright (C) 2002-2006  Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/


#include "header.h"
#include "tregex.h"


/* returns zero if matching */
int regcmp(char *string, char *regex){
    regex_t preg;
    int ret;
    
    ret = regcomp(&preg, regex, REG_EXTENDED | REG_NOSUB);
    if (ret) zinternal("regcomp failed");
    
    ret = regexec(&preg, string, 0, 0, 0);
    regfree(&preg);
    
    return ret;
}

int regcmpi(char *string, char *regex){
    regex_t preg;
    int ret;
    
    ret = regcomp(&preg, regex, REG_EXTENDED | REG_NOSUB | REG_ICASE);
    if (ret) zinternal("regcomp failed");
    
    ret = regexec(&preg, string, 0, 0, 0);
    regfree(&preg);
    
    return ret;
}

/* returns zero if matching */
#ifdef LEAK_DEBUG_LIST
int debug_regmatch(char *file, int line, const char *string, char *regex, ...){
#else
int regmatch(const char *string, char *regex, ...){
#endif
    regex_t preg;
    regmatch_t match[MAX_MATCHES];
    va_list ap;
    int ret,i;
    char **ppc;

/*    dbg("regmatch('%s','%s')\n", string, regex);*/

    ret = regcomp(&preg, regex, REG_EXTENDED);
    if (ret) zinternal("regcomp failed, regex='%s'", regex);
    
    ret = regexec(&preg, string, MAX_MATCHES, match, 0);
    regfree(&preg);
    if (ret) return ret;

/*    dbg("regmatch '%s'~=/%s/; \n",string,regex);*/

    va_start(ap,regex);
    for (i=0; i<MAX_MATCHES; i++){
        ppc=va_arg(ap, char **);
       /* dbg("i=%i  ppc=%p \n",i,ppc);*/
        if (ppc==NULL) break;
            
        if (match[i].rm_eo!=-1 && 
            match[i].rm_eo!=0) { 
#ifdef LEAK_DEBUG_LIST       
            *ppc=debug_g_malloc(file, line, match[i].rm_eo - match[i].rm_so + 1);
#else
            *ppc=g_malloc(match[i].rm_eo - match[i].rm_so + 1);
#endif
            memcpy(*ppc, string+match[i].rm_so, match[i].rm_eo - match[i].rm_so );
            (*ppc)[match[i].rm_eo - match[i].rm_so ] = '\0';
 /*           dbg("allocated %p '%s'\n",*ppc,*ppc);*/
        }else{
            *ppc=NULL;
        }
        
    }
    va_end(ap);
    
            
    
    
    return ret;
}

