/*
 *  cgistuff.c
 *
 *  This file contains routines common to all cgi scripts.
 */

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

#define TRUE 1
#define FALSE 0

/*
 *  Convert all cOld characters in cStr into cNew characters
 */
void strcvrt(char * cStr,char cOld,char cNew) {
int i;

    i = 0;
    while (cStr[i]) {
        if (cStr[i]==cOld) cStr[i] = cNew;
        i++;
    }
}

/*
 *  The string starts with two hex characters.  Return an integer formed from them.
 */
static int TwoHex2Int(char *pC) {
int Hi;
int Lo;
int Result;

    Hi = pC[0];
    if ('0'<=Hi && Hi<='9') {
        Hi -= '0';
    } else
    if ('a'<=Hi && Hi<='f') {
        Hi -= ('a'-10);
    } else
    if ('A'<=Hi && Hi<='F') {
        Hi -= ('A'-10);
    }
    Lo = pC[1];
    if ('0'<=Lo && Lo<='9') {
        Lo -= '0';
    } else
    if ('a'<=Lo && Lo<='f') {
        Lo -= ('a'-10);
    } else
    if ('A'<=Lo && Lo<='F') {
        Lo -= ('A'-10);
    }
    Result = Lo + 16*Hi;
    return Result;
}

/*
 *  Decode the given string in-place by expanding %XX escapes
 */
void urlDecode(char *p) {
char *pD;

    pD = p;
    while (*p) {
        if (*p=='%') {
            /* Escape: next 2 chars are hex representation of the actual character */
            p++;
            if (isxdigit(p[0]) && isxdigit(p[1])) {
                *pD++ = (char) TwoHex2Int(p);
                p += 2;
            }
        } else {
            *pD++ = *p++;
        }
    }
    *pD = '\0';
}

