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

char hexa2char(char *s)
{ char x;
x=0;
if (s[0]>='A') x+=s[0]+10-'A'; else x+=s[0]-'0';
x*=16;
if (s[1]>='A') x+=s[1]+10-'A'; else x+=s[1]-'0';
return(x);
}

char *textval(char *s)
{ int i,j,n;
char *r;
/* n : nombre de caracteres a allouer */
i=0; j=0;
while (s[i] != '\0' && s[i] != '&')
{ if (s[i] == '%') j++;
i++;
}
n = i - (2*j);
r = (char*) malloc (n * sizeof(char));
/* r : chaine renvoyee */
i = 0; j = 0;
while (s[i] != '\0' && s[i] != '&')
{switch (s[i])
{case '%' :
r[j] = hexa2char(&s[i+1]);
i+=2; break;
case '+' :
r[j] = ' '; break;
default :
r[j] = s[i];
}
i++; j++;
}
r[j] = '\0';
return(r);
}

int varsuiv(char *s, int i)
{ while (s[i] != '\0' && s[i] != '&') i++;
if (s[i] == '\0') return(-1); else return(i+1);
}

int idval(char *s , char *v, int n)
{ int i, o, l;
l = strlen(v);
i = o = 0;
while (i != -1)
{if (strncmp(&s[i],v,l) == 0) o++;
if (o == n) return(i+l+1);
i = varsuiv(s,i);
}
}

int nbocc(char *s , char *v)
{ int i, o, l;
if (s==NULL) return(0);
l = strlen(v);
i = o = 0;
while (i != -1)
{if (strncmp(&s[i],v,l) == 0) o++;
i = varsuiv(s,i);
}
return(o);
}

char *getval(char *s , char *v, int n)
{ int i;
if (s==NULL) return(NULL);
i = idval(s,v,n);
if (s[i] == '\0' || s[i] == '&') return(NULL);
return(textval(&s[i]));
}