#include <string.h>

#include "../global.h"

#include "shared_translate_url.h"


/*** This reads 'from' and writes it to 'to' converting
****
**** AMP_SUB to '&' (or '&amp', if try_xhtml_compatible is true and there's enough space)
**** EQUAL_SUB to '='
**** QMARK_SUB to '?'
****
****  AMP_SUB, etc. are #defined in shared_translate_url.h
****
**** This function was changed November 2004 to attempt to 
**** translate AMP_SUB to "&amp;" instead of simply "&" in
**** order to comply with modern HTML validation standards
**** without breaking existing code
***/


void
translate_url_substitutes (char *to, char *from, int maxlen, int try_xhtml_compatible)
{
  char *ptr;
  int i = 0;
  int required_space;
  
  if(try_xhtml_compatible)
   {
    /* set i = # of AMP_SUB characters in original string */
    for(ptr = from, i=0; *ptr; ptr++)
       if(*ptr == AMP_SUB)
             i++;
          
    required_space = strlen(from) + (i * 4) + 1;   /* each AMP_SUB requires another 4 chars: "&amp;"  */
   } 
   
   if(!try_xhtml_compatible || (required_space > maxlen))   /* then do it the 'old' way - pages will fail xhtml validation */
    {
	    strncpy (to, from, maxlen);
	    for (ptr = to; *ptr; ptr++)
	      switch (*ptr)
	        {
        	  case QMARK_SUB:
	      		*ptr = '?';
		       	break;
        	  case AMP_SUB:
			*ptr = '&';
			break;
	      	  case EQUAL_SUB:
			*ptr = '=';
		        break;
	      	  case POUND_SUB:
			*ptr = '#';
		        break;
                  default:
		        break;
                 }
    }
   else    /* we can safely substitute "&amp;" for AMP_SUB chars, to support xhtml validation */     
    {
      for(ptr=from, i= 0; *ptr && (i < maxlen-1); ptr++)
       {
         switch (*ptr)
          {
	      	case QMARK_SUB:
			*(to + i++) = '?';
			break;
	      	case AMP_SUB:
		        *(to + i++) = '&';
        		*(to + i++) = 'a';
	          	*(to + i++) = 'm';
        	  	*(to + i++) = 'p';          
          		*(to + i++) = ';';          
	          	break;
      		case EQUAL_SUB:
			*(to + i++) = '=';
			break;
      		case POUND_SUB:
			*(to + i++) = '#';
			break;

      		default:
               		*(to + i++) = *ptr;
			break;
	   }	
	}
	*(to + i) = '\0';
      }	
}

