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

#define MAX 512

/*****************************************
 ******* PREPARE NEW_URL FROM URL ********/
 
int prepare_new_url(int section)
{
 #ifdef DEBUG_NEW_URL
 int i=0;
 #endif
 
 char *k,*k1,tmp[MAX];

 #ifdef DEBUG_NEW_URL
 fprintf(stderr,"prepare url: %s\n",redir[section]->url);
 #endif

 for(k=redir[section]->url,k1=k;*k!=0; k++)
 {
  // #URL#
  if (*k=='#' && *(k+1)=='U' && *(k+2)=='R' && *(k+3)=='L' && *(k+4)=='#')
    {
     memcpy(tmp,k1,k-k1);
     tmp[k-k1]=0;
     k+=5;
     k1=k;
     add_new_url(section,tmp,1);
    }
    
  // #IP#
  if (*k=='#' && *(k+1)=='I' && *(k+2)=='P' && *(k+3)=='#')
    {
     memcpy(tmp,k1,k-k1);
     tmp[k-k1]=0;
     k+=4;
     k1=k;
     add_new_url(section,tmp,2);
    }

  // #IDENT#
  if (*k=='#' && *(k+1)=='I' && *(k+2)=='D' && *(k+3)=='E' && *(k+4)=='N' && *(k+5)=='T' && *(k+6)=='#')
    {
     memcpy(tmp,k1,k-k1);
     tmp[k-k1]=0;
     k+=7;
     k1=k;
     add_new_url(section,tmp,3);
    }

  // #METHOD#
  if (*k=='#' && *(k+1)=='M' && *(k+2)=='E' && *(k+3)=='T' && *(k+4)=='H' && *(k+5)=='O' && *(k+6)=='D' && *(k+7)=='#')
    {
     memcpy(tmp,k1,k-k1);
     tmp[k-k1]=0;
     k+=8;
     k1=k;
     add_new_url(section,tmp,4);
    }

  // #SECTION#
  if (*k=='#' && *(k+1)=='S' && *(k+2)=='E' && *(k+3)=='C' && *(k+4)=='T' && *(k+5)=='I' && *(k+6)=='O' && *(k+7)=='N' && *(k+8)=='#')
    {
     memcpy(tmp,k1,k-k1);
     tmp[k-k1]=0;
     k+=9;
     k1=k;
     add_new_url(section,tmp,5);
    }

 }
  // end of line
  if (k1!=k)
    {
     memcpy(tmp,k1,k-k1);
     tmp[k-k1]=0;
     add_new_url(section,tmp,0);
    }
 #ifdef DEBUG_NEW_URL
  for(i=0;i<redir[section]->new_url_count;i++)
   fprintf(stderr,"%i: %s TYPE:%i\n",i,redir[section]->new_url[i],redir[section]->new_url_inset[i]);
 #endif

 return(0);
}


int add_new_url (int section, char *buf, int inset)
{
   redir[section]->new_url_count++;
   
   //Add memory
    redir[section]->new_url=(char**)realloc(redir[section]->new_url,(redir[section]->new_url_count)*sizeof(char*));
    if (redir[section]->new_url==NULL)
	{
	 err_mes("Error: Can't allocate memory(realoc) for new_url\n");
         exit(-1);
        }
    // Store text
    redir[section]->new_url[redir[section]->new_url_count-1]=strdup(buf);
    if (redir[section]->new_url[redir[section]->new_url_count-1]==NULL)
        {
         err_mes("Error: Can't allocate memory(strdup) for new_url\n");
         exit(-1);
        }
    //Add memory
    redir[section]->new_url_inset=(char*)realloc(redir[section]->new_url_inset,(redir[section]->new_url_count)*sizeof(char*));
    if (redir[section]->new_url_inset==NULL)
	{
	 err_mes("Error: Can't allocate memory(realoc) for new_ur_insetl\n");
         exit(-1);
        }

    // Store type
    redir[section]->new_url_inset[redir[section]->new_url_count-1]=inset;
    
 return(0);
}

