* remove old (replaced) code
[citadel.git] / webcit / subst.c
index 36630a89ca6b0663657c5d064cb9ba48a465ff6d..05f03c6b925d0bf658915418d88a16ef26cbe57b 100644 (file)
@@ -29,14 +29,16 @@ HashList *LocalTemplateCache;
 
 HashList *GlobalNS;
 HashList *Iterators;
-HashList *Contitionals;
+HashList *Conditionals;
 
 int LoadTemplates = 0;
 
 #define SV_GETTEXT 1
 #define SV_CONDITIONAL 2
 #define SV_NEG_CONDITIONAL 3
-#define SV_SUBTEMPL 4
+#define SV_CUST_STR_CONDITIONAL 4
+#define SV_SUBTEMPL 5
+#define SV_PREEVALUATED 6
 
 typedef struct _WCTemplate {
        StrBuf *Data;
@@ -49,12 +51,18 @@ typedef struct _WCTemplate {
 typedef struct _HashHandler {
        int nMinArgs;
        int nMaxArgs;
+       int ContextRequired;
        WCHandlerFunc HandlerFunc;
 }HashHandler;
 
 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere);
 
-void RegisterNS(const char *NSName, long len, int nMinArgs, int nMaxArgs, WCHandlerFunc HandlerFunc)
+void RegisterNS(const char *NSName, 
+               long len, 
+               int nMinArgs, 
+               int nMaxArgs, 
+               WCHandlerFunc HandlerFunc, 
+               int ContextRequired)
 {
        HashHandler *NewHandler;
        
@@ -62,9 +70,39 @@ void RegisterNS(const char *NSName, long len, int nMinArgs, int nMaxArgs, WCHand
        NewHandler->nMinArgs = nMinArgs;
        NewHandler->nMaxArgs = nMaxArgs;
        NewHandler->HandlerFunc = HandlerFunc;  
+       NewHandler->ContextRequired = ContextRequired;
        Put(GlobalNS, NSName, len, NewHandler, NULL);
 }
 
+void FreeToken(WCTemplateToken **Token)
+{
+       int i; 
+       FreeStrBuf(&(*Token)->FlatToken);
+       if ((*Token)->HaveParameters) 
+               for (i = 0; i < (*Token)->nParameters; i++)
+                       free((*Token)->Params[i]);
+       free(*Token);
+       *Token = NULL;
+}
+
+
+
+void FreeWCTemplate(void *vFreeMe)
+{
+       int i;
+       WCTemplate *FreeMe = (WCTemplate*)vFreeMe;
+
+       if (FreeMe->TokenSpace > 0) {
+               for (i = 0; i < FreeMe->nTokensUsed; i ++) {
+                       FreeToken(&FreeMe->Tokens[i]);
+               }
+               free(FreeMe->Tokens);
+       }
+       FreeStrBuf(&FreeMe->FileName);
+       FreeStrBuf(&FreeMe->Data);
+       free(FreeMe);
+}
+
 
 /**
  * \brief debugging function to print array to log
@@ -166,6 +204,7 @@ void FlushPayload(wcsubst *ptr, int reusestrbuf, int type)
        }
 }
 
+
 /**
  * \brief destructor; kill one entry.
  */
@@ -344,7 +383,7 @@ void SVPutLong(char *keyname, size_t keylen, long Data)
  * \param keyname the keystring to substitute
  * \param fcn_ptr the function callback to give the substitution string
  */
-void SVCallback(char *keyname, size_t keylen, var_callback_fptr fcn_ptr)
+void SVCallback(char *keyname, size_t keylen, WCHandlerFunc fcn_ptr)
 {
        wcsubst *ptr;
        void *vPtr;
@@ -367,14 +406,14 @@ void SVCallback(char *keyname, size_t keylen, var_callback_fptr fcn_ptr)
 
        ptr->wcs_function = fcn_ptr;
 }
-inline void SVCALLBACK(char *keyname, var_callback_fptr fcn_ptr)
+inline void SVCALLBACK(char *keyname, WCHandlerFunc fcn_ptr)
 {
        SVCallback(keyname, strlen(keyname), fcn_ptr);
 }
 
 
 
-void SVPUTBuf(const char *keyname, int keylen, StrBuf *Buf, int ref)
+void SVPUTBuf(const char *keyname, int keylen, const StrBuf *Buf, int ref)
 {
        wcsubst *ptr;
        void *vPtr;
@@ -394,7 +433,7 @@ void SVPUTBuf(const char *keyname, int keylen, StrBuf *Buf, int ref)
        {
                ptr = NewSubstVar(keyname, keylen, (ref)?WCS_STRBUF_REF:WCS_STRBUF);
        }
-       ptr->wcs_value = Buf;
+       ptr->wcs_value = (StrBuf*)Buf;
 }
 
 /**
@@ -424,26 +463,116 @@ void pvo_do_cmd(StrBuf *Target, StrBuf *servcmd) {
        }
 }
 
+
+/**
+ * \brief puts string into the template and computes which escape methon we should use
+ * \param Source the string we should put into the template
+ * \param FormatTypeIndex where should we look for escape types if?
+ */
+void StrBufAppendTemplate(StrBuf *Target, 
+                         int nArgs, 
+                         WCTemplateToken *Tokens,
+                         void *Context, int ContextType,
+                         const StrBuf *Source, int FormatTypeIndex)
+{
+        struct wcsession *WCC;
+       StrBuf *Buf;
+       char EscapeAs = ' ';
+
+       if ((FormatTypeIndex < Tokens->nParameters) &&
+           (Tokens->Params[FormatTypeIndex]->Type == TYPE_STR) &&
+           (Tokens->Params[FormatTypeIndex]->len == 1)) {
+               EscapeAs = *Tokens->Params[FormatTypeIndex]->Start;
+       }
+
+       switch(EscapeAs)
+       {
+       case 'H':
+               WCC = WC;
+               Buf = NewStrBufPlain(NULL, StrLength(Buf));
+               StrBuf_RFC822_to_Utf8(Buf, 
+                                     Source, 
+                                     (WCC!=NULL)? WCC->DefaultCharset : NULL, 
+                                     NULL);
+               StrEscAppend(Target, Buf, NULL, 0, 0);
+               FreeStrBuf(&Buf);
+               break;
+       case 'X':
+               StrEscAppend(Target, Source, NULL, 0, 0);
+               break;
+       default:
+               StrBufAppendBuf(Target, Source, 0);
+       }
+}
+
+
+void GetTemplateTokenString(WCTemplateToken *Tokens,
+                           int N, 
+                           const char **Value, 
+                           long *len)
+{
+       StrBuf *Buf;
+
+       if (Tokens->nParameters < N) {
+               *Value = "";
+               *len = 0;
+               return;
+       }
+
+       switch (Tokens->Params[N]->Type) {
+
+       case TYPE_STR:
+               *Value = Tokens->Params[N]->Start;
+               *len = Tokens->Params[N]->len;
+               break;
+       case TYPE_BSTR:
+               Buf = (StrBuf*) SBstr(Tokens->Params[N]->Start, 
+                                     Tokens->Params[N]->len);
+               *Value = ChrPtr(Buf);
+               *len = StrLength(Buf);
+               break;
+       case TYPE_PREFSTR:
+               get_PREFERENCE(
+                       Tokens->Params[N]->Start, 
+                       Tokens->Params[N]->len, 
+                       &Buf);
+               *Value = ChrPtr(Buf);
+               *len = StrLength(Buf);
+               break;
+       case TYPE_LONG:
+       case TYPE_PREFINT:
+               break; ///todo: string to text?
+       case TYPE_GETTEXT:
+               *Value = _(Tokens->Params[N]->Start);
+               *len = strlen(*Value);
+               break;
+       default:
+               break;
+//todo log error
+       }
+}
+
+
+
 /**
  * \brief Print the value of a variable
  * \param keyname get a key to print
  */
-void print_value_of(StrBuf *Target, const char *keyname, size_t keylen) {
+void print_value_of(StrBuf *Target, WCTemplateToken *Tokens, void *Context, int ContextType) {
        struct wcsession *WCC = WC;
        wcsubst *ptr;
-       void *fcn();
        void *vVar;
 
        /*if (WCC->vars != NULL) PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
        /// TODO: debricated!
-       if (keyname[0] == '=') {
-               DoTemplate(keyname+1, keylen - 1, NULL, NULL);
+       if (Tokens->pName[0] == '=') {
+               DoTemplate(Tokens->pName+1, Tokens->NameEnd - 1, NULL, NULL, 0);
        }
 
 //////TODO: if param[1] == "U" -> urlescape
 /// X -> escputs
        /** Page-local variables */
-       if ((WCC->vars!= NULL) && GetHash(WCC->vars, keyname, keylen, &vVar)) {
+       if ((WCC->vars!= NULL) && GetHash(WCC->vars, Tokens->pName, Tokens->NameEnd, &vVar)) {
                ptr = (wcsubst*) vVar;
                switch(ptr->wcs_type) {
                case WCS_STRING:
@@ -453,7 +582,7 @@ void print_value_of(StrBuf *Target, const char *keyname, size_t keylen) {
                        pvo_do_cmd(Target, ptr->wcs_value);
                        break;
                case WCS_FUNCTION:
-                       (*ptr->wcs_function) ();
+                       (*ptr->wcs_function) (Target, Tokens->nParameters, Tokens, Context, ContextType);
                        break;
                case WCS_STRBUF:
                case WCS_STRBUF_REF:
@@ -463,9 +592,87 @@ void print_value_of(StrBuf *Target, const char *keyname, size_t keylen) {
                        StrBufAppendPrintf(Target, "%ld", ptr->lvalue);
                        break;
                default:
-                       lprintf(1,"WARNING: invalid value in SV-Hash at %s!", keyname);
+                       lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", Tokens->pName);
+                       StrBufAppendPrintf(Target, "<pre>WARNING: \ninvalid value in SV-Hash at %s!\n</pre>", Tokens->pName);
                }
        }
+       else {
+               lprintf(1, "didn't find Handler [%s] (in '%s' line %ld); "
+                       " [%s]\n", 
+                       Tokens->pName,
+                       ChrPtr(Tokens->FileName),
+                       Tokens->Line,
+                       ChrPtr(Tokens->FlatToken));
+               wc_backtrace();
+       }
+}
+
+int CompareSubstToToken(TemplateParam *ParamToCompare, TemplateParam *ParamToLookup)
+{
+       struct wcsession *WCC = WC;
+       wcsubst *ptr;
+       void *vVar;
+
+       if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
+                                         ParamToLookup->len, &vVar)) {
+               ptr = (wcsubst*) vVar;
+               switch(ptr->wcs_type) {
+               case WCS_STRING:
+               case WCS_STRBUF:
+               case WCS_STRBUF_REF:
+                       if (ParamToCompare->Type == TYPE_STR)
+                               return ((ParamToCompare->len == StrLength(ptr->wcs_value)) &&
+                                       (strcmp(ParamToCompare->Start, ChrPtr(ptr->wcs_value)) == 0));
+                       else
+                               return ParamToCompare->lvalue == StrTol(ptr->wcs_value);
+                       break;
+               case WCS_SERVCMD:
+                       return 1; 
+                       break;
+               case WCS_FUNCTION:
+                       return 1;
+               case WCS_LONG:
+                       if (ParamToCompare->Type == TYPE_STR)
+                               return 0;
+                       else 
+                               return ParamToCompare->lvalue == ptr->lvalue;
+                       break;
+               default:
+                       lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
+                               ParamToLookup->Start);
+               }
+       }
+       return 0;
+}
+
+int CompareSubstToStrBuf(StrBuf *Compare, TemplateParam *ParamToLookup)
+{
+       struct wcsession *WCC = WC;
+       wcsubst *ptr;
+       void *vVar;
+
+       if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
+                                         ParamToLookup->len, &vVar)) {
+               ptr = (wcsubst*) vVar;
+               switch(ptr->wcs_type) {
+               case WCS_STRING:
+               case WCS_STRBUF:
+               case WCS_STRBUF_REF:
+                       return ((StrLength(Compare) == StrLength(ptr->wcs_value)) &&
+                               (strcmp(ChrPtr(Compare), ChrPtr(ptr->wcs_value)) == 0));
+               case WCS_SERVCMD:
+                       return 1; 
+                       break;
+               case WCS_FUNCTION:
+                       return 1;
+               case WCS_LONG:
+                       return StrTol(Compare) == ptr->lvalue;
+               default:
+                       lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
+                               ParamToLookup->Start);
+               }
+       }
+       return 0;
 }
 
 
@@ -492,18 +699,40 @@ void PutNewToken(WCTemplate *Template, WCTemplateToken *NewToken)
        Template->Tokens[(Template->nTokensUsed)++] = NewToken;
 }
 
-TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe)
+TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe, WCTemplateToken *Tokens, WCTemplate *pTmpl)
 {
        const char *pch = *pCh;
        const char *pchs, *pche;
        TemplateParam *Parm = (TemplateParam *) malloc(sizeof(TemplateParam));
        char quote = '\0';
        
+
+       Parm->Type = TYPE_STR;
+
        /* Skip leading whitespaces */
        while ((*pch == ' ' )||
               (*pch == '\t')||
               (*pch == '\r')||
               (*pch == '\n')) pch ++;
+
+       if (*pch == ':') {
+               Parm->Type = TYPE_PREFSTR;
+               pch ++;
+       }
+       else if (*pch == ';') {
+               Parm->Type = TYPE_PREFINT;
+               pch ++;
+       }
+       else if (*pch == '_') {
+               Parm->Type = TYPE_GETTEXT;
+               pch ++;
+       }
+       else if (*pch == 'B') {
+               Parm->Type = TYPE_BSTR;
+               pch ++;
+       }
+
+
        if (*pch == '"')
                quote = '"';
        else if (*pch == '\'')
@@ -511,7 +740,6 @@ TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe)
        if (quote != '\0') {
                pch ++;
                pchs = pch;
-               Parm->Type = TYPE_STR;
                while (pch <= pe &&
                       ((*pch != quote) ||
                        ( (pch > pchs) && (*(pch - 1) == '\\'))
@@ -520,14 +748,22 @@ TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe)
                }
                pche = pch;
                if (*pch != quote) {
-                       lprintf(1, "Error evaluating template param [%s]\n", *pCh);
+                       lprintf(1, "Error (in '%s' line %ld); "
+                               "evaluating template param [%s] in Token [%s]\n",
+                               ChrPtr(pTmpl->FileName),
+                               Tokens->Line,
+                               ChrPtr(Tokens->FlatToken),
+                               *pCh);
                        pch ++;
                        free(Parm);
                        return NULL;
                }
                else {
                        StrBufPeek(Buf, pch, -1, '\0');         
-                       lprintf(1, "DBG: got param [%s]\n", pchs);
+                       if (LoadTemplates > 1) {                        
+                               lprintf(1, "DBG: got param [%s] %ld %ld\n", 
+                                       pchs, pche - pchs, strlen(pchs));
+                       }
                        Parm->Start = pchs;
                        Parm->len = pche - pchs;
                        pch ++; /* move after trailing quote */
@@ -550,7 +786,12 @@ TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe)
                }
                else {
                        Parm->lvalue = 0;
-                       lprintf(1, "Error evaluating template long param [%s]\n", *pCh);
+                       lprintf(1, "Error (in '%s' line %ld); "
+                               "evaluating long template param [%s] in Token [%s]\n",
+                               ChrPtr(pTmpl->FileName),
+                               Tokens->Line,
+                               ChrPtr(Tokens->FlatToken),
+                               *pCh);
                        free(Parm);
                        return NULL;
                }
@@ -568,18 +809,25 @@ TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe)
 WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf, 
                                       const char *pStart, 
                                       const char *pTmplStart, 
-                                      const char *pTmplEnd)
+                                      const char *pTmplEnd, 
+                                      long Line,
+                                      WCTemplate *pTmpl)
 {
+       void *vVar;
        const char *pch;
        TemplateParam *Param;
        WCTemplateToken *NewToken = (WCTemplateToken*)malloc(sizeof(WCTemplateToken));
 
+       NewToken->FileName = pTmpl->FileName; /* to print meaningfull log messages... */
        NewToken->Flags = 0;
+       NewToken->Line = Line + 1;
        NewToken->pTokenStart = pTmplStart;
        NewToken->TokenStart = pTmplStart - pStart;
        NewToken->TokenEnd =  (pTmplEnd - pStart) - NewToken->TokenStart;
        NewToken->pTokenEnd = pTmplEnd;
        NewToken->NameEnd = NewToken->TokenEnd - 2;
+       NewToken->PreEval = NULL;
+       NewToken->FlatToken = NewStrBufPlain(pTmplStart + 2, pTmplEnd - pTmplStart - 2);
        
        StrBufPeek(Buf, pTmplStart, + 1, '\0');
        StrBufPeek(Buf, pTmplEnd, -1, '\0');
@@ -593,13 +841,26 @@ WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf,
                        StrBufPeek(Buf, pch, -1, '\0');
                        NewToken->NameEnd = pch - NewToken->pName;
                        pch ++;
+                       if (*(pTmplEnd - 1) != ')') {
+                               lprintf(1, "Warning, Non welformed Token; missing right parenthesis (in '%s' line %ld); "
+                                       "[%s]\n", 
+                                       ChrPtr(pTmpl->FileName),
+                                       NewToken->Line,
+                                       ChrPtr(NewToken->FlatToken));
+                       }
                        while (pch < pTmplEnd - 1) {
-                               Param = GetNextParameter(Buf, &pch, pTmplEnd - 1);
+                               Param = GetNextParameter(Buf, &pch, pTmplEnd - 1, NewToken, pTmpl);
                                if (Param != NULL) {
                                        NewToken->HaveParameters = 1;
                                        if (NewToken->nParameters > MAXPARAM) {
-                                               lprintf(1, "Only %ld Tokens supported!\n", MAXPARAM);
+                                               lprintf(1, "Error (in '%s' line %ld); "
+                                                       "only [%ld] Params allowed in Tokens [%s]\n",
+                                                       ChrPtr(pTmpl->FileName),
+                                                       NewToken->Line,
+                                                       MAXPARAM,
+                                                       ChrPtr(NewToken->FlatToken));
                                                free(Param);
+                                               FreeToken(&NewToken);
                                                return NULL;
                                        }
                                        NewToken->Params[NewToken->nParameters++] = Param;
@@ -610,135 +871,303 @@ WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf,
                           (NewToken->HaveParameters == 1))
                           
                        {
-                               if ((NewToken->nParameters == 1) &&
-                                   (*(NewToken->pName) == '_'))
+                               if (*(NewToken->pName) == '_')
                                        NewToken->Flags = SV_GETTEXT;
-                               else if ((NewToken->nParameters == 1) &&
-                                        (*(NewToken->pName) == '='))
+                               else if (*(NewToken->pName) == '=')
                                        NewToken->Flags = SV_SUBTEMPL;
-                               else if ((NewToken->nParameters >= 2) &&
-                                        (*(NewToken->pName) == '?'))
+                               else if (*(NewToken->pName) == '%')
+                                       NewToken->Flags = SV_CUST_STR_CONDITIONAL;
+                               else if (*(NewToken->pName) == '?')
                                        NewToken->Flags = SV_CONDITIONAL;
-                               else if ((NewToken->nParameters >=2) &&
-                                        (*(NewToken->pName) == '!'))
+                               else if (*(NewToken->pName) == '!')
                                        NewToken->Flags = SV_NEG_CONDITIONAL;
                        }
                }
                else pch ++;            
        }
-       return NewToken;
-}
-
-void FreeToken(WCTemplateToken **Token)
-{
-       int i; 
-       if ((*Token)->HaveParameters) 
-               for (i = 0; i < (*Token)->nParameters; i++)
-                       free((*Token)->Params[i]);
-       free(*Token);
-       *Token = NULL;
-}
-
-
-
-void FreeWCTemplate(void *vFreeMe)
-{
-       int i;
-       WCTemplate *FreeMe = (WCTemplate*)vFreeMe;
-
-       if (FreeMe->TokenSpace > 0) {
-               for (i = 0; i < FreeMe->nTokensUsed; i ++) {
-                       FreeToken(&FreeMe->Tokens[i]);
+       
+       switch (NewToken->Flags) {
+       case 0:
+               /* If we're able to find out more about the token, do it now while its fresh. */
+               if (GetHash(GlobalNS, NewToken->pName, NewToken->NameEnd, &vVar)) {
+                       HashHandler *Handler;
+                       Handler = (HashHandler*) vVar;
+                       if ((NewToken->nParameters < Handler->nMinArgs) || 
+                           (NewToken->nParameters > Handler->nMaxArgs)) {
+                               lprintf(1, "Handler [%s] (in '%s' line %ld); "
+                                       "doesn't work with %ld params [%s]\n", 
+                                       NewToken->pName,
+                                       ChrPtr(pTmpl->FileName),
+                                       NewToken->Line,
+                                       NewToken->nParameters, 
+                                       ChrPtr(NewToken->FlatToken));
+                       }
+                       else {
+                               NewToken->PreEval = Handler;
+                               NewToken->Flags = SV_PREEVALUATED;              
+                       }
                }
-               free(FreeMe->Tokens);
+               break;
+       case SV_GETTEXT:
+               if (NewToken->nParameters !=1) {
+                       lprintf(1, "Gettext (in '%s' line %ld); "
+                               "requires exactly 1 parameter, you gave %ld params [%s]\n", 
+                               ChrPtr(pTmpl->FileName),
+                               NewToken->Line,
+                               NewToken->nParameters, 
+                               ChrPtr(NewToken->FlatToken));
+                       NewToken->Flags = 0;
+                       break;
+               }
+               break;
+       case SV_SUBTEMPL:
+               if (NewToken->nParameters != 1) {
+                       lprintf(1, "Subtemplates (in '%s' line %ld); "
+                               "require exactly 1 parameter, you gave %ld params [%s]\n", 
+                               ChrPtr(pTmpl->FileName),
+                               NewToken->Line,
+                               NewToken->nParameters, 
+                               ChrPtr(NewToken->FlatToken));
+                       break;
+               }
+               break;
+       case SV_CUST_STR_CONDITIONAL:
+       case SV_CONDITIONAL:
+       case SV_NEG_CONDITIONAL:
+               if (NewToken->nParameters <2) {
+                       lprintf(1, "Conditional (in '%s' line %ld); "
+                               "require at least 2 parameters, you gave %ld params [%s]\n", 
+                               ChrPtr(pTmpl->FileName),
+                               NewToken->Line,
+                               NewToken->nParameters, 
+                               ChrPtr(NewToken->FlatToken));
+                       NewToken->Flags = 0;
+                       break;
+               }
+               if (!GetHash(Conditionals, 
+                            NewToken->Params[0]->Start,
+                            NewToken->Params[0]->len,
+                            &vVar) || 
+                   (vVar == NULL)) {
+                       if ((NewToken->Params[0]->len == 1) &&
+                           (NewToken->Params[0]->Start[0] == 'X'))
+                               break;
+                       lprintf(1, "Conditional [%s] (in '%s' line %ld); Not found![%s]\n", 
+                               NewToken->Params[0]->Start,
+                               ChrPtr(pTmpl->FileName),
+                               NewToken->Line,
+                               ChrPtr(NewToken->FlatToken));
+/*
+                       NewToken->Error = NewStrBuf();
+                       StrBufAppendPrintf(
+                               NewToken->Error, 
+                               "<pre>\nConditional [%s] (in '%s' line %ld); Not found!\n[%s]\n</pre>\n", 
+                               NewToken->Params[0]->Start,
+                               ChrPtr(pTmpl->FileName),
+                               NewToken->Line,
+                               ChrPtr(NewToken->FlatToken));
+*/
+               }
+               else {
+                       NewToken->PreEval = vVar;
+               }
+               break;
        }
-       FreeStrBuf(&FreeMe->FileName);
-       FreeStrBuf(&FreeMe->Data);
-       free(FreeMe);
+       return NewToken;
 }
 
 
-int EvaluateConditional(WCTemplateToken *Token, void *Context, int Neg, int state)
+
+int EvaluateConditional(StrBuf *Target, WCTemplateToken *Tokens, WCTemplate *pTmpl, void *Context, int Neg, int state, int ContextType)
 {
-       void *vConditional;
        ConditionalStruct *Cond;
 
-       if ((Token->Params[0]->len == 1) &&
-           (Token->Params[0]->Start[0] == 'X'))
-               return (state != 0)?Token->Params[1]->lvalue:0;
-
-       if (!GetHash(Contitionals, 
-                Token->Params[0]->Start,
-                Token->Params[0]->len,
-                &vConditional)) {
-               lprintf(1, "Conditional %s Not found!\n", 
-                       Token->Params[0]->Start);
-       }
+       if ((Tokens->Params[0]->len == 1) &&
+           (Tokens->Params[0]->Start[0] == 'X'))
+               return (state != 0)?Tokens->Params[1]->lvalue:0;
            
-       Cond = (ConditionalStruct *) vConditional;
-
+       Cond = (ConditionalStruct *) Tokens->PreEval;
        if (Cond == NULL) {
-               lprintf(1, "Conditional %s Not found!\n", 
-                       Token->Params[0]->Start);
-               return 0;
+               lprintf(1, "Conditional [%s] (in '%s' line %ld); unknown![%s]\n", 
+                       Tokens->Params[0]->Start,
+                       ChrPtr(pTmpl->FileName),
+                       Tokens->Line,
+                       ChrPtr(Tokens->FlatToken));
+               return 1;
        }
-       if (Token->nParameters < Cond->nParams) {
-               lprintf(1, "Conditional [%s] needs %ld Params!\n", 
-                       Token->Params[0]->Start,
-                       Cond->nParams);
+
+       if (Tokens->nParameters < Cond->nParams) {
+               lprintf(1, "Conditional [%s] (in '%s' line %ld); needs %ld Params![%s]\n", 
+                       Tokens->Params[0]->Start,
+                       ChrPtr(pTmpl->FileName),
+                       Tokens->Line,
+                       Cond->nParams,
+                       ChrPtr(Tokens->FlatToken));
+               StrBufAppendPrintf(
+                       Target, 
+                       "<pre>\nConditional [%s] (in '%s' line %ld); needs %ld Params!\n[%s]\n</pre>\n", 
+                       Tokens->Params[0]->Start,
+                       ChrPtr(pTmpl->FileName),
+                       Tokens->Line,
+                       Cond->nParams,
+                       ChrPtr(Tokens->FlatToken));
                return 0;
        }
-       if (Cond->CondF(Token, Context) == Neg)
-               return Token->Params[1]->lvalue;
+       if (Cond->CondF(Tokens, Context, ContextType) == Neg)
+               return Tokens->Params[1]->lvalue;
        return 0;
 }
 
-int EvaluateToken(StrBuf *Target, WCTemplateToken *Token, void *Context, int state)
+/**
+ * \brief executes one token
+ * \param Target buffer to append to
+ * \param Token da to  process.
+ * \param Template we're iterating
+ * \param Context Contextpoointer to pass in
+ * \param state are we in conditional state?
+ * \param ContextType what type of information does context giv us?
+ */
+int EvaluateToken(StrBuf *Target, WCTemplateToken *Tokens, WCTemplate *pTmpl, void *Context, int state, int ContextType)
 {
+       HashHandler *Handler;
        void *vVar;
 // much output, since pName is not terminated...
 //     lprintf(1,"Doing token: %s\n",Token->pName);
-       switch (Token->Flags) {
+
+       switch (Tokens->Flags) {
        case SV_GETTEXT:
-               TmplGettext(Target, Token->nParameters, Token);
+               TmplGettext(Target, Tokens->nParameters, Tokens);
                break;
-       case SV_CONDITIONAL:
-               return EvaluateConditional(Token, Context, 1, state);
+       case SV_CONDITIONAL: /** Forward conditional evaluation */
+               return EvaluateConditional(Target, Tokens, pTmpl, Context, 1, state, ContextType);
                break;
-       case SV_NEG_CONDITIONAL:
-               return EvaluateConditional(Token, Context, 0, state);
+       case SV_NEG_CONDITIONAL: /** Reverse conditional evaluation */
+               return EvaluateConditional(Target, Tokens, pTmpl, Context, 0, state, ContextType);
+               break;
+       case SV_CUST_STR_CONDITIONAL: /** Conditional put custom strings from params */
+               if (Tokens->nParameters >= 6) {
+                       if (EvaluateConditional(Target, Tokens, pTmpl, Context, 0, state, ContextType))
+                               StrBufAppendBufPlain(Target, 
+                                                    Tokens->Params[5]->Start,
+                                                    Tokens->Params[5]->len,
+                                                    0);
+                       else
+                               StrBufAppendBufPlain(Target, 
+                                                    Tokens->Params[4]->Start,
+                                                    Tokens->Params[4]->len,
+                                                    0);
+               }
+               else  {
+                       lprintf(1, "Conditional [%s] (in '%s' line %ld); needs at least 6 Params![%s]\n", 
+                               Tokens->Params[0]->Start,
+                               ChrPtr(pTmpl->FileName),
+                               Tokens->Line,
+                               ChrPtr(Tokens->FlatToken));
+                       StrBufAppendPrintf(
+                               Target, 
+                               "<pre>\nConditional [%s] (in '%s' line %ld); needs 6 Params!\n[%s]\n</pre>\n", 
+                               Tokens->Params[0]->Start,
+                               ChrPtr(pTmpl->FileName),
+                               Tokens->Line,
+                               ChrPtr(Tokens->FlatToken));
+               }
                break;
        case SV_SUBTEMPL:
-               if (Token->nParameters == 1)
-                       DoTemplate(Token->Params[0]->Start, Token->Params[0]->len, NULL, NULL);
+               if (Tokens->nParameters == 1)
+                       DoTemplate(Tokens->Params[0]->Start, Tokens->Params[0]->len, NULL, NULL, ContextType);
                break;
+       case SV_PREEVALUATED:
+               Handler = (HashHandler*) Tokens->PreEval;
+               if ((Handler->ContextRequired != CTX_NONE) &&
+                   (Handler->ContextRequired != ContextType)) {
+                       lprintf(1, "Handler [%s] (in '%s' line %ld); "
+                               "requires context of type %ld, have %ld [%s]\n", 
+                               Tokens->pName,
+                               ChrPtr(pTmpl->FileName),
+                               Tokens->Line,
+                               Handler->ContextRequired, 
+                               ContextType,
+                               ChrPtr(Tokens->FlatToken));
+                       StrBufAppendPrintf(
+                               Target, 
+                               "<pre>\nHandler [%s] (in '%s' line %ld);"
+                               " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
+                               Tokens->pName,
+                               ChrPtr(pTmpl->FileName),
+                               Tokens->Line,
+                               Handler->ContextRequired, 
+                               ContextType,
+                               ChrPtr(Tokens->FlatToken));
+                       return -1;
+
+               }
+               Handler->HandlerFunc(Target, 
+                                    Tokens->nParameters,
+                                    Tokens,
+                                    Context, 
+                                    ContextType); 
+               break;          
        default:
-               if (GetHash(GlobalNS, Token->pName, Token->NameEnd, &vVar)) {
-                       HashHandler *Handler;
+               if (GetHash(GlobalNS, Tokens->pName, Tokens->NameEnd, &vVar)) {
                        Handler = (HashHandler*) vVar;
-                       if ((Token->nParameters < Handler->nMinArgs) || 
-                           (Token->nParameters > Handler->nMaxArgs)) {
-                               lprintf(1, "Handler [%s] doesn't work with %ld params", 
-                                       Token->pName,
-                                       Token->nParameters);
+                       if ((Handler->ContextRequired != CTX_NONE) &&
+                           (Handler->ContextRequired != ContextType)) {
+                               lprintf(1, "Handler [%s] (in '%s' line %ld); "
+                                       "requires context of type %ld, have %ld [%s]\n", 
+                                       Tokens->pName,
+                                       ChrPtr(pTmpl->FileName),
+                                       Tokens->Line,
+                                       Handler->ContextRequired, 
+                                       ContextType,
+                                       ChrPtr(Tokens->FlatToken));
+                               StrBufAppendPrintf(
+                                       Target, 
+                                       "<pre>\nHandler [%s] (in '%s' line %ld);"
+                                       " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
+                                       Tokens->pName,
+                                       ChrPtr(pTmpl->FileName),
+                                       Tokens->Line,
+                                       Handler->ContextRequired, 
+                                       ContextType,
+                                       ChrPtr(Tokens->FlatToken));
+                               return -1;
+                       }
+                       else if ((Tokens->nParameters < Handler->nMinArgs) || 
+                                (Tokens->nParameters > Handler->nMaxArgs)) {
+                               lprintf(1, "Handler [%s] (in '%s' line %ld); "
+                                       "doesn't work with %ld params [%s]\n", 
+                                       Tokens->pName,
+                                       ChrPtr(pTmpl->FileName),
+                                       Tokens->Line,
+                                       Tokens->nParameters, 
+                                       ChrPtr(Tokens->FlatToken));
+                               StrBufAppendPrintf(
+                                       Target, 
+                                       "<pre>\nHandler [%s] (in '%s' line %ld);"
+                                       " doesn't work with %ld params!\n[%s]\n</pre>\n", 
+                                       Tokens->pName,
+                                       ChrPtr(pTmpl->FileName),
+                                       Tokens->Line,
+                                       Tokens->nParameters,
+                                       ChrPtr(Tokens->FlatToken));
                        }
                        else {
                                Handler->HandlerFunc(Target, 
-                                                    Token->nParameters,
-                                                    Token,
-                                                    Context); /*TODO: subset of that */
-                               
+                                                    Tokens->nParameters,
+                                                    Tokens,
+                                                    Context
+                                                    ContextType); /*TODO: subset of that */
                                
                        }
                }
                else {
-                       print_value_of(Target, Token->pName, Token->NameEnd);
+                       print_value_of(Target, Tokens, Context, ContextType);
                }
        }
        return 0;
 }
 
-void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context)
+void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context, int ContextType)
 {
        WCTemplate *pTmpl = Tmpl;
        int done = 0;
@@ -746,8 +1175,20 @@ void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context)
        const char *pData, *pS;
        long len;
 
-       if (LoadTemplates != 0) {
+       if (LoadTemplates != 0) {                       
+               if (LoadTemplates > 1)
+                       lprintf(1, "DBG: ----- loading:  [%s] ------ \n", 
+                               ChrPtr(Tmpl->FileName));
+
                pTmpl = load_template(Tmpl->FileName, NULL, NULL);
+               if(pTmpl == NULL) {
+                       StrBufAppendPrintf(
+                               Target, 
+                               "<pre>\nError loading Template [%s]\n See Logfile for details\n</pre>\n", 
+                               ChrPtr(Tmpl->FileName));
+                       return;
+               }
+
        }
 
        pS = pData = ChrPtr(pTmpl->Data);
@@ -765,16 +1206,20 @@ void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context)
                        StrBufAppendBufPlain(
                                Target, pData, 
                                pTmpl->Tokens[i]->pTokenStart - pData, 0);
-                       state = EvaluateToken(Target, pTmpl->Tokens[i], Context, state);
+                       state = EvaluateToken(Target, pTmpl->Tokens[i], pTmpl, Context, state, ContextType);
                        while ((state != 0) && (i+1 < pTmpl->nTokensUsed)) {
                        /* condition told us to skip till its end condition */
                                i++;
                                if ((pTmpl->Tokens[i]->Flags == SV_CONDITIONAL) ||
                                    (pTmpl->Tokens[i]->Flags == SV_NEG_CONDITIONAL)) {
-                                       if (state == EvaluateConditional(pTmpl->Tokens[i], 
-                                                                        Context, 
-                                                                        pTmpl->Tokens[i]->Flags,
-                                                                        state))
+                                       if (state == EvaluateConditional(
+                                                   Target,
+                                                   pTmpl->Tokens[i], 
+                                                   pTmpl,
+                                                   Context, 
+                                                   pTmpl->Tokens[i]->Flags,
+                                                   state, 
+                                                   ContextType))
                                                state = 0;
                                }
                        }
@@ -816,6 +1261,7 @@ void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
        int fd;
        struct stat statbuf;
        const char *pS, *pE, *pch, *Err;
+       long Line;
        int pos;
        WCTemplate *NewTemplate;
 
@@ -834,7 +1280,7 @@ void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
 
        NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
        NewTemplate->Data = NewStrBufPlain(NULL, statbuf.st_size);
-       NewTemplate->FileName = NULL;
+       NewTemplate->FileName = NewStrBufDup(filename);
        NewTemplate->nTokensUsed = 0;
        NewTemplate->TokenSpace = 0;
        NewTemplate->Tokens = NULL;
@@ -847,20 +1293,26 @@ void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
        }
        close(fd);
 
+       Line = 0;
        pS = pch = ChrPtr(NewTemplate->Data);
        pE = pS + StrLength(NewTemplate->Data);
        while (pch < pE) {
                const char *pts, *pte;
                int InQuotes = 0;
                int InDoubleQuotes = 0;
+
+               /** Find one <? > */
                pos = (-1);
                for (; pch < pE; pch ++) {
                        if ((*pch=='<')&&(*(pch + 1)=='?'))
                                break;
+                       if (*pch=='\n') Line ++;
                }
                if (pch >= pE)
                        continue;
                pts = pch;
+
+               /** Found one? parse it. */
                for (; pch < pE - 1; pch ++) {
                        if (*pch == '"')
                                InDoubleQuotes = ! InDoubleQuotes;
@@ -876,7 +1328,7 @@ void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
                        continue;
                pte = pch;
                PutNewToken(NewTemplate, 
-                           NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte));
+                           NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte, Line, NewTemplate));
                pch ++;
        }
        if (LoadTemplates == 0)
@@ -884,11 +1336,22 @@ void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
        return NewTemplate;
 }
 
+
+///void PrintTemplate(const char *Key, void *vSubst, int odd)
+const char* PrintTemplate(void *vSubst)
+{
+       WCTemplate *Tmpl = vSubst;
+
+       return ChrPtr(Tmpl->FileName);
+
+}
+
+
 /**
  * \brief Display a variable-substituted template
  * \param templatename template file to load
  */
-void DoTemplate(const char *templatename, long len, void *Context, StrBuf *Target
+void DoTemplate(const char *templatename, long len, StrBuf *Target, void *Context, int ContextType
 {
        HashList *Static;
        HashList *StaticLocal;
@@ -905,14 +1368,26 @@ void DoTemplate(const char *templatename, long len, void *Context, StrBuf *Targe
                StaticLocal = LocalTemplateCache;
        }
 
+       if (len == 0)
+       {
+               lprintf (1, "Can't to load a template with empty name!\n");
+               StrBufAppendPrintf(Target, "<pre>\nCan't to load a template with empty name!\n</pre>");
+               return;
+       }
+
        if (!GetHash(StaticLocal, templatename, len, &vTmpl) &&
            !GetHash(Static, templatename, len, &vTmpl)) {
-               printf ("didn't find %s\n", templatename);
+               lprintf (1, "didn't find Template [%s] %ld %ld\n", templatename, len , (long)strlen(templatename));
+               StrBufAppendPrintf(Target, "<pre>\ndidn't find Template [%s] %ld %ld\n</pre>", 
+                                  templatename, len, 
+                                  (long)strlen(templatename));
+///            dbg_PrintHash(Static, PrintTemplate, NULL);
+//             PrintHash(Static, VarPrintTransition, PrintTemplate);
                return;
        }
        if (vTmpl == NULL) 
                return;
-       ProcessTemplate(vTmpl, Target, Context);        
+       ProcessTemplate(vTmpl, Target, Context, ContextType);
 }
 
 int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
@@ -930,6 +1405,7 @@ int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
        StrBufPrintf(Dir, "%s/t", DirName);
        filedir = opendir (ChrPtr(Dir));
        if (filedir == NULL) {
+               FreeStrBuf(&Dir);
                return 0;
        }
 
@@ -949,6 +1425,8 @@ int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
                        d_without_ext --;
                if ((d_without_ext == 0) || (d_namelen < 3))
                        continue;
+               if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
+                       continue; /* Ignore backup files... */
 
                IsMobile = (strstr(filedir_entry->d_name, ".m.html")!= NULL);
                PStart = filedir_entry->d_name;
@@ -958,8 +1436,8 @@ int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
                        *MinorPtr = '\0';
                StrBufPlain(Tag, filedir_entry->d_name, MinorPtr - filedir_entry->d_name);
 
-
-               printf("%s %d %s\n",ChrPtr(FileName), IsMobile, ChrPtr(Tag));
+               if (LoadTemplates > 1)
+                       lprintf(1, "%s %d %s\n",ChrPtr(FileName), IsMobile, ChrPtr(Tag));
                if (LoadTemplates == 0)
                        load_template(FileName, Tag, (IsMobile)?wireless:big);
                else
@@ -982,62 +1460,19 @@ void InitTemplateCache(void)
                        LocalTemplateCache);
 }
 
-void tmplput_serv_ip(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrBufAppendPrintf(Target, "%d", WC->ctdl_pid);
-}
-
-void tmplput_serv_nodename(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrEscAppend(Target, NULL, serv_info.serv_nodename, 0, 0);
-}
-
-void tmplput_serv_humannode(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrEscAppend(Target, NULL, serv_info.serv_humannode, 0, 0);
-}
-
-void tmplput_serv_fqdn(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrEscAppend(Target, NULL, serv_info.serv_fqdn, 0, 0);
-}
-
-void tmmplput_serv_software(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrEscAppend(Target, NULL, serv_info.serv_software, 0, 0);
-}
-
-void tmplput_serv_rev_level(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrBufAppendPrintf(Target, "%d.%02d",
-                           serv_info.serv_rev_level / 100,
-                           serv_info.serv_rev_level % 100);
-}
-
-void tmmplput_serv_bbs_city(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrEscAppend(Target, NULL, serv_info.serv_bbs_city, 0, 0);
-}
-
-void tmplput_current_user(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrEscAppend(Target, NULL, WC->wc_fullname, 0, 0);
-}
-
-void tmplput_current_room(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
-{
-       StrEscAppend(Target, NULL, WC->wc_roomname, 0, 0);
-}
 
 
 typedef struct _HashIterator {
        HashList *StaticList;
+       int AdditionalParams;
+       int ContextType;
+       int XPectContextType;
        RetrieveHashlistFunc GetHash;
        HashDestructorFunc Destructor;
        SubTemplFunc DoSubTemplate;
 } HashIterator;
 
-void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
+void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
 {
        void *vIt;
        HashIterator *It;
@@ -1052,22 +1487,91 @@ void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, vo
        if (!GetHash(Iterators, 
                     Tokens->Params[0]->Start,
                     Tokens->Params[0]->len,
-                    &vIt))
+                    &vIt)) {
+               lprintf(1, "unknown Iterator [%s] (in '%s' line %ld); "
+                       " [%s]\n", 
+                       Tokens->Params[0]->Start,
+                       ChrPtr(Tokens->FileName),
+                       Tokens->Line,
+                       ChrPtr(Tokens->FlatToken));
+               StrBufAppendPrintf(
+                       Target,
+                       "<pre>\nunknown Iterator [%s] (in '%s' line %ld); \n"
+                       " [%s]\n</pre>", 
+                       Tokens->Params[0]->Start,
+                       ChrPtr(Tokens->FileName),
+                       Tokens->Line,
+                       ChrPtr(Tokens->FlatToken));
                return;
+       }
+
        It = (HashIterator*) vIt;
+
+       if (Tokens->nParameters < It->AdditionalParams + 2) {
+               lprintf(1, "Iterator [%s] (in '%s' line %ld); "
+                       "doesn't work with %ld params [%s]\n", 
+                       Tokens->Params[0]->Start,
+                       ChrPtr(Tokens->FileName),
+                       Tokens->Line,
+                       Tokens->nParameters, 
+                       ChrPtr(Tokens->FlatToken));
+               StrBufAppendPrintf(
+                       Target,
+                       "<pre>Iterator [%s] \n(in '%s' line %ld);\n"
+                       "doesn't work with %ld params \n[%s]\n</pre>", 
+                       Tokens->Params[0]->Start,
+                       ChrPtr(Tokens->FileName),
+                       Tokens->Line,
+                       Tokens->nParameters, 
+                       ChrPtr(Tokens->FlatToken));
+               return;
+       }
+
+       if ((It->XPectContextType != CTX_NONE) &&
+           (It->XPectContextType != ContextType)) {
+               lprintf(1, "Iterator [%s] (in '%s' line %ld); "
+                       "requires context of type %ld, have %ld [%s]\n", 
+                       Tokens->pName,
+                       ChrPtr(Tokens->FileName),
+                       Tokens->Line,
+                       It->XPectContextType, 
+                       ContextType,
+                       ChrPtr(Tokens->FlatToken));
+               StrBufAppendPrintf(
+                       Target, 
+                       "<pre>\nIterator [%s] (in '%s' line %ld);"
+                       " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
+                       Tokens->pName,
+                       ChrPtr(Tokens->FileName),
+                       Tokens->Line,
+                       It->XPectContextType, 
+                       ContextType,
+                       ChrPtr(Tokens->FlatToken));
+               return ;
+               
+       }
+
+
+
+
        if (It->StaticList == NULL)
-               List = It->GetHash();
+               List = It->GetHash(Target, nArgs, Tokens, Context, ContextType);
        else
                List = It->StaticList;
 
        SubBuf = NewStrBuf();
        it = GetNewHashPos();
        while (GetNextHashPos(List, it, &len, &Key, &vContext)) {
-               svprintf(HKEY("ITERATE:ODDEVEN"), WCS_STRING, "%s", (oddeven)?"odd":"even");
-               It->DoSubTemplate(SubBuf, vContext);
+               svprintf(HKEY("ITERATE:ODDEVEN"), WCS_STRING, "%s", 
+                        (oddeven) ? "odd" : "even");
+               svprintf(HKEY("ITERATE:KEY"), WCS_STRING, "%s", Key);
+
+               if (It->DoSubTemplate != NULL)
+                       It->DoSubTemplate(SubBuf, vContext, Tokens);
                DoTemplate(Tokens->Params[1]->Start,
                           Tokens->Params[1]->len,
-                          vContext, SubBuf);
+                          SubBuf, vContext,
+                          It->ContextType);
                        
                StrBufAppendBuf(Target, SubBuf, 0);
                FlushStrBuf(SubBuf);
@@ -1075,10 +1579,11 @@ void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, vo
        }
        FreeStrBuf(&SubBuf);
        DeleteHashPos(&it);
-       It->Destructor(List);
+       if (It->Destructor != NULL)
+               It->Destructor(&List);
 }
 
-int ConditionalVar(WCTemplateToken *Tokens, void *Context)
+int ConditionalVar(WCTemplateToken *Tokens, void *Context, int ContextType)
 {
        void *vsubst;
        wcsubst *subst;
@@ -1089,6 +1594,12 @@ int ConditionalVar(WCTemplateToken *Tokens, void *Context)
                     &vsubst))
                return 0;
        subst = (wcsubst*) vsubst;
+       if ((subst->ContextRequired != CTX_NONE) &&
+           (subst->ContextRequired != ContextType)) {
+               lprintf(1,"  WARNING: Conditional requires Context: [%ld]!\n", Tokens->Params[2]->Start);
+               return -1;
+       }
+
        switch(subst->wcs_type) {
        case WCS_FUNCTION:
                return (subst->wcs_function!=NULL);
@@ -1107,78 +1618,126 @@ int ConditionalVar(WCTemplateToken *Tokens, void *Context)
                return (subst->lvalue == Tokens->Params[3]->lvalue);
        default:
                lprintf(1,"  WARNING: invalid type: [%ld]!\n", subst->wcs_type);
+               return -1;
        }
        return 0;
 }
 
 void RegisterITERATOR(const char *Name, long len, 
+                     int AdditionalParams, 
                      HashList *StaticList, 
                      RetrieveHashlistFunc GetHash, 
                      SubTemplFunc DoSubTempl,
-                     HashDestructorFunc Destructor)
+                     HashDestructorFunc Destructor,
+                     int ContextType, 
+                     int XPectContextType)
 {
        HashIterator *It = (HashIterator*)malloc(sizeof(HashIterator));
        It->StaticList = StaticList;
+       It->AdditionalParams = AdditionalParams;
        It->GetHash = GetHash;
        It->DoSubTemplate = DoSubTempl;
        It->Destructor = Destructor;
+       It->ContextType = ContextType;
+       It->XPectContextType = XPectContextType;
        Put(Iterators, Name, len, It, NULL);
 }
 
 void RegisterConditional(const char *Name, long len, 
                         int nParams,
-                        WCConditionalFunc CondF)
+                        WCConditionalFunc CondF, 
+                        int ContextRequired)
 {
        ConditionalStruct *Cond = (ConditionalStruct*)malloc(sizeof(ConditionalStruct));
+       Cond->PlainName = Name;
        Cond->nParams = nParams;
        Cond->CondF = CondF;
-       Put(Contitionals, Name, len, Cond, NULL);
+       Cond->ContextRequired = ContextRequired;
+       Put(Conditionals, Name, len, Cond, NULL);
+}
+
+
+void tmplput_ContextString(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
+{
+       StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType, (StrBuf*)Context, 0);
 }
+int ConditionalContextStr(WCTemplateToken *Tokens, void *Context, int ContextType)
+{
+       StrBuf *TokenText = (StrBuf*) Context;
+       const char *CompareToken;
+       long len;
 
-void tmpl_do_boxed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
+       GetTemplateTokenString(Tokens, 2, &CompareToken, &len);
+       return strcmp(ChrPtr(TokenText), CompareToken) == 0;
+}
+
+
+void tmpl_do_boxed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
 {
+       StrBuf *Headline;
        if (nArgs == 2) {
-               StrBuf *Headline = NewStrBuf();
-               DoTemplate(Tokens->Params[1]->Start, 
-                          Tokens->Params[1]->len,
-                          Context, 
-                          Headline);
-               SVPutBuf("BOXTITLE", Headline, 0);
+               if (Tokens->Params[1]->Type == TYPE_STR) {
+                       Headline = NewStrBuf();
+                       DoTemplate(Tokens->Params[1]->Start, 
+                                  Tokens->Params[1]->len,
+                                  Headline, 
+                                  Context, 
+                                  ContextType);
+               }
+               else {
+                       const char *Ch;
+                       long len;
+                       GetTemplateTokenString(Tokens, 
+                                              1,
+                                              &Ch,
+                                              &len);
+                       Headline = NewStrBufPlain(Ch, len);
+               }
        }
-
-       DoTemplate(HKEY("beginbox"), Context, Target);
+       
+       DoTemplate(HKEY("beginbox"), Target, Headline, CTX_STRBUF);
        DoTemplate(Tokens->Params[0]->Start, 
                   Tokens->Params[0]->len,
+                  Target, 
                   Context, 
-                  Target);
-       DoTemplate(HKEY("endbox"), Context, Target);
+                  ContextType);
+       DoTemplate(HKEY("endbox"), Target, Context, ContextType);
 }
 
-void tmpl_do_tabbed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
+
+void tmpl_do_tabbed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
 {
        StrBuf **TabNames;
-       int i, ntabs;
+       int i, ntabs, nTabs;
 
-       ntabs = Tokens->nParameters / 2;
+       nTabs = ntabs = Tokens->nParameters / 2;
        TabNames = (StrBuf **) malloc(ntabs * sizeof(StrBuf*));
 
        for (i = 0; i < ntabs; i++) {
                TabNames[i] = NewStrBuf();
-               DoTemplate(Tokens->Params[i * 2]->Start, 
-                          Tokens->Params[0]->len,
-                          Context,
-                          TabNames[i]);
+               if (Tokens->Params[i * 2]->len > 0) {
+                       DoTemplate(Tokens->Params[i * 2]->Start, 
+                                  Tokens->Params[i * 2]->len,
+                                  TabNames[i],
+                                  Context,
+                                  ContextType);
+               }
+               else { 
+                       /** A Tab without subject? we can't count that, add it as silent */
+                       nTabs --;
+               }
        }
 
-       StrTabbedDialog(Target, ntabs, TabNames);
+       StrTabbedDialog(Target, nTabs, TabNames);
        for (i = 0; i < ntabs; i++) {
-               StrBeginTab(Target, ntabs, i);
+               StrBeginTab(Target, i, nTabs);
 
                DoTemplate(Tokens->Params[i * 2 + 1]->Start, 
                           Tokens->Params[i * 2 + 1]->len,
+                          Target,
                           Context, 
-                          Target);
-               StrEndTab(Target, ntabs, i);
+                          ContextType);
+               StrEndTab(Target, i, nTabs);
        }
 }
 
@@ -1186,19 +1745,12 @@ void
 InitModule_SUBST
 (void)
 {
-       RegisterNamespace("SERV_PID", 0, 0, tmplput_serv_ip);
-       RegisterNamespace("SERV_NODENAME", 0, 0, tmplput_serv_nodename);
-       RegisterNamespace("SERV_HUMANNODE", 0, 0, tmplput_serv_humannode);
-       RegisterNamespace("SERV_FQDN", 0, 0, tmplput_serv_fqdn);
-       RegisterNamespace("SERV_SOFTWARE", 0, 0, tmmplput_serv_software);
-       RegisterNamespace("SERV_REV_LEVEL", 0, 0, tmplput_serv_rev_level);
-       RegisterNamespace("SERV_BBS_CITY", 0, 0, tmmplput_serv_bbs_city);
-       RegisterNamespace("CURRENT_USER", 0, 0, tmplput_current_user);
-       RegisterNamespace("CURRENT_ROOM", 0, 0, tmplput_current_room);
-       RegisterNamespace("ITERATE", 2, 4, tmpl_iterate_subtmpl);
-       RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed);
-       RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed);
-       RegisterConditional(HKEY("COND:SUBST"), 3, ConditionalVar);
+       RegisterNamespace("CONTEXTSTR", 0, 1, tmplput_ContextString, CTX_STRBUF);
+       RegisterNamespace("ITERATE", 2, 100, tmpl_iterate_subtmpl, CTX_NONE);
+       RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed, CTX_NONE);
+       RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed, CTX_NONE);
+       RegisterConditional(HKEY("COND:SUBST"), 3, ConditionalVar, CTX_NONE);
+       RegisterConditional(HKEY("COND:CONTEXTSTR"), 3, ConditionalContextStr, CTX_STRBUF);
 }
 
 /*@}*/