/* Author: Ram Samudrala (me@ram.org)
 * Version: O1.0
 * Detail: <http://www.ram.org/computing/sc/sc.html>
 * November 22, 1995.
 *
 * See the URL above for terms of use and general help.
 */

#include "cgi_common.h"

char *makeword(char *line, char stop);
char *fmakeword(FILE *f, char stop, int *cl);
char x2c(char *what);
void unescape_url(char *url);
void plustospace(char *str);

/******************************************************************/

void plustospace(char *str) 
{
  register int i;
  
  for(i = 0; str[i]; i++) 
    if (str[i] == '+') 
      str[i] = ' ';
  return;
}

/******************************************************************/

void unescape_url(char *url) 
{
  register int i, j;
  
  for(i= 0, j=0 ; url[i] != NULL ; i++, j++) 
    {
      if((url[i] = url[j]) == '%') 
	{
	  url[i] = x2c(&url[j+1]);
	  j += 2;
	}
    }
  url[i] = '\0';
  return;
}

/******************************************************************/

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);
}

/******************************************************************/

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;
    }
  return NULL;
}

/******************************************************************/

int read_entries(entry entries[])
{
  int i, num_entries;
  int cl;
  
  cl = atoi(getenv("CONTENT_LENGTH"));

  for(i = 0; cl && (!feof(stdin)); i++) 
    {
      num_entries = i;
      entries[i].val = fmakeword(stdin, '&', &cl);
      plustospace(entries[i].val);
      unescape_url(entries[i].val);
      entries[i].name = makeword(entries[i].val, '=');
    }
  return num_entries;
}

/******************************************************************/
