/* Copyright (C) 2004 Stefan Bellon <sbellon@sbellon.de>
 *
 * This file is part of RemotePrinterFS.
 *
 * RemotePrinterFS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * RemotePrinterFS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

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

#include "errors.h"
#include "syslogf.h"
#include "utils.h"

bool
aredigit(const char *s)
{
    while (*s)
        if (!isdigit(*s))
            return false;
        else
            ++s;

    return true;
}

int
strcasecmp(const char *a, const char *b)
{
    for(; *a && *b; ++a, ++b)
        if (*a != *b && toupper(*a) != toupper(*b))
	    break;

    return *a - *b;
}

char *
strdup(const char *s)
{
    if (!s)
        return NULL;
    else {
        const size_t mem = strlen(s) + 1;
        char *result = malloc(mem);
        if (result)
            return memcpy(result, s, mem);
        else {
            syslogf(LOG_CRIT, "malloc failed, no memory allocated");
            return result;
        }
    }
}

os_error const *
parse_special_field(char *sf, apply cb)
{
    char *i, *p, *copy;

    /* Copy the address into writable memory so we can use strtok(3). */
    copy = malloc(strlen(sf) + 1);
    if (!copy) {
        syslogf(LOG_CRIT, "malloc failed, no memory allocated");
        return ERR(err_NoMemory);
    }

    strcpy(copy, sf);
    p = strtok(copy, ";");

    while (p) {
        i = strchr(p, '=');
        if (i) {
            *i = 0;                     /* now: p is key, i+1 is value   */
            error = cb(p, i+1);
            if (error != NULL) {
                *i = '=';               /* restore overwritten character */
                free(copy);
                return error;
            }
            *i = '=';                   /* restore overwritten character */
        } else {
            free(copy);
            syslogf(LOG_ERR, "Syntax error in special field: no '=' found");
            return ERR(err_InvalidSpecialField);
        }
        p = strtok(NULL, ";");
    }
    free(copy);

    return NULL;
}
