#include <stdlib.h>
#include "tools.h"

/* the vast majority of these functions come from the NCSA distrubtion
 * from the utils.c file.  Some functions have been optimized or made
 * more versitile in thier design.
 * -- Michael Turner (m_turner@dax.cs.wisc.edu)
 */

void html_error(char *msg)
  {
    printf("Content-type: text/html\n\n");
    printf("<HTML><HEAD>\n");
    printf("<TITLE>Error message</TITLE>\n");
    printf("</HEAD><BODY>\n");
    printf("%s\n",msg);
    printf("</BODY></HTML>\n");
  }
  
char x2c(char *what) {
    register char digit;

    digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
    digit *= 16;
    digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
    return(digit);
}
  
void getword(char *word, char *line, char stop) {
    int x = 0,y;

    for(x=0;((line[x]) && (line[x] != stop));x++) word[x] = line[x];

    word[x] = '\0';
    if(line[x]) ++x;
    y=0;

    while(line[y++] = line[x++]);
}

void atob(char *str, char a, char b)
  { register int x; for(x=0;str[x];x++) if(str[x] == a) str[x] = b; }

void unescape_url(char *url) {
    register int x,y;

    for(x=0;url[x];x++)
        if(url[x] == '%')
            url[x+1] = x2c(&url[x+1]);

    for(x=0,y=0;url[y];++x,++y) {
        if((url[x] = url[y]) == '%') {
            url[x] = url[y+1];
            y+=2;
	}
    }
    url[x] = '\0';
}

void strip_char(char *str, char strip)
  {
    char foo[STR_SIZE];
    register int i = 0;
    register int j = 0;
    while(str[i])
      {
	if(str[i] != strip) 
	  foo[j++] = str[i];
	i++;
      }
    foo[j] = '\0';
    strcpy(str,foo);
  }

void replacechar2str(char *word, char find, char *replace)
  {
    char foo[STR_SIZE];
    register int i = 0;
    register int j = 0;
    register int k = 0;
    while(word[i])
      {
	if(word[i] == find)
	  {
	    k = 0;
	    while(replace[k]) foo[j++] = replace[k++];
	  }
         else
	  { foo[j++] = word[i]; }
	i++;
      }
    foo[j] = '\0'; 
    strcpy(word,foo);
  }


char *makeword(char *line, char stop) {
    int x = 0,y;
    char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));

    for(x=0;((line[x]) && (line[x] != stop));x++)
        word[x] = line[x];

    word[x] = '\0';
    if(line[x]) ++x;
    y=0;

    while(line[y++] = line[x++]);
    return word;
}


char *fmakeword(FILE *f, char stop, int *cl) 
  {
    int wsize;
    char *word;
    int ll;

    wsize = 102400;
    ll=0;
    word = (char *) malloc(sizeof(char) * (wsize + 1));

    while(1)
      {
        word[ll] = (char)fgetc(f);
        if(ll==wsize) 
	  {
            word[ll+1] = '\0';
            wsize+=102400;
            word = (char *)realloc(word,sizeof(char)*(wsize+1));
          }
        --(*cl);
        if((word[ll] == stop) || (feof(f)) || (!(*cl))) 
	  {
            if(word[ll] != stop) ll++;
            word[ll] = '\0';
            return word;
          }
        ++ll;
      }
  }
