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

#include "globals.h"
#include "functions.h"

/* fix session variables to use $_SESSION */

void insert_session()
{
int t,l;
char temp[256];

  fprintf(out,"<?\n");

  fprintf(out,"  session_start();\n");

  for (t=0; t<sessionptr; t++)
  {
    strcpy(temp,sessionpool[t]);
    l=strlen(temp);
    strcpy(temp+l-1,"_session");

    /* strcpy(sessionpool[t],temp+1); */
    fprintf(out,"  session_register(\"%s\");\n",temp+1);
  }

  fprintf(out,"?>\n");

  add_session=0;
}

int session_registered(char *molecule)
{
int t,l;

  if (molecule[0]!='\'' && molecule[0]!='\"') return -1;

  t=1;

  while (molecule[t]!=0)
  { 
    if (molecule[t]==molecule[0]) break; 

    t++;
  }

  if (molecule[t]==0 || molecule[t+1]!=0) return -1;

  l=strlen(molecule)-2;

  for (t=0; t<sessionptr; t++)
  {
/* printf("%d) %s    %s\n",t,sessionpool[t],molecule+1); */
    if (strncmp(molecule+1,sessionpool[t]+1,l)==0) return t;
  }

  return -1;
}

int parse_session()
{
int tokentype;
char token[TOKENSIZE];
char sessionvar[1024];
char newtoken[LINELENGTH];
int t,l;
char temp[256];

#ifdef DEBUG
printf("in parse_session()\n");
#endif

  tokentype=gettoken(token);
  strcpy(newtoken,"");
  strcpy(sessionvar,"");

  if (strcmp(token,"(")==0)
  {
    push(token,tokentype);

    eval_funct(sessionvar);

    tokentype=gettoken(token);
    if (strcmp(token,"=")!=0)
    { error(token,"=","Session"); }

    t=session_registered(sessionvar);

    eval_molecule(newtoken);
    autoindent();

    if (t!=-1)
    {
      strcpy(temp,sessionpool[t]);
      l=strlen(temp);
      strcpy(temp+l-1,"_session");

      fprintf(out,"$%s=%s;\n",temp+1,newtoken);
    }
      else
    {
      fprintf(out,"session_register(%s);\n",sessionvar);
      fprintf(out,"${%s.\"_session\"}=%s;\n",sessionvar,newtoken);
    }
  }
    else
  if (tokentype==14)
  {
    tokentype=gettoken(token);

    if (strcasecmp(token,"timeout")==0)
    {
      tokentype=gettoken(token);
      if (strcmp(token,"=")!=0)
      { error(token,"=","Session.Timeout"); }

      eval_molecule(newtoken);
      fprintf(out,"// [unsupported] session.timeout=%s;\n",newtoken);
    }
      else
    if (strcasecmp(token,"sessionid")==0)
    {
      tokentype=gettoken(token);
      if (strcmp(token,"=")!=0)
      { error(token,"=","Session.SessionID"); }

      eval_molecule(newtoken);
      fprintf(out,"session_id(%s);\n",newtoken);
    }
  }

  return 0;
}

int parse_session_properties(char *newtoken)
{
char token[TOKENSIZE];
int tokentype;

  tokentype=gettoken(token);

  if (tokentype==14)
  {
    tokentype=gettoken(token);

    if (strcasecmp(token,"sessionid")==0)
    { sprintf(newtoken,"session_id()"); }
  }
    else
  {
    error(token,".","Session");
  }

  return 0;
}


