Code

some changes bcs of the name of uninstall.exe
[inkscape.git] / buildtool.cpp
index bcec40c93227b0cf31b1799ffb008e867c36d443..5975f86e195fa0289c0a07eb1782bb7d23b0d9d8 100644 (file)
@@ -4,7 +4,7 @@
  * Authors:
  *   Bob Jamison
  *
- * Copyright (C) 2006 Bob Jamison
+ * Copyright (C) 2006-2007 Bob Jamison
  *
  *  This library is free software; you can redistribute it and/or
  *  modify it under the terms of the GNU Lesser General Public
  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
-/*
-
-
-
-
-
-
-
-
-
+/**
+ * To use this file, compile with:
+ * <pre>
+ * g++ -O3 buildtool.cpp -o btool.exe
+ * (or whatever your compiler might be) 
+ * Then
+ * btool
+ * or 
+ * btool {target}
+ * 
+ * Note: if you are using MinGW, and a not very recent version of it,
+ * gettimeofday() might be missing.  If so, just build this file with
+ * this command:
+ * g++ -O3 -DNEED_GETTIMEOFDAY buildtool.cpp -o btool.exe
+ *     
+ */  
 
-*/
+#define BUILDTOOL_VERSION  "BuildTool v0.7.0, 2007 Bob Jamison"
 
 #include <stdio.h>
+#include <fcntl.h>
 #include <unistd.h>
 #include <stdarg.h>
 #include <sys/stat.h>
 #include <time.h>
 #include <sys/time.h>
+#include <utime.h>
 #include <dirent.h>
 
 #include <string>
 #endif
 
 
+#include <errno.h>
+
+
+//########################################################################
+//# Definition of gettimeofday() for those who don't have it
+//########################################################################
+#ifdef NEED_GETTIMEOFDAY
+#include <sys/timeb.h>
+
+struct timezone {
+      int tz_minuteswest; /* minutes west of Greenwich */
+      int tz_dsttime;     /* type of dst correction */
+    };
+
+static int gettimeofday (struct timeval *tv, struct timezone *tz)
+{
+   struct _timeb tb;
+
+   if (!tv)
+      return (-1);
+
+    _ftime (&tb);
+    tv->tv_sec  = tb.time;
+    tv->tv_usec = tb.millitm * 1000 + 500;
+    if (tz)
+        {
+        tz->tz_minuteswest = -60 * _timezone;
+        tz->tz_dsttime = _daylight;
+        }
+    return 0;
+}
+
+#endif
+
+
+
+
+
+
 
 namespace buildtool
 {
@@ -59,6 +106,749 @@ namespace buildtool
 
 
 
+//########################################################################
+//########################################################################
+//##  R E G E X P
+//########################################################################
+//########################################################################
+
+/**
+ * This is the T-Rex regular expression library, which we
+ * gratefully acknowledge.  It's clean code and small size allow
+ * us to embed it in BuildTool without adding a dependency
+ *
+ */    
+
+//begin trex.h
+
+#ifndef _TREX_H_
+#define _TREX_H_
+/***************************************************************
+    T-Rex a tiny regular expression library
+
+    Copyright (C) 2003-2006 Alberto Demichelis
+
+    This software is provided 'as-is', without any express 
+    or implied warranty. In no event will the authors be held 
+    liable for any damages arising from the use of this software.
+
+    Permission is granted to anyone to use this software for 
+    any purpose, including commercial applications, and to alter
+    it and redistribute it freely, subject to the following restrictions:
+
+        1. The origin of this software must not be misrepresented;
+        you must not claim that you wrote the original software.
+        If you use this software in a product, an acknowledgment
+        in the product documentation would be appreciated but
+        is not required.
+
+        2. Altered source versions must be plainly marked as such,
+        and must not be misrepresented as being the original software.
+
+        3. This notice may not be removed or altered from any
+        source distribution.
+
+****************************************************************/
+
+#ifdef _UNICODE
+#define TRexChar unsigned short
+#define MAX_CHAR 0xFFFF
+#define _TREXC(c) L##c 
+#define trex_strlen wcslen
+#define trex_printf wprintf
+#else
+#define TRexChar char
+#define MAX_CHAR 0xFF
+#define _TREXC(c) (c) 
+#define trex_strlen strlen
+#define trex_printf printf
+#endif
+
+#ifndef TREX_API
+#define TREX_API extern
+#endif
+
+#define TRex_True 1
+#define TRex_False 0
+
+typedef unsigned int TRexBool;
+typedef struct TRex TRex;
+
+typedef struct {
+    const TRexChar *begin;
+    int len;
+} TRexMatch;
+
+TREX_API TRex *trex_compile(const TRexChar *pattern,const TRexChar **error);
+TREX_API void trex_free(TRex *exp);
+TREX_API TRexBool trex_match(TRex* exp,const TRexChar* text);
+TREX_API TRexBool trex_search(TRex* exp,const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end);
+TREX_API TRexBool trex_searchrange(TRex* exp,const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end);
+TREX_API int trex_getsubexpcount(TRex* exp);
+TREX_API TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch *subexp);
+
+#endif
+
+//end trex.h
+
+//start trex.c
+
+
+#include <stdio.h>
+#include <string>
+
+/* see copyright notice in trex.h */
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <setjmp.h>
+//#include "trex.h"
+
+#ifdef _UINCODE
+#define scisprint iswprint
+#define scstrlen wcslen
+#define scprintf wprintf
+#define _SC(x) L(x)
+#else
+#define scisprint isprint
+#define scstrlen strlen
+#define scprintf printf
+#define _SC(x) (x)
+#endif
+
+#ifdef _DEBUG
+#include <stdio.h>
+
+static const TRexChar *g_nnames[] =
+{
+    _SC("NONE"),_SC("OP_GREEDY"),    _SC("OP_OR"),
+    _SC("OP_EXPR"),_SC("OP_NOCAPEXPR"),_SC("OP_DOT"),    _SC("OP_CLASS"),
+    _SC("OP_CCLASS"),_SC("OP_NCLASS"),_SC("OP_RANGE"),_SC("OP_CHAR"),
+    _SC("OP_EOL"),_SC("OP_BOL"),_SC("OP_WB")
+};
+
+#endif
+#define OP_GREEDY        (MAX_CHAR+1) // * + ? {n}
+#define OP_OR            (MAX_CHAR+2)
+#define OP_EXPR            (MAX_CHAR+3) //parentesis ()
+#define OP_NOCAPEXPR    (MAX_CHAR+4) //parentesis (?:)
+#define OP_DOT            (MAX_CHAR+5)
+#define OP_CLASS        (MAX_CHAR+6)
+#define OP_CCLASS        (MAX_CHAR+7)
+#define OP_NCLASS        (MAX_CHAR+8) //negates class the [^
+#define OP_RANGE        (MAX_CHAR+9)
+#define OP_CHAR            (MAX_CHAR+10)
+#define OP_EOL            (MAX_CHAR+11)
+#define OP_BOL            (MAX_CHAR+12)
+#define OP_WB            (MAX_CHAR+13)
+
+#define TREX_SYMBOL_ANY_CHAR ('.')
+#define TREX_SYMBOL_GREEDY_ONE_OR_MORE ('+')
+#define TREX_SYMBOL_GREEDY_ZERO_OR_MORE ('*')
+#define TREX_SYMBOL_GREEDY_ZERO_OR_ONE ('?')
+#define TREX_SYMBOL_BRANCH ('|')
+#define TREX_SYMBOL_END_OF_STRING ('$')
+#define TREX_SYMBOL_BEGINNING_OF_STRING ('^')
+#define TREX_SYMBOL_ESCAPE_CHAR ('\\')
+
+
+typedef int TRexNodeType;
+
+typedef struct tagTRexNode{
+    TRexNodeType type;
+    int left;
+    int right;
+    int next;
+}TRexNode;
+
+struct TRex{
+    const TRexChar *_eol;
+    const TRexChar *_bol;
+    const TRexChar *_p;
+    int _first;
+    int _op;
+    TRexNode *_nodes;
+    int _nallocated;
+    int _nsize;
+    int _nsubexpr;
+    TRexMatch *_matches;
+    int _currsubexp;
+    void *_jmpbuf;
+    const TRexChar **_error;
+};
+
+static int trex_list(TRex *exp);
+
+static int trex_newnode(TRex *exp, TRexNodeType type)
+{
+    TRexNode n;
+    int newid;
+    n.type = type;
+    n.next = n.right = n.left = -1;
+    if(type == OP_EXPR)
+        n.right = exp->_nsubexpr++;
+    if(exp->_nallocated < (exp->_nsize + 1)) {
+        //int oldsize = exp->_nallocated;
+        exp->_nallocated *= 2;
+        exp->_nodes = (TRexNode *)realloc(exp->_nodes, exp->_nallocated * sizeof(TRexNode));
+    }
+    exp->_nodes[exp->_nsize++] = n;
+    newid = exp->_nsize - 1;
+    return (int)newid;
+}
+
+static void trex_error(TRex *exp,const TRexChar *error)
+{
+    if(exp->_error) *exp->_error = error;
+    longjmp(*((jmp_buf*)exp->_jmpbuf),-1);
+}
+
+static void trex_expect(TRex *exp, int n){
+    if((*exp->_p) != n) 
+        trex_error(exp, _SC("expected paren"));
+    exp->_p++;
+}
+
+static TRexChar trex_escapechar(TRex *exp)
+{
+    if(*exp->_p == TREX_SYMBOL_ESCAPE_CHAR){
+        exp->_p++;
+        switch(*exp->_p) {
+        case 'v': exp->_p++; return '\v';
+        case 'n': exp->_p++; return '\n';
+        case 't': exp->_p++; return '\t';
+        case 'r': exp->_p++; return '\r';
+        case 'f': exp->_p++; return '\f';
+        default: return (*exp->_p++);
+        }
+    } else if(!scisprint(*exp->_p)) trex_error(exp,_SC("letter expected"));
+    return (*exp->_p++);
+}
+
+static int trex_charclass(TRex *exp,int classid)
+{
+    int n = trex_newnode(exp,OP_CCLASS);
+    exp->_nodes[n].left = classid;
+    return n;
+}
+
+static int trex_charnode(TRex *exp,TRexBool isclass)
+{
+    TRexChar t;
+    if(*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) {
+        exp->_p++;
+        switch(*exp->_p) {
+            case 'n': exp->_p++; return trex_newnode(exp,'\n');
+            case 't': exp->_p++; return trex_newnode(exp,'\t');
+            case 'r': exp->_p++; return trex_newnode(exp,'\r');
+            case 'f': exp->_p++; return trex_newnode(exp,'\f');
+            case 'v': exp->_p++; return trex_newnode(exp,'\v');
+            case 'a': case 'A': case 'w': case 'W': case 's': case 'S': 
+            case 'd': case 'D': case 'x': case 'X': case 'c': case 'C': 
+            case 'p': case 'P': case 'l': case 'u': 
+                {
+                t = *exp->_p; exp->_p++; 
+                return trex_charclass(exp,t);
+                }
+            case 'b': 
+            case 'B':
+                if(!isclass) {
+                    int node = trex_newnode(exp,OP_WB);
+                    exp->_nodes[node].left = *exp->_p;
+                    exp->_p++; 
+                    return node;
+                } //else default
+            default: 
+                t = *exp->_p; exp->_p++; 
+                return trex_newnode(exp,t);
+        }
+    }
+    else if(!scisprint(*exp->_p)) {
+        
+        trex_error(exp,_SC("letter expected"));
+    }
+    t = *exp->_p; exp->_p++; 
+    return trex_newnode(exp,t);
+}
+static int trex_class(TRex *exp)
+{
+    int ret = -1;
+    int first = -1,chain;
+    if(*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING){
+        ret = trex_newnode(exp,OP_NCLASS);
+        exp->_p++;
+    }else ret = trex_newnode(exp,OP_CLASS);
+    
+    if(*exp->_p == ']') trex_error(exp,_SC("empty class"));
+    chain = ret;
+    while(*exp->_p != ']' && exp->_p != exp->_eol) {
+        if(*exp->_p == '-' && first != -1){ 
+            int r,t;
+            if(*exp->_p++ == ']') trex_error(exp,_SC("unfinished range"));
+            r = trex_newnode(exp,OP_RANGE);
+            if(first>*exp->_p) trex_error(exp,_SC("invalid range"));
+            if(exp->_nodes[first].type == OP_CCLASS) trex_error(exp,_SC("cannot use character classes in ranges"));
+            exp->_nodes[r].left = exp->_nodes[first].type;
+            t = trex_escapechar(exp);
+            exp->_nodes[r].right = t;
+            exp->_nodes[chain].next = r;
+            chain = r;
+            first = -1;
+        }
+        else{
+            if(first!=-1){
+                int c = first;
+                exp->_nodes[chain].next = c;
+                chain = c;
+                first = trex_charnode(exp,TRex_True);
+            }
+            else{
+                first = trex_charnode(exp,TRex_True);
+            }
+        }
+    }
+    if(first!=-1){
+        int c = first;
+        exp->_nodes[chain].next = c;
+        chain = c;
+        first = -1;
+    }
+    /* hack? */
+    exp->_nodes[ret].left = exp->_nodes[ret].next;
+    exp->_nodes[ret].next = -1;
+    return ret;
+}
+
+static int trex_parsenumber(TRex *exp)
+{
+    int ret = *exp->_p-'0';
+    int positions = 10;
+    exp->_p++;
+    while(isdigit(*exp->_p)) {
+        ret = ret*10+(*exp->_p++-'0');
+        if(positions==1000000000) trex_error(exp,_SC("overflow in numeric constant"));
+        positions *= 10;
+    };
+    return ret;
+}
+
+static int trex_element(TRex *exp)
+{
+    int ret = -1;
+    switch(*exp->_p)
+    {
+    case '(': {
+        int expr,newn;
+        exp->_p++;
+
+
+        if(*exp->_p =='?') {
+            exp->_p++;
+            trex_expect(exp,':');
+            expr = trex_newnode(exp,OP_NOCAPEXPR);
+        }
+        else
+            expr = trex_newnode(exp,OP_EXPR);
+        newn = trex_list(exp);
+        exp->_nodes[expr].left = newn;
+        ret = expr;
+        trex_expect(exp,')');
+              }
+              break;
+    case '[':
+        exp->_p++;
+        ret = trex_class(exp);
+        trex_expect(exp,']');
+        break;
+    case TREX_SYMBOL_END_OF_STRING: exp->_p++; ret = trex_newnode(exp,OP_EOL);break;
+    case TREX_SYMBOL_ANY_CHAR: exp->_p++; ret = trex_newnode(exp,OP_DOT);break;
+    default:
+        ret = trex_charnode(exp,TRex_False);
+        break;
+    }
+
+    {
+        int op;
+        TRexBool isgreedy = TRex_False;
+        unsigned short p0 = 0, p1 = 0;
+        switch(*exp->_p){
+            case TREX_SYMBOL_GREEDY_ZERO_OR_MORE: p0 = 0; p1 = 0xFFFF; exp->_p++; isgreedy = TRex_True; break;
+            case TREX_SYMBOL_GREEDY_ONE_OR_MORE: p0 = 1; p1 = 0xFFFF; exp->_p++; isgreedy = TRex_True; break;
+            case TREX_SYMBOL_GREEDY_ZERO_OR_ONE: p0 = 0; p1 = 1; exp->_p++; isgreedy = TRex_True; break;
+            case '{':
+                exp->_p++;
+                if(!isdigit(*exp->_p)) trex_error(exp,_SC("number expected"));
+                p0 = (unsigned short)trex_parsenumber(exp);
+                /*******************************/
+                switch(*exp->_p) {
+            case '}':
+                p1 = p0; exp->_p++;
+                break;
+            case ',':
+                exp->_p++;
+                p1 = 0xFFFF;
+                if(isdigit(*exp->_p)){
+                    p1 = (unsigned short)trex_parsenumber(exp);
+                }
+                trex_expect(exp,'}');
+                break;
+            default:
+                trex_error(exp,_SC(", or } expected"));
+        }
+        /*******************************/
+        isgreedy = TRex_True; 
+        break;
+
+        }
+        if(isgreedy) {
+            int nnode = trex_newnode(exp,OP_GREEDY);
+            op = OP_GREEDY;
+            exp->_nodes[nnode].left = ret;
+            exp->_nodes[nnode].right = ((p0)<<16)|p1;
+            ret = nnode;
+        }
+    }
+    if((*exp->_p != TREX_SYMBOL_BRANCH) && (*exp->_p != ')') && (*exp->_p != TREX_SYMBOL_GREEDY_ZERO_OR_MORE) && (*exp->_p != TREX_SYMBOL_GREEDY_ONE_OR_MORE) && (*exp->_p != '\0')) {
+        int nnode = trex_element(exp);
+        exp->_nodes[ret].next = nnode;
+    }
+
+    return ret;
+}
+
+static int trex_list(TRex *exp)
+{
+    int ret=-1,e;
+    if(*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) {
+        exp->_p++;
+        ret = trex_newnode(exp,OP_BOL);
+    }
+    e = trex_element(exp);
+    if(ret != -1) {
+        exp->_nodes[ret].next = e;
+    }
+    else ret = e;
+
+    if(*exp->_p == TREX_SYMBOL_BRANCH) {
+        int temp,tright;
+        exp->_p++;
+        temp = trex_newnode(exp,OP_OR);
+        exp->_nodes[temp].left = ret;
+        tright = trex_list(exp);
+        exp->_nodes[temp].right = tright;
+        ret = temp;
+    }
+    return ret;
+}
+
+static TRexBool trex_matchcclass(int cclass,TRexChar c)
+{
+    switch(cclass) {
+    case 'a': return isalpha(c)?TRex_True:TRex_False;
+    case 'A': return !isalpha(c)?TRex_True:TRex_False;
+    case 'w': return (isalnum(c) || c == '_')?TRex_True:TRex_False;
+    case 'W': return (!isalnum(c) && c != '_')?TRex_True:TRex_False;
+    case 's': return isspace(c)?TRex_True:TRex_False;
+    case 'S': return !isspace(c)?TRex_True:TRex_False;
+    case 'd': return isdigit(c)?TRex_True:TRex_False;
+    case 'D': return !isdigit(c)?TRex_True:TRex_False;
+    case 'x': return isxdigit(c)?TRex_True:TRex_False;
+    case 'X': return !isxdigit(c)?TRex_True:TRex_False;
+    case 'c': return iscntrl(c)?TRex_True:TRex_False;
+    case 'C': return !iscntrl(c)?TRex_True:TRex_False;
+    case 'p': return ispunct(c)?TRex_True:TRex_False;
+    case 'P': return !ispunct(c)?TRex_True:TRex_False;
+    case 'l': return islower(c)?TRex_True:TRex_False;
+    case 'u': return isupper(c)?TRex_True:TRex_False;
+    }
+    return TRex_False; /*cannot happen*/
+}
+
+static TRexBool trex_matchclass(TRex* exp,TRexNode *node,TRexChar c)
+{
+    do {
+        switch(node->type) {
+            case OP_RANGE:
+                if(c >= node->left && c <= node->right) return TRex_True;
+                break;
+            case OP_CCLASS:
+                if(trex_matchcclass(node->left,c)) return TRex_True;
+                break;
+            default:
+                if(c == node->type)return TRex_True;
+        }
+    } while((node->next != -1) && (node = &exp->_nodes[node->next]));
+    return TRex_False;
+}
+
+static const TRexChar *trex_matchnode(TRex* exp,TRexNode *node,const TRexChar *str,TRexNode *next)
+{
+    
+    TRexNodeType type = node->type;
+    switch(type) {
+    case OP_GREEDY: {
+        //TRexNode *greedystop = (node->next != -1) ? &exp->_nodes[node->next] : NULL;
+        TRexNode *greedystop = NULL;
+        int p0 = (node->right >> 16)&0x0000FFFF, p1 = node->right&0x0000FFFF, nmaches = 0;
+        const TRexChar *s=str, *good = str;
+
+        if(node->next != -1) {
+            greedystop = &exp->_nodes[node->next];
+        }
+        else {
+            greedystop = next;
+        }
+
+        while((nmaches == 0xFFFF || nmaches < p1)) {
+
+            const TRexChar *stop;
+            if(!(s = trex_matchnode(exp,&exp->_nodes[node->left],s,greedystop)))
+                break;
+            nmaches++;
+            good=s;
+            if(greedystop) {
+                //checks that 0 matches satisfy the expression(if so skips)
+                //if not would always stop(for instance if is a '?')
+                if(greedystop->type != OP_GREEDY ||
+                (greedystop->type == OP_GREEDY && ((greedystop->right >> 16)&0x0000FFFF) != 0))
+                {
+                    TRexNode *gnext = NULL;
+                    if(greedystop->next != -1) {
+                        gnext = &exp->_nodes[greedystop->next];
+                    }else if(next && next->next != -1){
+                        gnext = &exp->_nodes[next->next];
+                    }
+                    stop = trex_matchnode(exp,greedystop,s,gnext);
+                    if(stop) {
+                        //if satisfied stop it
+                        if(p0 == p1 && p0 == nmaches) break;
+                        else if(nmaches >= p0 && p1 == 0xFFFF) break;
+                        else if(nmaches >= p0 && nmaches <= p1) break;
+                    }
+                }
+            }
+            
+            if(s >= exp->_eol)
+                break;
+        }
+        if(p0 == p1 && p0 == nmaches) return good;
+        else if(nmaches >= p0 && p1 == 0xFFFF) return good;
+        else if(nmaches >= p0 && nmaches <= p1) return good;
+        return NULL;
+    }
+    case OP_OR: {
+            const TRexChar *asd = str;
+            TRexNode *temp=&exp->_nodes[node->left];
+            while( (asd = trex_matchnode(exp,temp,asd,NULL)) ) {
+                if(temp->next != -1)
+                    temp = &exp->_nodes[temp->next];
+                else
+                    return asd;
+            }
+            asd = str;
+            temp = &exp->_nodes[node->right];
+            while( (asd = trex_matchnode(exp,temp,asd,NULL)) ) {
+                if(temp->next != -1)
+                    temp = &exp->_nodes[temp->next];
+                else
+                    return asd;
+            }
+            return NULL;
+            break;
+    }
+    case OP_EXPR:
+    case OP_NOCAPEXPR:{
+            TRexNode *n = &exp->_nodes[node->left];
+            const TRexChar *cur = str;
+            int capture = -1;
+            if(node->type != OP_NOCAPEXPR && node->right == exp->_currsubexp) {
+                capture = exp->_currsubexp;
+                exp->_matches[capture].begin = cur;
+                exp->_currsubexp++;
+            }
+            
+            do {
+                TRexNode *subnext = NULL;
+                if(n->next != -1) {
+                    subnext = &exp->_nodes[n->next];
+                }else {
+                    subnext = next;
+                }
+                if(!(cur = trex_matchnode(exp,n,cur,subnext))) {
+                    if(capture != -1){
+                        exp->_matches[capture].begin = 0;
+                        exp->_matches[capture].len = 0;
+                    }
+                    return NULL;
+                }
+            } while((n->next != -1) && (n = &exp->_nodes[n->next]));
+
+            if(capture != -1) 
+                exp->_matches[capture].len = cur - exp->_matches[capture].begin;
+            return cur;
+    }                 
+    case OP_WB:
+        if(str == exp->_bol && !isspace(*str)
+         || (str == exp->_eol && !isspace(*(str-1)))
+         || (!isspace(*str) && isspace(*(str+1)))
+         || (isspace(*str) && !isspace(*(str+1))) ) {
+            return (node->left == 'b')?str:NULL;
+        }
+        return (node->left == 'b')?NULL:str;
+    case OP_BOL:
+        if(str == exp->_bol) return str;
+        return NULL;
+    case OP_EOL:
+        if(str == exp->_eol) return str;
+        return NULL;
+    case OP_DOT:{
+        *str++;
+                }
+        return str;
+    case OP_NCLASS:
+    case OP_CLASS:
+        if(trex_matchclass(exp,&exp->_nodes[node->left],*str)?(type == OP_CLASS?TRex_True:TRex_False):(type == OP_NCLASS?TRex_True:TRex_False)) {
+            *str++;
+            return str;
+        }
+        return NULL;
+    case OP_CCLASS:
+        if(trex_matchcclass(node->left,*str)) {
+            *str++;
+            return str;
+        }
+        return NULL;
+    default: /* char */
+        if(*str != node->type) return NULL;
+        *str++;
+        return str;
+    }
+    return NULL;
+}
+
+/* public api */
+TRex *trex_compile(const TRexChar *pattern,const TRexChar **error)
+{
+    TRex *exp = (TRex *)malloc(sizeof(TRex));
+    exp->_eol = exp->_bol = NULL;
+    exp->_p = pattern;
+    exp->_nallocated = (int)scstrlen(pattern) * sizeof(TRexChar);
+    exp->_nodes = (TRexNode *)malloc(exp->_nallocated * sizeof(TRexNode));
+    exp->_nsize = 0;
+    exp->_matches = 0;
+    exp->_nsubexpr = 0;
+    exp->_first = trex_newnode(exp,OP_EXPR);
+    exp->_error = error;
+    exp->_jmpbuf = malloc(sizeof(jmp_buf));
+    if(setjmp(*((jmp_buf*)exp->_jmpbuf)) == 0) {
+        int res = trex_list(exp);
+        exp->_nodes[exp->_first].left = res;
+        if(*exp->_p!='\0')
+            trex_error(exp,_SC("unexpected character"));
+#ifdef _DEBUG
+        {
+            int nsize,i;
+            TRexNode *t;
+            nsize = exp->_nsize;
+            t = &exp->_nodes[0];
+            scprintf(_SC("\n"));
+            for(i = 0;i < nsize; i++) {
+                if(exp->_nodes[i].type>MAX_CHAR)
+                    scprintf(_SC("[%02d] %10s "),i,g_nnames[exp->_nodes[i].type-MAX_CHAR]);
+                else
+                    scprintf(_SC("[%02d] %10c "),i,exp->_nodes[i].type);
+                scprintf(_SC("left %02d right %02d next %02d\n"),exp->_nodes[i].left,exp->_nodes[i].right,exp->_nodes[i].next);
+            }
+            scprintf(_SC("\n"));
+        }
+#endif
+        exp->_matches = (TRexMatch *) malloc(exp->_nsubexpr * sizeof(TRexMatch));
+        memset(exp->_matches,0,exp->_nsubexpr * sizeof(TRexMatch));
+    }
+    else{
+        trex_free(exp);
+        return NULL;
+    }
+    return exp;
+}
+
+void trex_free(TRex *exp)
+{
+    if(exp)    {
+        if(exp->_nodes) free(exp->_nodes);
+        if(exp->_jmpbuf) free(exp->_jmpbuf);
+        if(exp->_matches) free(exp->_matches);
+        free(exp);
+    }
+}
+
+TRexBool trex_match(TRex* exp,const TRexChar* text)
+{
+    const TRexChar* res = NULL;
+    exp->_bol = text;
+    exp->_eol = text + scstrlen(text);
+    exp->_currsubexp = 0;
+    res = trex_matchnode(exp,exp->_nodes,text,NULL);
+    if(res == NULL || res != exp->_eol)
+        return TRex_False;
+    return TRex_True;
+}
+
+TRexBool trex_searchrange(TRex* exp,const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end)
+{
+    const TRexChar *cur = NULL;
+    int node = exp->_first;
+    if(text_begin >= text_end) return TRex_False;
+    exp->_bol = text_begin;
+    exp->_eol = text_end;
+    do {
+        cur = text_begin;
+        while(node != -1) {
+            exp->_currsubexp = 0;
+            cur = trex_matchnode(exp,&exp->_nodes[node],cur,NULL);
+            if(!cur)
+                break;
+            node = exp->_nodes[node].next;
+        }
+        *text_begin++;
+    } while(cur == NULL && text_begin != text_end);
+
+    if(cur == NULL)
+        return TRex_False;
+
+    --text_begin;
+
+    if(out_begin) *out_begin = text_begin;
+    if(out_end) *out_end = cur;
+    return TRex_True;
+}
+
+TRexBool trex_search(TRex* exp,const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end)
+{
+    return trex_searchrange(exp,text,text + scstrlen(text),out_begin,out_end);
+}
+
+int trex_getsubexpcount(TRex* exp)
+{
+    return exp->_nsubexpr;
+}
+
+TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch *subexp)
+{
+    if( n<0 || n >= exp->_nsubexpr) return TRex_False;
+    *subexp = exp->_matches[n];
+    return TRex_True;
+}
+
+
+//########################################################################
+//########################################################################
+//##  E N D    R E G E X P
+//########################################################################
+//########################################################################
+
+
+
 
 
 //########################################################################
@@ -172,18 +962,18 @@ friend class Parser;
 public:
     Element()
         {
-        parent = NULL;
+        init();
         }
 
     Element(const String &nameArg)
         {
-        parent = NULL;
+        init();
         name   = nameArg;
         }
 
     Element(const String &nameArg, const String &valueArg)
         {
-        parent = NULL;
+        init();
         name   = nameArg;
         value  = valueArg;
         }
@@ -251,9 +1041,18 @@ public:
      * @param elem the element to output
      */
     void print();
+    
+    int getLine()
+        { return line; }
 
 protected:
 
+    void init()
+        {
+        parent = NULL;
+        line   = 0;
+        }
+
     void assign(const Element &other)
         {
         parent     = other.parent;
@@ -262,6 +1061,7 @@ protected:
         namespaces = other.namespaces;
         name       = other.name;
         value      = other.value;
+        line       = other.line;
         }
 
     void findElementsRecursive(std::vector<Element *>&res, const String &name);
@@ -277,7 +1077,8 @@ protected:
 
     String name;
     String value;
-
+    
+    int line;
 };
 
 
@@ -345,15 +1146,17 @@ private:
         currentPosition = 0;
         }
 
-    void getLineAndColumn(long pos, long *lineNr, long *colNr);
+    int countLines(int begin, int end);
+
+    void getLineAndColumn(int pos, int *lineNr, int *colNr);
 
-    void error(char *fmt, ...);
+    void error(const char *fmt, ...);
 
-    int peek(long pos);
+    int peek(int pos);
 
-    int match(long pos, const char *text);
+    int match(int pos, const char *text);
 
-    int skipwhite(long p);
+    int skipwhite(int p);
 
     int getWord(int p0, String &buf);
 
@@ -369,12 +1172,10 @@ private:
 
     bool       keepGoing;
     Element    *currentNode;
-    long       parselen;
+    int        parselen;
     XMLCh      *parsebuf;
-    String  cdatabuf;
-    long       currentPosition;
-    int        colNr;
-
+    String     cdatabuf;
+    int        currentPosition;
 };
 
 
@@ -390,6 +1191,7 @@ Element *Element::clone()
     elem->parent     = parent;
     elem->attributes = attributes;
     elem->namespaces = namespaces;
+    elem->line       = line;
 
     std::vector<Element *>::iterator iter;
     for (iter = children.begin(); iter != children.end() ; iter++)
@@ -523,7 +1325,7 @@ void Element::print()
 
 typedef struct
     {
-    char *escaped;
+    const char *escaped;
     char value;
     } EntityEntry;
 
@@ -568,10 +1370,24 @@ String Parser::trim(const String &s)
     return res;
 }
 
-void Parser::getLineAndColumn(long pos, long *lineNr, long *colNr)
+
+int Parser::countLines(int begin, int end)
+{
+    int count = 0;
+    for (int i=begin ; i<end ; i++)
+        {
+        XMLCh ch = parsebuf[i];
+        if (ch == '\n' || ch == '\r')
+            count++;
+        }
+    return count;
+}
+
+
+void Parser::getLineAndColumn(int pos, int *lineNr, int *colNr)
 {
-    long line = 1;
-    long col  = 1;
+    int line = 1;
+    int col  = 1;
     for (long i=0 ; i<pos ; i++)
         {
         XMLCh ch = parsebuf[i];
@@ -589,13 +1405,13 @@ void Parser::getLineAndColumn(long pos, long *lineNr, long *colNr)
 }
 
 
-void Parser::error(char *fmt, ...)
+void Parser::error(const char *fmt, ...)
 {
-    long lineNr;
-    long colNr;
+    int lineNr;
+    int colNr;
     getLineAndColumn(currentPosition, &lineNr, &colNr);
     va_list args;
-    fprintf(stderr, "xml error at line %ld, column %ld:", lineNr, colNr);
+    fprintf(stderr, "xml error at line %d, column %d:", lineNr, colNr);
     va_start(args,fmt);
     vfprintf(stderr,fmt,args);
     va_end(args) ;
@@ -604,7 +1420,7 @@ void Parser::error(char *fmt, ...)
 
 
 
-int Parser::peek(long pos)
+int Parser::peek(int pos)
 {
     if (pos >= parselen)
         return -1;
@@ -640,7 +1456,7 @@ String Parser::encode(const String &str)
 }
 
 
-int Parser::match(long p0, const char *text)
+int Parser::match(int p0, const char *text)
 {
     int p = p0;
     while (*text)
@@ -654,7 +1470,7 @@ int Parser::match(long p0, const char *text)
 
 
 
-int Parser::skipwhite(long p)
+int Parser::skipwhite(int p)
 {
 
     while (p<parselen)
@@ -811,7 +1627,9 @@ int Parser::parseDoctype(int p0)
     return p;
 }
 
-int Parser::parseElement(int p0, Element *par,int depth)
+
+
+int Parser::parseElement(int p0, Element *par,int lineNr)
 {
 
     int p = p0;
@@ -825,6 +1643,9 @@ int Parser::parseElement(int p0, Element *par,int depth)
     if (ch!='<')
         return p0;
 
+    //int line, col;
+    //getLineAndColumn(p, &line, &col);
+
     p++;
 
     String openTagName;
@@ -835,6 +1656,7 @@ int Parser::parseElement(int p0, Element *par,int depth)
 
     //Add element to tree
     Element *n = new Element(openTagName);
+    n->line = lineNr + countLines(p0, p);
     n->parent = par;
     par->addChild(n);
 
@@ -929,7 +1751,7 @@ int Parser::parseElement(int p0, Element *par,int depth)
         //# CHILD ELEMENT
         if (ch == '<')
             {
-            p2 = parseElement(p, n, depth+1);
+            p2 = parseElement(p, n, lineNr + countLines(p0, p));
             if (p2 == p)
                 {
                 /*
@@ -1021,7 +1843,7 @@ Element *Parser::parse(XMLCh *buf,int pos,int len)
     Element *rootNode = new Element("root");
     pos = parseVersion(pos);
     pos = parseDoctype(pos);
-    pos = parseElement(pos, rootNode, 0);
+    pos = parseElement(pos, rootNode, 1);
     return rootNode;
 }
 
@@ -1088,8 +1910,6 @@ Element *Parser::parseFile(const String &fileName)
     return n;
 }
 
-
-
 //########################################################################
 //########################################################################
 //##  E N D    X M L
@@ -1097,6 +1917,10 @@ Element *Parser::parseFile(const String &fileName)
 //########################################################################
 
 
+
+
+
+
 //########################################################################
 //########################################################################
 //##  U R I
@@ -1325,7 +2149,7 @@ private:
 
     int peek(int p);
 
-    int match(int p, char *key);
+    int match(int p, const char *key);
 
     int parseScheme(int p);
 
@@ -1347,9 +2171,9 @@ private:
 
 typedef struct
 {
-    int  ival;
-    char *sval;
-    int  port;
+    int         ival;
+    const char *sval;
+    int         port;
 } LookupEntry;
 
 LookupEntry schemes[] =
@@ -1542,6 +2366,7 @@ URI URI::resolve(const URI &other) const
 }
 
 
+
 /**
  *  This follows the Java URI algorithm:
  *   1. All "." segments are removed.
@@ -1660,6 +2485,7 @@ void URI::trace(const char *fmt, ...)
 
 
 
+
 //#########################################################################
 //# P A R S I N G
 //#########################################################################
@@ -1675,7 +2501,7 @@ int URI::peek(int p)
 
 
 
-int URI::match(int p0, char *key)
+int URI::match(int p0, const char *key)
 {
     int p = p0;
     while (p < parselen)
@@ -1868,7 +2694,8 @@ int URI::parse(int p0)
 
 bool URI::parse(const String &str)
 {
-
+    init();
+    
     parselen = str.size();
 
     String tmp;
@@ -1912,8 +2739,131 @@ bool URI::parse(const String &str)
 //########################################################################
 //########################################################################
 
+//########################################################################
+//# F I L E S E T
+//########################################################################
+/**
+ * This is the descriptor for a <fileset> item
+ */
+class FileSet
+{
+public:
+
+    /**
+     *
+     */
+    FileSet()
+        {}
+
+    /**
+     *
+     */
+    FileSet(const FileSet &other)
+        { assign(other); }
+
+    /**
+     *
+     */
+    FileSet &operator=(const FileSet &other)
+        { assign(other); return *this; }
+
+    /**
+     *
+     */
+    virtual ~FileSet()
+        {}
+
+    /**
+     *
+     */
+    String getDirectory()
+        { return directory; }
+        
+    /**
+     *
+     */
+    void setDirectory(const String &val)
+        { directory = val; }
+
+    /**
+     *
+     */
+    void setFiles(const std::vector<String> &val)
+        { files = val; }
+
+    /**
+     *
+     */
+    std::vector<String> getFiles()
+        { return files; }
+        
+    /**
+     *
+     */
+    void setIncludes(const std::vector<String> &val)
+        { includes = val; }
+
+    /**
+     *
+     */
+    std::vector<String> getIncludes()
+        { return includes; }
+        
+    /**
+     *
+     */
+    void setExcludes(const std::vector<String> &val)
+        { excludes = val; }
+
+    /**
+     *
+     */
+    std::vector<String> getExcludes()
+        { return excludes; }
+        
+    /**
+     *
+     */
+    unsigned int size()
+        { return files.size(); }
+        
+    /**
+     *
+     */
+    String operator[](int index)
+        { return files[index]; }
+        
+    /**
+     *
+     */
+    void clear()
+        {
+        directory = "";
+        files.clear();
+        includes.clear();
+        excludes.clear();
+        }
+        
+
+private:
+
+    void assign(const FileSet &other)
+        {
+        directory = other.directory;
+        files     = other.files;
+        includes  = other.includes;
+        excludes  = other.excludes;
+        }
+
+    String directory;
+    std::vector<String> files;
+    std::vector<String> includes;
+    std::vector<String> excludes;
+};
+
+
+
 
-
 //########################################################################
 //# M A K E    B A S E
 //########################################################################
@@ -1923,13 +2873,14 @@ bool URI::parse(const String &str)
 class MakeBase
 {
 public:
+
     MakeBase()
-        {}
+        { line = 0; }
     virtual ~MakeBase()
         {}
 
     /**
-     *         Return the URI of the file associated with this object 
+     *     Return the URI of the file associated with this object 
      */     
     URI getURI()
         { return uri; }
@@ -1954,11 +2905,56 @@ public:
      * Get an element value, performing substitutions if necessary
      */
     bool getValue(Element *elem, String &result);
+    
+    /**
+     * Set the current line number in the file
+     */         
+    void setLine(int val)
+        { line = val; }
+        
+    /**
+     * Get the current line number in the file
+     */         
+    int getLine()
+        { return line; }
+
+
+    /**
+     * Set a property to a given value
+     */
+    virtual void setProperty(const String &name, const String &val)
+        {
+        properties[name] = val;
+        }
+
+    /**
+     * Return a named property is found, else a null string
+     */
+    virtual String getProperty(const String &name)
+        {
+        String val;
+        std::map<String, String>::iterator iter = properties.find(name);
+        if (iter != properties.end())
+            val = iter->second;
+        return val;
+        }
+
+    /**
+     * Return true if a named property is found, else false
+     */
+    virtual bool hasProperty(const String &name)
+        {
+        std::map<String, String>::iterator iter = properties.find(name);
+        if (iter == properties.end())
+            return false;
+        return true;
+        }
+
 
 protected:
 
     /**
-     * The path to the file associated with this object
+     *    The path to the file associated with this object
      */     
     URI uri;
 
@@ -1966,17 +2962,22 @@ protected:
     /**
      *  Print a printf()-like formatted error message
      */
-    void error(char *fmt, ...);
+    void error(const char *fmt, ...);
 
     /**
      *  Print a printf()-like formatted trace message
      */
-    void status(char *fmt, ...);
+    void status(const char *fmt, ...);
 
     /**
      *  Print a printf()-like formatted trace message
      */
-    void trace(char *fmt, ...);
+    void trace(const char *fmt, ...);
+
+    /**
+     *  Check if a given string matches a given regex pattern
+     */
+    bool regexMatch(const String &str, const String &pattern);
 
     /**
      *
@@ -1988,13 +2989,28 @@ protected:
      * in delimiters.  Null-length substrings are ignored
      */  
     std::vector<String> tokenize(const String &val,
-                             const String &delimiters);
+                          const String &delimiters);
+
+    /**
+     *  replace runs of whitespace with a space
+     */
+    String strip(const String &s);
+
+    /**
+     *  remove leading whitespace from each line
+     */
+    String leftJustify(const String &s);
 
     /**
      *  remove leading and trailing whitespace from string
      */
     String trim(const String &s);
 
+    /**
+     *  Return a lower case version of the given string
+     */
+    String toLower(const String &s);
+
     /**
      * Return the native format of the canonical
      * path which we store
@@ -2004,45 +3020,47 @@ protected:
     /**
      * Execute a shell command.  Outbuf is a ref to a string
      * to catch the result.     
-     */             
+     */         
     bool executeCommand(const String &call,
-                           const String &inbuf,
-                                               String &outbuf,
-                                               String &errbuf);
+                        const String &inbuf,
+                        String &outbuf,
+                        String &errbuf);
     /**
      * List all directories in a given base and starting directory
      * It is usually called like:
-     *          bool ret = listDirectories("src", "", result);    
-     */             
+     *        bool ret = listDirectories("src", "", result);    
+     */         
     bool listDirectories(const String &baseName,
                          const String &dirname,
                          std::vector<String> &res);
 
     /**
-     * Find all files in the named directory whose short names (no path) match
-     * the given regex pattern     
-     */             
+     * Find all files in the named directory 
+     */         
     bool listFiles(const String &baseName,
                    const String &dirname,
-                   std::vector<String> &excludes,
-                   std::vector<String> &res);
+                   std::vector<String> &result);
+
+    /**
+     * Perform a listing for a fileset 
+     */         
+    bool listFiles(MakeBase &propRef, FileSet &fileSet);
 
     /**
      * Parse a <patternset>
      */  
-    bool getPatternSet(Element *elem,
+    bool parsePatternSet(Element *elem,
                        MakeBase &propRef,
-                                          std::vector<String> &includes,
-                                          std::vector<String> &excludes);
+                       std::vector<String> &includes,
+                       std::vector<String> &excludes);
 
     /**
      * Parse a <fileset> entry, and determine which files
      * should be included
      */  
-    bool getFileSet(Element *elem,
+    bool parseFileSet(Element *elem,
                     MakeBase &propRef,
-                    String &dir,
-                                       std::vector<String> &result);
+                    FileSet &fileSet);
 
     /**
      * Return this object's property list
@@ -2050,31 +3068,18 @@ protected:
     virtual std::map<String, String> &getProperties()
         { return properties; }
 
-    /**
-     * Return a named property if found, else a null string
-     */
-    virtual String getProperty(const String &name)
-        {
-        String val;
-        std::map<String, String>::iterator iter;
-        iter = properties.find(name);
-        if (iter != properties.end())
-            val = iter->second;
-        return val;
-        }
-
 
     std::map<String, String> properties;
 
     /**
      * Turn 'true' and 'false' into boolean values
-     */                    
+     */             
     bool getBool(const String &str, bool &val);
 
     /**
      * Create a directory, making intermediate dirs
      * if necessary
-     */                            
+     */                  
     bool createDirectory(const String &dirname);
 
     /**
@@ -2087,6 +3092,16 @@ protected:
      */ 
     bool copyFile(const String &srcFile, const String &destFile);
 
+    /**
+     * Tests if the file exists and is a regular file
+     */ 
+    bool isRegularFile(const String &fileName);
+
+    /**
+     * Tests if the file exists and is a directory
+     */ 
+    bool isDirectory(const String &fileName);
+
     /**
      * Tests is the modification date of fileA is newer than fileB
      */ 
@@ -2096,9 +3111,10 @@ private:
 
     /**
      * replace variable refs like ${a} with their values
-     */             
+     */         
     bool getSubstitutions(const String &s, String &result);
 
+    int line;
 
 
 };
@@ -2109,11 +3125,11 @@ private:
 /**
  *  Print a printf()-like formatted error message
  */
-void MakeBase::error(char *fmt, ...)
+void MakeBase::error(const char *fmt, ...)
 {
     va_list args;
     va_start(args,fmt);
-    fprintf(stderr, "Make error: ");
+    fprintf(stderr, "Make error line %d: ", line);
     vfprintf(stderr, fmt, args);
     fprintf(stderr, "\n");
     va_end(args) ;
@@ -2124,7 +3140,7 @@ void MakeBase::error(char *fmt, ...)
 /**
  *  Print a printf()-like formatted trace message
  */
-void MakeBase::status(char *fmt, ...)
+void MakeBase::status(const char *fmt, ...)
 {
     va_list args;
     va_start(args,fmt);
@@ -2151,7 +3167,7 @@ String MakeBase::resolve(const String &otherPath)
 /**
  *  Print a printf()-like formatted trace message
  */
-void MakeBase::trace(char *fmt, ...)
+void MakeBase::trace(const char *fmt, ...)
 {
     va_list args;
     va_start(args,fmt);
@@ -2162,6 +3178,40 @@ void MakeBase::trace(char *fmt, ...)
 }
 
 
+
+/**
+ *  Check if a given string matches a given regex pattern
+ */
+bool MakeBase::regexMatch(const String &str, const String &pattern)
+{
+    const TRexChar *terror = NULL;
+    const TRexChar *cpat = pattern.c_str();
+    TRex *expr = trex_compile(cpat, &terror);
+    if (!expr)
+        {
+        if (!terror)
+            terror = "undefined";
+        error("compilation error [%s]!\n", terror);
+        return false;
+        } 
+
+    bool ret = true;
+
+    const TRexChar *cstr = str.c_str();
+    if (trex_match(expr, cstr))
+        {
+        ret = true;
+        }
+    else
+        {
+        ret = false;
+        }
+
+    trex_free(expr);
+
+    return ret;
+}
+
 /**
  *  Return the suffix, if any, of a file name
  */
@@ -2223,6 +3273,78 @@ std::vector<String> MakeBase::tokenize(const String &str,
 
 
 
+/**
+ *  replace runs of whitespace with a single space
+ */
+String MakeBase::strip(const String &s)
+{
+    int len = s.size();
+    String stripped;
+    for (int i = 0 ; i<len ; i++)
+        {
+        char ch = s[i];
+        if (isspace(ch))
+            {
+            stripped.push_back(' ');
+            for ( ; i<len ; i++)
+                {
+                ch = s[i];
+                if (!isspace(ch))
+                    {
+                    stripped.push_back(ch);
+                    break;
+                    }
+                }
+            }
+        else
+            {
+            stripped.push_back(ch);
+            }
+        }
+    return stripped;
+}
+
+/**
+ *  remove leading whitespace from each line
+ */
+String MakeBase::leftJustify(const String &s)
+{
+    String out;
+    int len = s.size();
+    for (int i = 0 ; i<len ; )
+        {
+        char ch;
+        //Skip to first visible character
+        while (i<len)
+            {
+            ch = s[i];
+            if (ch == '\n' || ch == '\r'
+              || !isspace(ch))
+                  break;
+            i++;
+            }
+        //Copy the rest of the line
+        while (i<len)
+            {
+            ch = s[i];
+            if (ch == '\n' || ch == '\r')
+                {
+                if (ch != '\r')
+                    out.push_back('\n');
+                i++;
+                break;
+                }
+            else
+                {
+                out.push_back(ch);
+                }
+            i++;
+            }
+        }
+    return out;
+}
+
+
 /**
  *  Removes whitespace from beginning and end of a string
  */
@@ -2252,6 +3374,24 @@ String MakeBase::trim(const String &s)
     return res;
 }
 
+
+/**
+ *  Return a lower case version of the given string
+ */
+String MakeBase::toLower(const String &s)
+{
+    if (s.size()==0)
+        return s;
+
+    String ret;
+    for(unsigned int i=0; i<s.size() ; i++)
+        {
+        ret.push_back(tolower(s[i]));
+        }
+    return ret;
+}
+
+
 /**
  * Return the native format of the canonical
  * path which we store
@@ -2320,13 +3460,16 @@ static String win32LastError()
  */
 bool MakeBase::executeCommand(const String &command,
                               const String &inbuf,
-                                                         String &outbuf,
-                                                         String &errbuf)
+                              String &outbuf,
+                              String &errbuf)
 {
 
     status("============ cmd ============\n%s\n=============================",
-                   command.c_str());
+                command.c_str());
 
+    outbuf.clear();
+    errbuf.clear();
+    
 #ifdef __WIN32__
 
     /*
@@ -2342,10 +3485,13 @@ bool MakeBase::executeCommand(const String &command,
     if (!paramBuf)
        {
        error("executeCommand cannot allocate command buffer");
-          return false;
+       return false;
        }
     strcpy(paramBuf, (char *)command.c_str());
 
+    //# Go to http://msdn2.microsoft.com/en-us/library/ms682499.aspx
+    //# to see how Win32 pipes work
+
     //# Create pipes
     SECURITY_ATTRIBUTES saAttr; 
     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
@@ -2355,25 +3501,25 @@ bool MakeBase::executeCommand(const String &command,
     HANDLE stdoutRead, stdoutWrite;
     HANDLE stderrRead, stderrWrite;
     if (!CreatePipe(&stdinRead, &stdinWrite, &saAttr, 0))
-           {
-               error("executeProgram: could not create pipe");
+        {
+        error("executeProgram: could not create pipe");
         delete[] paramBuf;
-               return false;
-               
+        return false;
+        } 
     SetHandleInformation(stdinWrite, HANDLE_FLAG_INHERIT, 0);
-       if (!CreatePipe(&stdoutRead, &stdoutWrite, &saAttr, 0))
-           {
-               error("executeProgram: could not create pipe");
+    if (!CreatePipe(&stdoutRead, &stdoutWrite, &saAttr, 0))
+        {
+        error("executeProgram: could not create pipe");
         delete[] paramBuf;
-               return false;
-               
+        return false;
+        } 
     SetHandleInformation(stdoutRead, HANDLE_FLAG_INHERIT, 0);
-       if (!CreatePipe(&stderrRead, &stderrWrite, &saAttr, 0))
-           {
-               error("executeProgram: could not create pipe");
+    if (!CreatePipe(&stderrRead, &stderrWrite, &saAttr, 0))
+        {
+        error("executeProgram: could not create pipe");
         delete[] paramBuf;
-               return false;
-               
+        return false;
+        } 
     SetHandleInformation(stderrRead, HANDLE_FLAG_INHERIT, 0);
 
     // Create the process
@@ -2392,74 +3538,82 @@ bool MakeBase::executeCommand(const String &command,
                 &piProcessInfo))
         {
         error("executeCommand : could not create process : %s",
-                           win32LastError().c_str());
+                    win32LastError().c_str());
         ret = false;
         }
 
+    delete[] paramBuf;
+
     DWORD bytesWritten;
     if (inbuf.size()>0 &&
         !WriteFile(stdinWrite, inbuf.c_str(), inbuf.size(), 
                &bytesWritten, NULL))
         {
         error("executeCommand: could not write to pipe");
-               return false;
-               }       
+        return false;
+        }    
     if (!CloseHandle(stdinWrite))
-           {           
+        {          
         error("executeCommand: could not close write pipe");
-               return false;
-               }
+        return false;
+        }
     if (!CloseHandle(stdoutWrite))
-           {
+        {
         error("executeCommand: could not close read pipe");
-               return false;
-               }
+        return false;
+        }
     if (!CloseHandle(stderrWrite))
-           {
+        {
         error("executeCommand: could not close read pipe");
-               return false;
-               }
-       while (true)
+        return false;
+        }
+
+    bool lastLoop = false;
+    while (true)
         {
-        //trace("## stderr");
         DWORD avail;
-        if (!PeekNamedPipe(stderrRead, NULL, 0, NULL, &avail, NULL))
-            break;
+        DWORD bytesRead;
+        char readBuf[4096];
+
+        //trace("## stderr");
+        PeekNamedPipe(stderrRead, NULL, 0, NULL, &avail, NULL);
         if (avail > 0)
             {
-            DWORD bytesRead = 0;
-            char readBuf[1025];
-            if (avail>1024) avail = 1024;
-            if (!ReadFile(stderrRead, readBuf, avail, &bytesRead, NULL)
-                || bytesRead == 0)
+            bytesRead = 0;
+            if (avail>4096) avail = 4096;
+            ReadFile(stderrRead, readBuf, avail, &bytesRead, NULL);
+            if (bytesRead > 0)
                 {
-                break;
+                for (unsigned int i=0 ; i<bytesRead ; i++)
+                    errbuf.push_back(readBuf[i]);
                 }
-            for (unsigned int i=0 ; i<bytesRead ; i++)
-                errbuf.push_back(readBuf[i]);
             }
+
         //trace("## stdout");
-        if (!PeekNamedPipe(stdoutRead, NULL, 0, NULL, &avail, NULL))
-            break;
+        PeekNamedPipe(stdoutRead, NULL, 0, NULL, &avail, NULL);
         if (avail > 0)
             {
-            DWORD bytesRead = 0;
-            char readBuf[1025];
-            if (avail>1024) avail = 1024;
-            if (!ReadFile(stdoutRead, readBuf, avail, &bytesRead, NULL)
-                || bytesRead==0)
+            bytesRead = 0;
+            if (avail>4096) avail = 4096;
+            ReadFile(stdoutRead, readBuf, avail, &bytesRead, NULL);
+            if (bytesRead > 0)
                 {
-                break;
+                for (unsigned int i=0 ; i<bytesRead ; i++)
+                    outbuf.push_back(readBuf[i]);
                 }
-            for (unsigned int i=0 ; i<bytesRead ; i++)
-                outbuf.push_back(readBuf[i]);
             }
-               DWORD exitCode;
+            
+        //Was this the final check after program done?
+        if (lastLoop)
+            break;
+
+        DWORD exitCode;
         GetExitCodeProcess(piProcessInfo.hProcess, &exitCode);
         if (exitCode != STILL_ACTIVE)
-            break;
-        Sleep(100);
-        }      
+            lastLoop = true;
+
+        Sleep(10);
+        }    
     //trace("outbuf:%s", outbuf.c_str());
     if (!CloseHandle(stdoutRead))
         {
@@ -2480,11 +3634,9 @@ bool MakeBase::executeCommand(const String &command,
         ret = false;
         }
     
-    // Clean up
     CloseHandle(piProcessInfo.hProcess);
     CloseHandle(piProcessInfo.hThread);
 
-
     return ret;
 
 #else //do it unix-style
@@ -2503,15 +3655,15 @@ bool MakeBase::executeCommand(const String &command,
             }
         errnum = pclose(f);
         }
-       outbuf = s;
-       if (errnum < 0)
-           {
-           error("exec of command '%s' failed : %s",
-                    command.c_str(), strerror(errno));
-           return false;
-           }
-       else
-           return true;
+    outbuf = s;
+    if (errnum != 0)
+        {
+        error("exec of command '%s' failed : %s",
+             command.c_str(), strerror(errno));
+        return false;
+        }
+    else
+        return true;
 
 #endif
 } 
@@ -2569,7 +3721,6 @@ bool MakeBase::listDirectories(const String &baseName,
 
 bool MakeBase::listFiles(const String &baseDir,
                          const String &dirName,
-                         std::vector<String> &excludes,
                          std::vector<String> &res)
 {
     String fullDir = baseDir;
@@ -2582,6 +3733,12 @@ bool MakeBase::listFiles(const String &baseDir,
 
     std::vector<String> subdirs;
     DIR *dir = opendir(dirNative.c_str());
+    if (!dir)
+        {
+        error("Could not open directory %s : %s",
+              dirNative.c_str(), strerror(errno));
+        return false;
+        }
     while (true)
         {
         struct dirent *de = readdir(dir);
@@ -2603,34 +3760,22 @@ bool MakeBase::listFiles(const String &baseDir,
         fullChild.append("/");
         fullChild.append(childName);
         
-        if (std::find(excludes.begin(), excludes.end(), childName)
-                       != excludes.end())
-            {
-            //trace("EXCLUDED:%s", childName.c_str());
-            continue;
-            }
-
-        struct stat finfo;
-        String nativeName = getNativePath(fullChild);
-        if (stat(nativeName.c_str(), &finfo)<0)
-            {
-            error("cannot stat file:%s", childName.c_str());
-            return false;
-            }
-        else if (S_ISDIR(finfo.st_mode))
+        if (isDirectory(fullChild))
             {
             //trace("directory: %s", childName.c_str());
-            if (!listFiles(baseDir, childName, excludes, res))
+            if (!listFiles(baseDir, childName, res))
                 return false;
+            continue;
             }
-        else if (!S_ISREG(finfo.st_mode))
-            {
-            trace("not regular: %s", childName.c_str());
-            }
-        else
+        else if (!isRegularFile(fullChild))
             {
-            res.push_back(childName);
+            error("unknown file:%s", childName.c_str());
+            return false;
             }
+
+       //all done!
+        res.push_back(childName);
+
         }
     closedir(dir);
 
@@ -2638,7 +3783,68 @@ bool MakeBase::listFiles(const String &baseDir,
 }
 
 
+bool MakeBase::listFiles(MakeBase &propRef, FileSet &fileSet)
+{
+    String baseDir = propRef.resolve(fileSet.getDirectory());
+    std::vector<String> fileList;
+    if (!listFiles(baseDir, "", fileList))
+        return false;
+
+    std::vector<String> includes = fileSet.getIncludes();
+    std::vector<String> excludes = fileSet.getExcludes();
+
+    std::vector<String> incs;
+    std::vector<String>::iterator iter;
+
+    std::sort(fileList.begin(), fileList.end());
+
+    //If there are <includes>, then add files to the output
+    //in the order of the include list
+    if (includes.size()==0)
+        incs = fileList;
+    else
+        {
+        for (iter = includes.begin() ; iter != includes.end() ; iter++)
+            {
+            String pattern = *iter;
+            std::vector<String>::iterator siter;
+            for (siter = fileList.begin() ; siter != fileList.end() ; siter++)
+                {
+                String s = *siter;
+                if (regexMatch(s, pattern))
+                    {
+                    //trace("INCLUDED:%s", s.c_str());
+                    incs.push_back(s);
+                    }
+                }
+            }
+        }
+
+    //Now trim off the <excludes>
+    std::vector<String> res;
+    for (iter = incs.begin() ; iter != incs.end() ; iter++)
+        {
+        String s = *iter;
+        bool skipme = false;
+        std::vector<String>::iterator siter;
+        for (siter = excludes.begin() ; siter != excludes.end() ; siter++)
+            {
+            String pattern = *siter;
+            if (regexMatch(s, pattern))
+                {
+                //trace("EXCLUDED:%s", s.c_str());
+                skipme = true;
+                break;
+                }
+            }
+        if (!skipme)
+            res.push_back(s);
+        }
+        
+    fileSet.setFiles(res);
 
+    return true;
+}
 
 
 
@@ -2653,44 +3859,44 @@ bool MakeBase::getSubstitutions(const String &str, String &result)
         {
         char ch = s[i];
         if (ch == '$' && s[i+1] == '{')
-                   {
+            {
             String varname;
-                   int j = i+2;
-                   for ( ; j<len ; j++)
-                       {
-                       ch = s[j];
-                       if (ch == '$' && s[j+1] == '{')
-                           {
-                           error("attribute %s cannot have nested variable references",
-                                  s.c_str());
-                           return false;
-                           }
-                       else if (ch == '}')
-                           {
-                           std::map<String, String>::iterator iter;
-                           iter = properties.find(trim(varname));
-                           if (iter != properties.end())
-                               {
-                               val.append(iter->second);
-                               }
-                           else
-                               {
-                               error("property ${%s} not found", varname.c_str());
-                               return false;
-                               }
-                           break;
-                           }
-                       else
-                           {
-                           varname.push_back(ch);
-                           }
-                       }
-                   i = j;
-                       }
-               else
-                   {
-                   val.push_back(ch);
-                   }
+            int j = i+2;
+            for ( ; j<len ; j++)
+                {
+                ch = s[j];
+                if (ch == '$' && s[j+1] == '{')
+                    {
+                    error("attribute %s cannot have nested variable references",
+                           s.c_str());
+                    return false;
+                    }
+                else if (ch == '}')
+                    {
+                    std::map<String, String>::iterator iter;
+                    iter = properties.find(trim(varname));
+                    if (iter != properties.end())
+                        {
+                        val.append(iter->second);
+                        }
+                    else
+                        {
+                        error("property ${%s} not found", varname.c_str());
+                        return false;
+                        }
+                    break;
+                    }
+                else
+                    {
+                    varname.push_back(ch);
+                    }
+                }
+            i = j;
+            }
+        else
+            {
+            val.push_back(ch);
+            }
         }
     result = val;
     return true;
@@ -2708,37 +3914,14 @@ bool MakeBase::getAttribute(Element *elem, const String &name,
 bool MakeBase::getValue(Element *elem, String &result)
 {
     String s = elem->getValue();
-    int len = s.size();
     //Replace all runs of whitespace with a single space
-    String stripped; 
-    for (int i = 0 ; i<len ; i++)
-        {
-        char ch = s[i];
-        if (isspace(ch))
-            {
-            stripped.push_back(' ');
-            for ( ; i<len ; i++)
-                {
-                ch = s[i];
-                if (!isspace(ch))
-                    {
-                    stripped.push_back(ch);
-                    break;
-                    }
-                }
-            }
-        else
-            {
-            stripped.push_back(ch);
-            }
-        }
-    return getSubstitutions(stripped, result);
+    return getSubstitutions(s, result);
 }
 
 
 /**
  * Turn 'true' and 'false' into boolean values
- */                
+ */             
 bool MakeBase::getBool(const String &str, bool &val)
 {
     if (str == "true")
@@ -2759,11 +3942,11 @@ bool MakeBase::getBool(const String &str, bool &val)
 /**
  * Parse a <patternset> entry
  */  
-bool MakeBase::getPatternSet(Element *elem,
+bool MakeBase::parsePatternSet(Element *elem,
                           MakeBase &propRef,
-                                                 std::vector<String> &includes,
-                                                 std::vector<String> &excludes
-                                                 )
+                          std::vector<String> &includes,
+                          std::vector<String> &excludes
+                          )
 {
     std::vector<Element *> children  = elem->getChildren();
     for (unsigned int i=0 ; i<children.size() ; i++)
@@ -2773,16 +3956,16 @@ bool MakeBase::getPatternSet(Element *elem,
         if (tagName == "exclude")
             {
             String fname;
-                       if (!propRef.getAttribute(child, "name", fname))
-                           return false;
+            if (!propRef.getAttribute(child, "name", fname))
+                return false;
             //trace("EXCLUDE: %s", fname.c_str());
             excludes.push_back(fname);
             }
         else if (tagName == "include")
             {
             String fname;
-                       if (!propRef.getAttribute(child, "name", fname))
-                           return false;
+            if (!propRef.getAttribute(child, "name", fname))
+                return false;
             //trace("INCLUDE: %s", fname.c_str());
             includes.push_back(fname);
             }
@@ -2798,10 +3981,9 @@ bool MakeBase::getPatternSet(Element *elem,
  * Parse a <fileset> entry, and determine which files
  * should be included
  */  
-bool MakeBase::getFileSet(Element *elem,
+bool MakeBase::parseFileSet(Element *elem,
                           MakeBase &propRef,
-                                                 String &dir,
-                                                 std::vector<String> &result)
+                          FileSet &fileSet)
 {
     String name = elem->getName();
     if (name != "fileset")
@@ -2815,7 +3997,7 @@ bool MakeBase::getFileSet(Element *elem,
     std::vector<String> excludes;
 
     //A fileset has one implied patternset
-    if (!getPatternSet(elem, propRef, includes, excludes))
+    if (!parsePatternSet(elem, propRef, includes, excludes))
         {
         return false;
         }
@@ -2827,43 +4009,43 @@ bool MakeBase::getFileSet(Element *elem,
         String tagName = child->getName();
         if (tagName == "patternset")
             {
-            if (!getPatternSet(child, propRef, includes, excludes))
+            if (!parsePatternSet(child, propRef, includes, excludes))
                 {
                 return false;
                 }
             }
         }
 
+    String dir;
     //Now do the stuff
     //Get the base directory for reading file names
     if (!propRef.getAttribute(elem, "dir", dir))
         return false;
 
+    fileSet.setDirectory(dir);
+    fileSet.setIncludes(includes);
+    fileSet.setExcludes(excludes);
+    
+    /*
     std::vector<String> fileList;
     if (dir.size() > 0)
         {
         String baseDir = propRef.resolve(dir);
-           if (!listFiles(baseDir, "", excludes, fileList))
-               return false;
-           }
-       
-       std::vector<String>::iterator iter;
-    for (iter=includes.begin() ; iter!=includes.end() ; iter++)
+        if (!listFiles(baseDir, "", includes, excludes, fileList))
+            return false;
+        }
+    std::sort(fileList.begin(), fileList.end());
+    result = fileList;
+    */
+
+    
+    /*
+    for (unsigned int i=0 ; i<result.size() ; i++)
         {
-        String fname = *iter;
-        fileList.push_back(fname);
+        trace("RES:%s", result[i].c_str());
         }
-        
-       result = fileList;
-       
-       /*
-       for (unsigned int i=0 ; i<result.size() ; i++)
-           {
-           trace("RES:%s", result[i].c_str());
-           }
     */
 
-    std::sort(fileList.begin(), fileList.end());
     
     return true;
 }
@@ -2873,7 +4055,7 @@ bool MakeBase::getFileSet(Element *elem,
 /**
  * Create a directory, making intermediate dirs
  * if necessary
- */                        
+ */                  
 bool MakeBase::createDirectory(const String &dirname)
 {
     //trace("## createDirectory: %s", dirname.c_str());
@@ -2881,12 +4063,16 @@ bool MakeBase::createDirectory(const String &dirname)
     struct stat finfo;
     String nativeDir = getNativePath(dirname);
     char *cnative = (char *) nativeDir.c_str();
-    if (stat(dirname.c_str(), &finfo)==0)
+#ifdef __WIN32__
+    if (strlen(cnative)==2 && cnative[1]==':')
+        return true;
+#endif
+    if (stat(cnative, &finfo)==0)
         {
         if (!S_ISDIR(finfo.st_mode))
             {
             error("mkdir: file %s exists but is not a directory",
-                             cnative);
+                  cnative);
             return false;
             }
         else //exists
@@ -2898,17 +4084,23 @@ bool MakeBase::createDirectory(const String &dirname)
     //## 2: pull off the last path segment, if any,
     //## to make the dir 'above' this one, if necessary
     unsigned int pos = dirname.find_last_of('/');
-    if (pos != dirname.npos)
+    if (pos>0 && pos != dirname.npos)
         {
         String subpath = dirname.substr(0, pos);
+        //A letter root (c:) ?
         if (!createDirectory(subpath))
             return false;
         }
         
     //## 3: now make
+#ifdef __WIN32__
     if (mkdir(cnative)<0)
+#else
+    if (mkdir(cnative, S_IRWXU | S_IRWXG | S_IRWXO)<0)
+#endif
         {
-        error("cannot make directory %s", cnative);
+        error("cannot make directory '%s' : %s",
+                 cnative, strerror(errno));
         return false;
         }
         
@@ -2961,14 +4153,14 @@ bool MakeBase::removeDirectory(const String &dirName)
         else if (S_ISDIR(finfo.st_mode))
             {
             //trace("DEL dir: %s", childName.c_str());
-                       if (!removeDirectory(childName))
-                   {
-                           return false;
-                           }
+            if (!removeDirectory(childName))
+                {
+                return false;
+                }
             }
         else if (!S_ISREG(finfo.st_mode))
             {
-            trace("not regular: %s", cnative);
+            //trace("not regular: %s", cnative);
             }
         else
             {
@@ -2976,9 +4168,9 @@ bool MakeBase::removeDirectory(const String &dirName)
             if (remove(cnative)<0)
                 {
                 error("error deleting %s : %s",
-                                    cnative, strerror(errno));
-                               return false;
-                               }
+                     cnative, strerror(errno));
+                return false;
+                }
             }
         }
     closedir(dir);
@@ -3008,7 +4200,7 @@ bool MakeBase::copyFile(const String &srcFile, const String &destFile)
     if (stat(srcNative.c_str(), &srcinfo)<0)
         {
         error("source file %s for copy does not exist",
-                        srcNative.c_str());
+                 srcNative.c_str());
         return false;
         }
 
@@ -3030,6 +4222,8 @@ bool MakeBase::copyFile(const String &srcFile, const String &destFile)
         }
 
     //# 3 do the data copy
+#ifndef __WIN32__
+
     FILE *srcf = fopen(srcNative.c_str(), "rb");
     if (!srcf)
         {
@@ -3054,7 +4248,59 @@ bool MakeBase::copyFile(const String &srcFile, const String &destFile)
     fclose(destf);
     fclose(srcf);
 
+#else
+    
+    if (!CopyFile(srcNative.c_str(), destNative.c_str(), false))
+        {
+        error("copyFile from %s to %s failed",
+             srcNative.c_str(), destNative.c_str());
+        return false;
+        }
+        
+#endif /* __WIN32__ */
+
+
+    return true;
+}
+
+
+
+/**
+ * Tests if the file exists and is a regular file
+ */ 
+bool MakeBase::isRegularFile(const String &fileName)
+{
+    String native = getNativePath(fileName);
+    struct stat finfo;
+    
+    //Exists?
+    if (stat(native.c_str(), &finfo)<0)
+        return false;
+
+
+    //check the file mode
+    if (!S_ISREG(finfo.st_mode))
+        return false;
+
+    return true;
+}
+
+/**
+ * Tests if the file exists and is a directory
+ */ 
+bool MakeBase::isDirectory(const String &fileName)
+{
+    String native = getNativePath(fileName);
+    struct stat finfo;
+    
+    //Exists?
+    if (stat(native.c_str(), &finfo)<0)
+        return false;
+
 
+    //check the file mode
+    if (!S_ISDIR(finfo.st_mode))
+        return false;
 
     return true;
 }
@@ -3072,22 +4318,22 @@ bool MakeBase::isNewerThan(const String &fileA, const String &fileB)
     //IF source does not exist, NOT newer
     if (stat(nativeA.c_str(), &infoA)<0)
         {
-               return false;
-               }
+        return false;
+        }
 
     String nativeB = getNativePath(fileB);
     struct stat infoB;
     //IF dest does not exist, YES, newer
     if (stat(nativeB.c_str(), &infoB)<0)
         {
-               return true;
-               }
+        return true;
+        }
 
     //check the actual times
     if (infoA.st_mtime > infoB.st_mtime)
         {
-               return true;
-               }
+        return true;
+        }
 
     return false;
 }
@@ -3109,13 +4355,7 @@ public:
      *
      */
     PkgConfig()
-        { init(); }
-
-    /**
-     *
-     */
-    PkgConfig(const String &namearg)
-        { init(); name = namearg; }
+        { path="."; init(); }
 
     /**
      *
@@ -3141,6 +4381,30 @@ public:
     virtual String getName()
         { return name; }
 
+    /**
+     *
+     */
+    virtual String getPath()
+        { return path; }
+
+    /**
+     *
+     */
+    virtual void setPath(const String &val)
+        { path = val; }
+
+    /**
+     *
+     */
+    virtual String getPrefix()
+        { return prefix; }
+
+    /**
+     *  Allow the user to override the prefix in the file
+     */
+    virtual void setPrefix(const String &val)
+        { prefix = val; }
+
     /**
      *
      */
@@ -3159,6 +4423,17 @@ public:
     virtual String getLibs()
         { return libs; }
 
+    /**
+     *
+     */
+    virtual String getAll()
+        {
+         String ret = cflags;
+         ret.append(" ");
+         ret.append(libs);
+         return ret;
+        }
+
     /**
      *
      */
@@ -3195,12 +4470,21 @@ public:
     virtual std::vector<String> &getRequireList()
         { return requireList; }
 
+    /**
+     *  Read a file for its details
+     */         
     virtual bool readFile(const String &fileName);
 
+    /**
+     *  Read a file for its details
+     */         
+    virtual bool query(const String &name);
+
 private:
 
     void init()
         {
+        //do not set path or prefix here
         name         = "";
         description  = "";
         cflags       = "";
@@ -3218,6 +4502,8 @@ private:
     void assign(const PkgConfig &other)
         {
         name         = other.name;
+        path         = other.path;
+        prefix       = other.prefix;
         description  = other.description;
         cflags       = other.cflags;
         libs         = other.libs;
@@ -3243,12 +4529,18 @@ private:
 
     void parseVersion();
 
+    bool parseLine(const String &lineBuf);
+
     bool parse(const String &buf);
 
     void dumpAttrs();
 
     String name;
 
+    String path;
+
+    String prefix;
+
     String description;
 
     String cflags;
@@ -3292,6 +4584,7 @@ int PkgConfig::get(int pos)
 /**
  *  Skip over all whitespace characters beginning at pos.  Return
  *  the position of the first non-whitespace character.
+ *  Pkg-config is line-oriented, so check for newline
  */
 int PkgConfig::skipwhite(int pos)
 {
@@ -3401,15 +4694,12 @@ void PkgConfig::parseVersion()
 }
 
 
-bool PkgConfig::parse(const String &buf)
+bool PkgConfig::parseLine(const String &lineBuf)
 {
-    init();
-
-    parsebuf = (char *)buf.c_str();
-    parselen = buf.size();
+    parsebuf = (char *)lineBuf.c_str();
+    parselen = lineBuf.size();
     int pos = 0;
-
-
+    
     while (pos < parselen)
         {
         String attrName;
@@ -3430,6 +4720,7 @@ bool PkgConfig::parse(const String &buf)
         pos = getword(pos, attrName);
         if (attrName.size() == 0)
             continue;
+        
         pos = skipwhite(pos);
         ch = get(pos);
         if (ch != ':' && ch != '=')
@@ -3464,10 +4755,18 @@ bool PkgConfig::parse(const String &buf)
                         subName.push_back((char)ch);
                     pos++;
                     }
-                //trace("subName:%s", subName.c_str());
-                String subVal = attrs[subName];
-                //trace("subVal:%s", subVal.c_str());
-                attrVal.append(subVal);
+                //trace("subName:%s %s", subName.c_str(), prefix.c_str());
+                if (subName == "prefix" && prefix.size()>0)
+                    {
+                    attrVal.append(prefix);
+                    //trace("prefix override:%s", prefix.c_str());
+                    }
+                else
+                    {
+                    String subVal = attrs[subName];
+                    //trace("subVal:%s", subVal.c_str());
+                    attrVal.append(subVal);
+                    }
                 }
             else
                 attrVal.push_back((char)ch);
@@ -3477,23 +4776,55 @@ bool PkgConfig::parse(const String &buf)
         attrVal = trim(attrVal);
         attrs[attrName] = attrVal;
 
-        if (attrName == "Name")
+        String attrNameL = toLower(attrName);
+
+        if (attrNameL == "name")
             name = attrVal;
-        else if (attrName == "Description")
+        else if (attrNameL == "description")
             description = attrVal;
-        else if (attrName == "Cflags")
+        else if (attrNameL == "cflags")
             cflags = attrVal;
-        else if (attrName == "Libs")
+        else if (attrNameL == "libs")
             libs = attrVal;
-        else if (attrName == "Requires")
+        else if (attrNameL == "requires")
             requires = attrVal;
-        else if (attrName == "Version")
+        else if (attrNameL == "version")
             version = attrVal;
 
         //trace("name:'%s'  value:'%s'",
         //      attrName.c_str(), attrVal.c_str());
         }
 
+    return true;
+}
+
+
+bool PkgConfig::parse(const String &buf)
+{
+    init();
+
+    String line;
+    int lineNr = 0;
+    for (unsigned int p=0 ; p<buf.size() ; p++)
+        {
+        int ch = buf[p];
+        if (ch == '\n' || ch == '\r')
+            {
+            if (!parseLine(line))
+                return false;
+            line.clear();
+            lineNr++;
+            }
+        else
+            {
+            line.push_back(ch);
+            }
+        }
+    if (line.size()>0)
+        {
+        if (!parseLine(line))
+            return false;
+        }
 
     parseRequires();
     parseVersion();
@@ -3501,9 +4832,12 @@ bool PkgConfig::parse(const String &buf)
     return true;
 }
 
+
+
+
 void PkgConfig::dumpAttrs()
 {
-    trace("### PkgConfig attributes for %s", fileName.c_str());
+    //trace("### PkgConfig attributes for %s", fileName.c_str());
     std::map<String, String>::iterator iter;
     for (iter=attrs.begin() ; iter!=attrs.end() ; iter++)
         {
@@ -3512,9 +4846,9 @@ void PkgConfig::dumpAttrs()
 }
 
 
-bool PkgConfig::readFile(const String &fileNameArg)
+bool PkgConfig::readFile(const String &fname)
 {
-    fileName = fileNameArg;
+    fileName = getNativePath(fname);
 
     FILE *f = fopen(fileName.c_str(), "r");
     if (!f)
@@ -3532,14 +4866,31 @@ bool PkgConfig::readFile(const String &fileNameArg)
         }
     fclose(f);
 
-    trace("####### File:\n%s", buf.c_str());
+    //trace("####### File:\n%s", buf.c_str());
     if (!parse(buf))
         {
         return false;
         }
 
-    dumpAttrs();
+    //dumpAttrs();
+
+    return true;
+}
+
+
+
+bool PkgConfig::query(const String &pkgName)
+{
+    name = pkgName;
+
+    String fname = path;
+    fname.append("/");
+    fname.append(name);
+    fname.append(".pc");
 
+    if (!readFile(fname))
+        return false;
+    
     return true;
 }
 
@@ -3572,23 +4923,23 @@ public:
      *  Constructor
      */
     FileRec()
-        {init(); type = UNKNOWN;}
+        { init(); type = UNKNOWN; }
 
     /**
      *  Copy constructor
      */
     FileRec(const FileRec &other)
-        {init(); assign(other);}
+        { init(); assign(other); }
     /**
      *  Constructor
      */
     FileRec(int typeVal)
-        {init(); type = typeVal;}
+        { init(); type = typeVal; }
     /**
      *  Assignment operator
      */
     FileRec &operator=(const FileRec &other)
-        {init(); assign(other); return *this;}
+        { init(); assign(other); return *this; }
 
 
     /**
@@ -3710,7 +5061,7 @@ private:
         path     = other.path;
         name     = other.name;
         suffix   = other.suffix;
-        files    = other.files;
+        files    = other.files; //avoid recursion
         }
 
 };
@@ -3724,19 +5075,19 @@ public:
      *  Constructor
      */
     DepTool()
-        {init();}
+        { init(); }
 
     /**
      *  Copy constructor
      */
     DepTool(const DepTool &other)
-        {init(); assign(other);}
+        { init(); assign(other); }
 
     /**
      *  Assignment operator
      */
     DepTool &operator=(const DepTool &other)
-        {init(); assign(other); return *this;}
+        { init(); assign(other); return *this; }
 
 
     /**
@@ -3804,7 +5155,8 @@ public:
     /**
      *  Load a dependency file, generating one if necessary
      */
-    std::vector<DepRec> getDepFile(const String &fileName);
+    std::vector<DepRec> getDepFile(const String &fileName,
+              bool forceRefresh);
 
     /**
      *  Save a dependency file
@@ -3841,7 +5193,7 @@ private:
     /**
      *
      */
-    bool sequ(int pos, char *key);
+    bool sequ(int pos, const char *key);
 
     /**
      *
@@ -3856,9 +5208,7 @@ private:
     /**
      *
      */
-    bool processDependency(FileRec *ofile,
-                           FileRec *include,
-                           int depth);
+    bool processDependency(FileRec *ofile, FileRec *include);
 
     /**
      *
@@ -3877,8 +5227,7 @@ private:
 
     /**
      * A list of all files which will be processed for
-     * dependencies.  This is the only list that has the actual
-     * records.  All other lists have pointers to these records.     
+     * dependencies.
      */
     std::map<String, FileRec *> allFiles;
 
@@ -3886,11 +5235,13 @@ private:
      * The list of .o files, and the
      * dependencies upon them.
      */
-    std::map<String, FileRec *> depFiles;
+    std::map<String, FileRec *> oFiles;
 
     int depFileSize;
     char *depFileBuf;
-    
+
+    static const int readBufSize = 8192;
+    char readBuf[8193];//byte larger
 
 };
 
@@ -3909,13 +5260,15 @@ void DepTool::init()
     fileList.clear();
     directories.clear();
     
-    //clear refs
-    depFiles.clear();
-    //clear records
+    //clear output file list
     std::map<String, FileRec *>::iterator iter;
-    for (iter=allFiles.begin() ; iter!=allFiles.end() ; iter++)
-         delete iter->second;
+    for (iter=oFiles.begin(); iter!=oFiles.end() ; iter++)
+        delete iter->second;
+    oFiles.clear();
 
+    //allFiles actually contains the master copies. delete them
+    for (iter= allFiles.begin(); iter!=allFiles.end() ; iter++)
+        delete iter->second;
     allFiles.clear(); 
 
 }
@@ -3975,7 +5328,7 @@ bool DepTool::createFileList()
         String sfx;
         parseName(fileName, path, basename, sfx);
         if (sfx == "cpp" || sfx == "c" || sfx == "cxx"   ||
-                   sfx == "cc" || sfx == "CC")
+            sfx == "cc" || sfx == "CC")
             {
             FileRec *fe         = new FileRec(FileRec::CFILE);
             fe->path            = path;
@@ -4060,7 +5413,7 @@ int DepTool::getword(int pos, String &ret)
  * Return whether the sequence of characters in the buffer
  * beginning at pos match the key,  for the length of the key
  */
-bool DepTool::sequ(int pos, char *key)
+bool DepTool::sequ(int pos, const char *key)
 {
     while (*key)
         {
@@ -4080,7 +5433,8 @@ bool DepTool::sequ(int pos, char *key)
  */
 bool DepTool::addIncludeFile(FileRec *frec, const String &iname)
 {
-
+    //# if the name is an exact match to a path name
+    //# in allFiles, like "myinc.h"
     std::map<String, FileRec *>::iterator iter =
            allFiles.find(iname);
     if (iter != allFiles.end()) //already exists
@@ -4093,6 +5447,7 @@ bool DepTool::addIncludeFile(FileRec *frec, const String &iname)
         }
     else 
         {
+        //## Ok, it was not found directly
         //look in other dirs
         std::vector<String>::iterator diter;
         for (diter=directories.begin() ;
@@ -4101,12 +5456,17 @@ bool DepTool::addIncludeFile(FileRec *frec, const String &iname)
             String dfname = *diter;
             dfname.append("/");
             dfname.append(iname);
-            iter = allFiles.find(dfname);
+            URI fullPathURI(dfname);  //normalize path name
+            String fullPath = fullPathURI.getPath();
+            if (fullPath[0] == '/')
+                fullPath = fullPath.substr(1);
+            //trace("Normalized %s to %s", dfname.c_str(), fullPath.c_str());
+            iter = allFiles.find(fullPath);
             if (iter != allFiles.end())
                 {
                 FileRec *other = iter->second;
                 //trace("other: '%s'", iname.c_str());
-                frec->files[dfname] = other;
+                frec->files[fullPath] = other;
                 return true;
                 }
             }
@@ -4138,12 +5498,11 @@ bool DepTool::scanFile(const String &fname, FileRec *frec)
         return false;
         }
     String buf;
-    while (true)
+    while (!feof(f))
         {
-        int ch = fgetc(f);
-        if (ch < 0)
-            break;
-        buf.push_back((char)ch);
+        int len = fread(readBuf, 1, readBufSize, f);
+        readBuf[len] = '\0';
+        buf.append(readBuf);
         }
     fclose(f);
 
@@ -4214,9 +5573,7 @@ bool DepTool::scanFile(const String &fname, FileRec *frec)
  *  Recursively check include lists to find all files in allFiles to which
  *  a given file is dependent.
  */
-bool DepTool::processDependency(FileRec *ofile,
-                             FileRec *include,
-                             int depth)
+bool DepTool::processDependency(FileRec *ofile, FileRec *include)
 {
     std::map<String, FileRec *>::iterator iter;
     for (iter=include->files.begin() ; iter!=include->files.end() ; iter++)
@@ -4230,7 +5587,7 @@ bool DepTool::processDependency(FileRec *ofile,
         FileRec *child  = iter->second;
         ofile->files[fname] = child;
       
-        processDependency(ofile, child, depth+1);
+        processDependency(ofile, child);
         }
 
 
@@ -4263,23 +5620,23 @@ bool DepTool::generateDependencies()
         FileRec *include = iter->second;
         if (include->type == FileRec::CFILE)
             {
-            String cFileName = iter->first;
-            FileRec *ofile      = new FileRec(FileRec::OFILE);
-            ofile->path         = include->path;
-            ofile->baseName     = include->baseName;
-            ofile->suffix       = include->suffix;
-            String fname     = include->path;
+            String cFileName   = iter->first;
+            FileRec *ofile     = new FileRec(FileRec::OFILE);
+            ofile->path        = include->path;
+            ofile->baseName    = include->baseName;
+            ofile->suffix      = include->suffix;
+            String fname       = include->path;
             if (fname.size()>0)
                 fname.append("/");
             fname.append(include->baseName);
             fname.append(".o");
-            depFiles[fname]    = ofile;
+            oFiles[fname]    = ofile;
             //add the .c file first?   no, don't
             //ofile->files[cFileName] = include;
             
             //trace("ofile:%s", fname.c_str());
 
-            processDependency(ofile, include, 0);
+            processDependency(ofile, include);
             }
         }
 
@@ -4327,13 +5684,13 @@ bool DepTool::saveDepFile(const String &fileName)
 
     fprintf(f, "<dependencies source='%s'>\n\n", sourceDir.c_str());
     std::map<String, FileRec *>::iterator iter;
-    for (iter=depFiles.begin() ; iter!=depFiles.end() ; iter++)
+    for (iter=oFiles.begin() ; iter!=oFiles.end() ; iter++)
         {
         FileRec *frec = iter->second;
         if (frec->type == FileRec::OFILE)
             {
             fprintf(f, "<object path='%s' name='%s' suffix='%s'>\n",
-                            frec->path.c_str(), frec->baseName.c_str(), frec->suffix.c_str());
+                 frec->path.c_str(), frec->baseName.c_str(), frec->suffix.c_str());
             std::map<String, FileRec *>::iterator citer;
             for (citer=frec->files.begin() ; citer!=frec->files.end() ; citer++)
                 {
@@ -4371,14 +5728,14 @@ std::vector<DepRec> DepTool::loadDepFile(const String &depFile)
     Element *root = parser.parseFile(depFile.c_str());
     if (!root)
         {
-        error("Could not open %s for reading", depFile.c_str());
+        //error("Could not open %s for reading", depFile.c_str());
         return result;
         }
 
     if (root->getChildren().size()==0 ||
         root->getChildren()[0]->getName()!="dependencies")
         {
-        error("Main xml element should be <dependencies>");
+        error("loadDepFile: main xml element should be <dependencies>");
         delete root;
         return result;
         }
@@ -4391,50 +5748,53 @@ std::vector<DepRec> DepTool::loadDepFile(const String &depFile)
         {
         Element *objectElem = objects[i];
         String tagName = objectElem->getName();
-        if (tagName == "object")
-            {
-            String objName   = objectElem->getAttribute("name");
-             //trace("object:%s", objName.c_str());
-            DepRec depObject(objName);
-            depObject.path   = objectElem->getAttribute("path");
-            depObject.suffix = objectElem->getAttribute("suffix");
-            //########## DESCRIPTION
-            std::vector<Element *> depElems = objectElem->getChildren();
-            for (unsigned int i=0 ; i<depElems.size() ; i++)
+        if (tagName != "object")
+            {
+            error("loadDepFile: <dependencies> should have only <object> children");
+            return result;
+            }
+
+        String objName   = objectElem->getAttribute("name");
+         //trace("object:%s", objName.c_str());
+        DepRec depObject(objName);
+        depObject.path   = objectElem->getAttribute("path");
+        depObject.suffix = objectElem->getAttribute("suffix");
+        //########## DESCRIPTION
+        std::vector<Element *> depElems = objectElem->getChildren();
+        for (unsigned int i=0 ; i<depElems.size() ; i++)
+            {
+            Element *depElem = depElems[i];
+            tagName = depElem->getName();
+            if (tagName != "dep")
                 {
-                Element *depElem = depElems[i];
-                tagName = depElem->getName();
-                if (tagName == "dep")
-                    {
-                    String depName = depElem->getAttribute("name");
-                    //trace("    dep:%s", depName.c_str());
-                    depObject.files.push_back(depName);
-                    }
+                error("loadDepFile: <object> should have only <dep> children");
+                return result;
                 }
-            //Insert into the result list, in a sorted manner
-            bool inserted = false;
-            std::vector<DepRec>::iterator iter;
-            for (iter = result.begin() ; iter != result.end() ; iter++)
+            String depName = depElem->getAttribute("name");
+            //trace("    dep:%s", depName.c_str());
+            depObject.files.push_back(depName);
+            }
+
+        //Insert into the result list, in a sorted manner
+        bool inserted = false;
+        std::vector<DepRec>::iterator iter;
+        for (iter = result.begin() ; iter != result.end() ; iter++)
+            {
+            String vpath = iter->path;
+            vpath.append("/");
+            vpath.append(iter->name);
+            String opath = depObject.path;
+            opath.append("/");
+            opath.append(depObject.name);
+            if (vpath > opath)
                 {
-                if (iter->path > depObject.path)
-                    {
-                    inserted = true;
-                    iter = result.insert(iter, depObject);
-                    break;
-                    }
-                else if (iter->path == depObject.path)
-                    {
-                    if (iter->name > depObject.name)
-                        {
-                        inserted = true;
-                        iter = result.insert(iter, depObject);
-                        break;
-                        }
-                    }
+                inserted = true;
+                iter = result.insert(iter, depObject);
+                break;
                 }
-            if (!inserted)
-                result.push_back(depObject);
             }
+        if (!inserted)
+            result.push_back(depObject);
         }
 
     delete root;
@@ -4446,14 +5806,26 @@ std::vector<DepRec> DepTool::loadDepFile(const String &depFile)
 /**
  *   This loads the dependency cache.
  */
-std::vector<DepRec> DepTool::getDepFile(const String &depFile)
+std::vector<DepRec> DepTool::getDepFile(const String &depFile,
+                   bool forceRefresh)
 {
-    std::vector<DepRec> result = loadDepFile(depFile);
-    if (result.size() == 0)
+    std::vector<DepRec> result;
+    if (forceRefresh)
         {
         generateDependencies(depFile);
         result = loadDepFile(depFile);
         }
+    else
+        {
+        //try once
+        result = loadDepFile(depFile);
+        if (result.size() == 0)
+            {
+            //fail? try again
+            generateDependencies(depFile);
+            result = loadDepFile(depFile);
+            }
+        }
     return result;
 }
 
@@ -4478,18 +5850,22 @@ public:
     typedef enum
         {
         TASK_NONE,
-        TASK_AR,
         TASK_CC,
         TASK_COPY,
         TASK_DELETE,
         TASK_JAR,
         TASK_JAVAC,
         TASK_LINK,
+        TASK_MAKEFILE,
         TASK_MKDIR,
         TASK_MSGFMT,
+        TASK_PKG_CONFIG,
         TASK_RANLIB,
         TASK_RC,
+        TASK_SHAREDLIB,
+        TASK_STATICLIB,
         TASK_STRIP,
+        TASK_TOUCH,
         TASK_TSTAMP
         } TaskType;
         
@@ -4558,7 +5934,7 @@ public:
     /**
      *
      */
-    Task *createTask(Element *elem);
+    Task *createTask(Element *elem, int lineNr);
 
 
 protected:
@@ -4590,109 +5966,6 @@ protected:
 
 
 
-
-/**
- * Run the "ar" command to archive .o's into a .a
- */
-class TaskAr : public Task
-{
-public:
-
-    TaskAr(MakeBase &par) : Task(par)
-        {
-               type = TASK_AR; name = "ar";
-               command = "ar crv";
-               }
-
-    virtual ~TaskAr()
-        {}
-
-    virtual bool execute()
-        {
-        //trace("###########HERE %d", fileSet.size());
-        bool doit = false;
-        
-        String fullOut = parent.resolve(fileName);
-        //trace("ar fullout: %s", fullOut.c_str());
-        
-
-        for (unsigned int i=0 ; i<fileSet.size() ; i++)
-            {
-            String fname;
-                       if (fileSetDir.size()>0)
-                           {
-                           fname.append(fileSetDir);
-                fname.append("/");
-                }
-            fname.append(fileSet[i]);
-            String fullName = parent.resolve(fname);
-            //trace("ar : %s/%s", fullOut.c_str(), fullName.c_str());
-            if (isNewerThan(fullName, fullOut))
-                doit = true;
-            }
-        //trace("Needs it:%d", doit);
-        if (!doit)
-            {
-            return true;
-            }
-
-        String cmd = command;
-        cmd.append(" ");
-        cmd.append(fullOut);
-        for (unsigned int i=0 ; i<fileSet.size() ; i++)
-            {
-            String fname;
-                       if (fileSetDir.size()>0)
-                           {
-                           fname.append(fileSetDir);
-                fname.append("/");
-                }
-            fname.append(fileSet[i]);
-            String fullName = parent.resolve(fname);
-
-            cmd.append(" ");
-            cmd.append(fullName);
-            }
-
-        String outString, errString;
-        if (!executeCommand(cmd.c_str(), "", outString, errString))
-            {
-            error("AR problem: %s", errString.c_str());
-            return false;
-            }
-
-        return true;
-        }
-
-    virtual bool parse(Element *elem)
-        {
-        if (!parent.getAttribute(elem, "file", fileName))
-            return false;
-            
-        std::vector<Element *> children = elem->getChildren();
-        for (unsigned int i=0 ; i<children.size() ; i++)
-            {
-            Element *child = children[i];
-            String tagName = child->getName();
-            if (tagName == "fileset")
-                {
-                if (!getFileSet(child, parent, fileSetDir, fileSet))
-                    return false;
-                }
-            }
-        return true;
-        }
-
-private:
-
-    String command;
-    String fileName;
-    String fileSetDir;
-    std::vector<String> fileSet;
-
-};
-
-
 /**
  * This task runs the C/C++ compiler.  The compiler is invoked
  * for all .c or .cpp files which are newer than their correcsponding
@@ -4704,26 +5977,47 @@ public:
 
     TaskCC(MakeBase &par) : Task(par)
         {
-               type = TASK_CC; name = "cc";
-               ccCommand   = "gcc";
-               cxxCommand  = "g++";
-               source      = ".";
-               dest        = ".";
-               flags       = "";
-               defines     = "";
-               includes    = "";
-               sourceFiles.clear();
+        type = TASK_CC; name = "cc";
+        ccCommand   = "gcc";
+        cxxCommand  = "g++";
+        source      = ".";
+        dest        = ".";
+        flags       = "";
+        defines     = "";
+        includes    = "";
+        fileSet.clear();
         }
 
     virtual ~TaskCC()
         {}
 
+    virtual bool needsCompiling(const FileRec &depRec,
+              const String &src, const String &dest)
+        {
+        return false;
+        }
+
     virtual bool execute()
         {
+        if (!listFiles(parent, fileSet))
+            return false;
+            
+        FILE *f = NULL;
+        f = fopen("compile.lst", "w");
+
+        bool refreshCache = false;
+        String fullName = parent.resolve("build.dep");
+        if (isNewerThan(parent.getURI().getPath(), fullName))
+            {
+            status("          : regenerating C/C++ dependency cache");
+            refreshCache = true;
+            }
+
         DepTool depTool;
         depTool.setSourceDirectory(source);
-        depTool.setFileList(sourceFiles);
-        std::vector<DepRec> deps = depTool.getDepFile("build.dep");
+        depTool.setFileList(fileSet.getFiles());
+        std::vector<DepRec> deps =
+             depTool.getDepFile("build.dep", refreshCache);
         
         String incs;
         incs.append("-I");
@@ -4769,37 +6063,80 @@ public:
             //## Select command
             String sfx = dep.suffix;
             String command = ccCommand;
-            if (sfx == "cpp" || sfx == "c++" || sfx == "cc"
-                            || sfx == "CC")
-                           command = cxxCommand;
+            if (sfx == "cpp" || sfx == "cxx" || sfx == "c++" ||
+                 sfx == "cc" || sfx == "CC")
+                command = cxxCommand;
  
             //## Make paths
             String destPath = dest;
             String srcPath  = source;
             if (dep.path.size()>0)
-                           {
+                {
                 destPath.append("/");
-                               destPath.append(dep.path);
+                destPath.append(dep.path);
                 srcPath.append("/");
-                               srcPath.append(dep.path);
-                           }
+                srcPath.append(dep.path);
+                }
             //## Make sure destination directory exists
-                       if (!createDirectory(destPath))
-                           return false;
-                           
+            if (!createDirectory(destPath))
+                return false;
+                
             //## Check whether it needs to be done
-                       String destFullName = destPath;
-                       destFullName.append("/");
-                       destFullName.append(dep.name);
-                       destFullName.append(".o");
-                       String srcFullName = srcPath;
-                       srcFullName.append("/");
-                       srcFullName.append(dep.name);
-                       srcFullName.append(".");
-                       srcFullName.append(dep.suffix);
-            if (!isNewerThan(srcFullName, destFullName))
+            String destName;
+            if (destPath.size()>0)
+                {
+                destName.append(destPath);
+                destName.append("/");
+                }
+            destName.append(dep.name);
+            destName.append(".o");
+            String destFullName = parent.resolve(destName);
+            String srcName;
+            if (srcPath.size()>0)
+                {
+                srcName.append(srcPath);
+                srcName.append("/");
+                }
+            srcName.append(dep.name);
+            srcName.append(".");
+            srcName.append(dep.suffix);
+            String srcFullName = parent.resolve(srcName);
+            bool compileMe = false;
+            //# First we check if the source is newer than the .o
+            if (isNewerThan(srcFullName, destFullName))
+                {
+                status("          : compile of %s required by %s",
+                        destFullName.c_str(), srcFullName.c_str());
+                compileMe = true;
+                }
+            else
+                {
+                //# secondly, we check if any of the included dependencies
+                //# of the .c/.cpp is newer than the .o
+                for (unsigned int i=0 ; i<dep.files.size() ; i++)
+                    {
+                    String depName;
+                    if (source.size()>0)
+                        {
+                        depName.append(source);
+                        depName.append("/");
+                        }
+                    depName.append(dep.files[i]);
+                    String depFullName = parent.resolve(depName);
+                    bool depRequires = isNewerThan(depFullName, destFullName);
+                    //trace("%d %s %s\n", depRequires,
+                    //        destFullName.c_str(), depFullName.c_str());
+                    if (depRequires)
+                        {
+                        status("          : compile of %s required by %s",
+                                destFullName.c_str(), depFullName.c_str());
+                        compileMe = true;
+                        break;
+                        }
+                    }
+                }
+            if (!compileMe)
                 {
-                //trace("%s skipped", srcFullName.c_str());
                 continue;
                 }
 
@@ -4807,23 +6144,60 @@ public:
             String cmd = command;
             cmd.append(" -c ");
             cmd.append(flags);
-                       cmd.append(" ");
+            cmd.append(" ");
             cmd.append(defines);
-                       cmd.append(" ");
+            cmd.append(" ");
             cmd.append(incs);
-                       cmd.append(" ");
-                       cmd.append(srcFullName);
+            cmd.append(" ");
+            cmd.append(srcFullName);
             cmd.append(" -o ");
-                       cmd.append(destFullName);
+            cmd.append(destFullName);
 
             //## Execute the command
 
             String outString, errString;
-            if (!executeCommand(cmd.c_str(), "", outString, errString))
+            bool ret = executeCommand(cmd.c_str(), "", outString, errString);
+
+            if (f)
+                {
+                fprintf(f, "########################### File : %s\n",
+                             srcFullName.c_str());
+                fprintf(f, "#### COMMAND ###\n");
+                int col = 0;
+                for (unsigned int i = 0 ; i < cmd.size() ; i++)
+                    {
+                    char ch = cmd[i];
+                    if (isspace(ch)  && col > 63)
+                        {
+                        fputc('\n', f);
+                        col = 0;
+                        }
+                    else
+                        {
+                        fputc(ch, f);
+                        col++;
+                        }
+                    if (col > 76)
+                        {
+                        fputc('\n', f);
+                        col = 0;
+                        }
+                    }
+                fprintf(f, "\n");
+                fprintf(f, "#### STDOUT ###\n%s\n", outString.c_str());
+                fprintf(f, "#### STDERR ###\n%s\n\n", errString.c_str());
+                }
+            if (!ret)
                 {
                 error("problem compiling: %s", errString.c_str());
                 return false;
                 }
+                
+            }
+
+        if (f)
+            {
+            fclose(f);
             }
         
         return true;
@@ -4854,21 +6228,25 @@ public:
                 {
                 if (!parent.getValue(child, flags))
                     return false;
+                flags = strip(flags);
                 }
             else if (tagName == "includes")
                 {
                 if (!parent.getValue(child, includes))
                     return false;
+                includes = strip(includes);
                 }
             else if (tagName == "defines")
                 {
                 if (!parent.getValue(child, defines))
                     return false;
+                defines = strip(defines);
                 }
             else if (tagName == "fileset")
                 {
-                if (!getFileSet(child, parent, source, sourceFiles))
+                if (!parseFileSet(child, parent, fileSet))
                     return false;
+                source = fileSet.getDirectory();
                 }
             }
 
@@ -4884,7 +6262,7 @@ protected:
     String flags;
     String defines;
     String includes;
-    std::vector<String> sourceFiles;
+    FileSet fileSet;
     
 };
 
@@ -4906,11 +6284,11 @@ public:
 
     TaskCopy(MakeBase &par) : Task(par)
         {
-               type = TASK_COPY; name = "copy";
-               cptype = CP_NONE;
-               verbose = false;
-               haveFileSet = false;
-               }
+        type = TASK_COPY; name = "copy";
+        cptype = CP_NONE;
+        verbose = false;
+        haveFileSet = false;
+        }
 
     virtual ~TaskCopy()
         {}
@@ -4923,13 +6301,20 @@ public:
                {
                if (fileName.size()>0)
                    {
-                   status("          : %s", fileName.c_str());
+                   status("          : %s to %s",
+                        fileName.c_str(), toFileName.c_str());
                    String fullSource = parent.resolve(fileName);
                    String fullDest = parent.resolve(toFileName);
                    //trace("copy %s to file %s", fullSource.c_str(),
-                                  //                       fullDest.c_str());
+                   //                       fullDest.c_str());
+                   if (!isRegularFile(fullSource))
+                       {
+                       error("copy : file %s does not exist", fullSource.c_str());
+                       return false;
+                       }
                    if (!isNewerThan(fullSource, fullDest))
                        {
+                       status("          : skipped");
                        return true;
                        }
                    if (!copyFile(fullSource, fullDest))
@@ -4942,8 +6327,14 @@ public:
                {
                if (haveFileSet)
                    {
+                   if (!listFiles(parent, fileSet))
+                       return false;
+                   String fileSetDir = fileSet.getDirectory();
+
+                   status("          : %s to %s",
+                       fileSetDir.c_str(), toDirName.c_str());
+
                    int nrFiles = 0;
-                   status("          : %s", fileSetDir.c_str());
                    for (unsigned int i=0 ; i<fileSet.size() ; i++)
                        {
                        String fileName = fileSet[i];
@@ -4961,11 +6352,11 @@ public:
                        String baseFileSetDir = fileSetDir;
                        unsigned int pos = baseFileSetDir.find_last_of('/');
                        if (pos!=baseFileSetDir.npos &&
-                                                     pos < baseFileSetDir.size()-1)
+                                  pos < baseFileSetDir.size()-1)
                            baseFileSetDir =
-                                                     baseFileSetDir.substr(pos+1,
-                                                              baseFileSetDir.size());
-                                          //Now make the new path
+                              baseFileSetDir.substr(pos+1,
+                                   baseFileSetDir.size());
+                       //Now make the new path
                        String destPath;
                        if (toDirName.size()>0)
                            {
@@ -4981,7 +6372,7 @@ public:
                        String fullDest = parent.resolve(destPath);
                        //trace("fileName:%s", fileName.c_str());
                        //trace("copy %s to new dir : %s", fullSource.c_str(),
-                                      //                   fullDest.c_str());
+                       //                   fullDest.c_str());
                        if (!isNewerThan(fullSource, fullDest))
                            {
                            //trace("copy skipping %s", fullSource.c_str());
@@ -4997,7 +6388,8 @@ public:
                    {
                    //For file->dir we want only the basename of
                    //the source appended to the dest dir
-                   status("          : %s", fileName.c_str());
+                   status("          : %s to %s", 
+                       fileName.c_str(), toDirName.c_str());
                    String baseName = fileName;
                    unsigned int pos = baseName.find_last_of('/');
                    if (pos!=baseName.npos && pos<baseName.size()-1)
@@ -5012,9 +6404,15 @@ public:
                    destPath.append(baseName);
                    String fullDest = parent.resolve(destPath);
                    //trace("copy %s to new dir : %s", fullSource.c_str(),
-                                  //                       fullDest.c_str());
+                   //                       fullDest.c_str());
+                   if (!isRegularFile(fullSource))
+                       {
+                       error("copy : file %s does not exist", fullSource.c_str());
+                       return false;
+                       }
                    if (!isNewerThan(fullSource, fullDest))
                        {
+                       status("          : skipped");
                        return true;
                        }
                    if (!copyFile(fullSource, fullDest))
@@ -5055,21 +6453,21 @@ public:
             String tagName = child->getName();
             if (tagName == "fileset")
                 {
-                if (!getFileSet(child, parent, fileSetDir, fileSet))
+                if (!parseFileSet(child, parent, fileSet))
                     {
                     error("problem getting fileset");
-                                       return false;
-                                       }
-                               haveFileSet = true;
+                    return false;
+                    }
+                haveFileSet = true;
                 }
             }
 
         //Perform validity checks
-               if (fileName.size()>0 && fileSet.size()>0)
-                   {
-                   error("<copy> can only have one of : file= and <fileset>");
-                   return false;
-                   }
+        if (fileName.size()>0 && fileSet.size()>0)
+            {
+            error("<copy> can only have one of : file= and <fileset>");
+            return false;
+            }
         if (toFileName.size()>0 && toDirName.size()>0)
             {
             error("<copy> can only have one of : tofile= or todir=");
@@ -5080,16 +6478,16 @@ public:
             error("a <copy> task with a <fileset> must have : todir=");
             return false;
             }
-               if (cptype == CP_TOFILE && fileName.size()==0)
-                   {
-                   error("<copy> tofile= must be associated with : file=");
-                   return false;
-                   }
-               if (cptype == CP_TODIR && fileName.size()==0 && !haveFileSet)
-                   {
-                   error("<copy> todir= must be associated with : file= or <fileset>");
-                   return false;
-                   }
+        if (cptype == CP_TOFILE && fileName.size()==0)
+            {
+            error("<copy> tofile= must be associated with : file=");
+            return false;
+            }
+        if (cptype == CP_TODIR && fileName.size()==0 && !haveFileSet)
+            {
+            error("<copy> todir= must be associated with : file= or <fileset>");
+            return false;
+            }
 
         return true;
         }
@@ -5098,8 +6496,7 @@ private:
 
     int cptype;
     String fileName;
-    String fileSetDir;
-    std::vector<String> fileSet;
+    FileSet fileSet;
     String toFileName;
     String toDirName;
     bool verbose;
@@ -5123,13 +6520,13 @@ public:
 
     TaskDelete(MakeBase &par) : Task(par)
         { 
-                 type        = TASK_DELETE;
-                 name        = "delete";
-                 delType     = DEL_FILE;
+          type        = TASK_DELETE;
+          name        = "delete";
+          delType     = DEL_FILE;
           verbose     = false;
           quiet       = false;
           failOnError = true;
-               }
+        }
 
     virtual ~TaskDelete()
         {}
@@ -5185,7 +6582,12 @@ public:
             delType = DEL_DIR;
         if (fileName.size()>0 && dirName.size()>0)
             {
-            error("<delete> can only have one attribute of file= or dir=");
+            error("<delete> can have one attribute of file= or dir=");
+            return false;
+            }
+        if (fileName.size()==0 && dirName.size()==0)
+            {
+            error("<delete> must have one attribute of file= or dir=");
             return false;
             }
         String ret;
@@ -5274,15 +6676,22 @@ public:
 
     TaskLink(MakeBase &par) : Task(par)
         {
-               type = TASK_LINK; name = "link";
-               command = "g++";
-               }
+        type = TASK_LINK; name = "link";
+        command = "g++";
+        doStrip = false;
+                stripCommand = "strip";
+                objcopyCommand = "objcopy";
+        }
 
     virtual ~TaskLink()
         {}
 
     virtual bool execute()
         {
+        if (!listFiles(parent, fileSet))
+            return false;
+        String fileSetDir = fileSet.getDirectory();
+        //trace("%d files in %s", fileSet.size(), fileSetDir.c_str());
         bool doit = false;
         String fullTarget = parent.resolve(fileName);
         String cmd = command;
@@ -5295,13 +6704,16 @@ public:
             cmd.append(" ");
             String obj;
             if (fileSetDir.size()>0)
-                           {
-                               obj.append(fileSetDir);
+                {
+                obj.append(fileSetDir);
                 obj.append("/");
                 }
             obj.append(fileSet[i]);
             String fullObj = parent.resolve(obj);
-            cmd.append(fullObj);
+            String nativeFullObj = getNativePath(fullObj);
+            cmd.append(nativeFullObj);
+            //trace("link: tgt:%s obj:%s", fullTarget.c_str(),
+            //          fullObj.c_str());
             if (isNewerThan(fullObj, fullTarget))
                 doit = true;
             }
@@ -5315,21 +6727,66 @@ public:
         //trace("LINK cmd:%s", cmd.c_str());
 
 
-        String outString, errString;
-        if (!executeCommand(cmd.c_str(), "", outString, errString))
+        String outbuf, errbuf;
+        if (!executeCommand(cmd.c_str(), "", outbuf, errbuf))
             {
-            error("LINK problem: %s", errString.c_str());
+            error("LINK problem: %s", errbuf.c_str());
             return false;
             }
+
+        if (symFileName.size()>0)
+            {
+            String symFullName = parent.resolve(symFileName);
+            cmd = objcopyCommand;
+            cmd.append(" --only-keep-debug ");
+            cmd.append(getNativePath(fullTarget));
+            cmd.append(" ");
+            cmd.append(getNativePath(symFullName));
+            if (!executeCommand(cmd, "", outbuf, errbuf))
+                {
+                error("<strip> symbol file failed : %s", errbuf.c_str());
+                return false;
+                }
+            }
+            
+        if (doStrip)
+            {
+            cmd = stripCommand;
+            cmd.append(" ");
+            cmd.append(getNativePath(fullTarget));
+            if (!executeCommand(cmd, "", outbuf, errbuf))
+               {
+               error("<strip> failed : %s", errbuf.c_str());
+               return false;
+               }
+            }
+
         return true;
         }
 
     virtual bool parse(Element *elem)
         {
-        if (!parent.getAttribute(elem, "command", command))
+        String s;
+        if (!parent.getAttribute(elem, "command", s))
+            return false;
+        if (s.size()>0)
+            command = s;
+        if (!parent.getAttribute(elem, "objcopycommand", s))
             return false;
+        if (s.size()>0)
+            objcopyCommand = s;
+        if (!parent.getAttribute(elem, "stripcommand", s))
+            return false;
+        if (s.size()>0)
+            stripCommand = s;
         if (!parent.getAttribute(elem, "out", fileName))
             return false;
+        if (!parent.getAttribute(elem, "strip", s))
+            return false;
+        if (s.size()>0 && !getBool(s, doStrip))
+            return false;
+        if (!parent.getAttribute(elem, "symfile", symFileName))
+            return false;
             
         std::vector<Element *> children = elem->getChildren();
         for (unsigned int i=0 ; i<children.size() ; i++)
@@ -5338,18 +6795,20 @@ public:
             String tagName = child->getName();
             if (tagName == "fileset")
                 {
-                if (!getFileSet(child, parent, fileSetDir, fileSet))
+                if (!parseFileSet(child, parent, fileSet))
                     return false;
                 }
             else if (tagName == "flags")
                 {
                 if (!parent.getValue(child, flags))
                     return false;
+                flags = strip(flags);
                 }
             else if (tagName == "libs")
                 {
                 if (!parent.getValue(child, libs))
                     return false;
+                libs = strip(libs);
                 }
             }
         return true;
@@ -5357,12 +6816,15 @@ public:
 
 private:
 
-    String command;
-    String fileName;
-    String flags;
-    String libs;
-    String fileSetDir;
-    std::vector<String> fileSet;
+    String  command;
+    String  fileName;
+    String  flags;
+    String  libs;
+    FileSet fileSet;
+    bool    doStrip;
+    String  symFileName;
+    String  stripCommand;
+    String  objcopyCommand;
 
 };
 
@@ -5371,24 +6833,85 @@ private:
 /**
  * Create a named directory
  */
-class TaskMkDir : public Task
+class TaskMakeFile : public Task
 {
 public:
 
-    TaskMkDir(MakeBase &par) : Task(par)
-        { type = TASK_MKDIR; name = "mkdir"; }
+    TaskMakeFile(MakeBase &par) : Task(par)
+        { type = TASK_MAKEFILE; name = "makefile"; }
 
-    virtual ~TaskMkDir()
+    virtual ~TaskMakeFile()
         {}
 
     virtual bool execute()
         {
-        status("          : %s", dirName.c_str());
-        String fullDir = parent.resolve(dirName);
-        //trace("fullDir:%s", fullDir.c_str());
-        if (!createDirectory(fullDir))
+        status("          : %s", fileName.c_str());
+        String fullName = parent.resolve(fileName);
+        if (!isNewerThan(parent.getURI().getPath(), fullName))
+            {
+            //trace("skipped <makefile>");
+            return true;
+            }
+        //trace("fullName:%s", fullName.c_str());
+        FILE *f = fopen(fullName.c_str(), "w");
+        if (!f)
+            {
+            error("<makefile> could not open %s for writing : %s",
+                fullName.c_str(), strerror(errno));
             return false;
-        return true;
+            }
+        for (unsigned int i=0 ; i<text.size() ; i++)
+            fputc(text[i], f);
+        fputc('\n', f);
+        fclose(f);
+        return true;
+        }
+
+    virtual bool parse(Element *elem)
+        {
+        if (!parent.getAttribute(elem, "file", fileName))
+            return false;
+        if (fileName.size() == 0)
+            {
+            error("<makefile> requires 'file=\"filename\"' attribute");
+            return false;
+            }
+        if (!parent.getValue(elem, text))
+            return false;
+        text = leftJustify(text);
+        //trace("dirname:%s", dirName.c_str());
+        return true;
+        }
+
+private:
+
+    String fileName;
+    String text;
+};
+
+
+
+/**
+ * Create a named directory
+ */
+class TaskMkDir : public Task
+{
+public:
+
+    TaskMkDir(MakeBase &par) : Task(par)
+        { type = TASK_MKDIR; name = "mkdir"; }
+
+    virtual ~TaskMkDir()
+        {}
+
+    virtual bool execute()
+        {
+        status("          : %s", dirName.c_str());
+        String fullDir = parent.resolve(dirName);
+        //trace("fullDir:%s", fullDir.c_str());
+        if (!createDirectory(fullDir))
+            return false;
+        return true;
         }
 
     virtual bool parse(Element *elem)
@@ -5400,7 +6923,6 @@ public:
             error("<mkdir> requires 'dir=\"dirname\"' attribute");
             return false;
             }
-        //trace("dirname:%s", dirName.c_str());
         return true;
         }
 
@@ -5420,16 +6942,22 @@ public:
 
     TaskMsgFmt(MakeBase &par) : Task(par)
          {
-                type = TASK_MSGFMT;
-                name = "msgfmt";
-                command = "msgfmt";
-                }
+         type    = TASK_MSGFMT;
+         name    = "msgfmt";
+         command = "msgfmt";
+         owndir  = false;
+         outName = "";
+         }
 
     virtual ~TaskMsgFmt()
         {}
 
     virtual bool execute()
         {
+        if (!listFiles(parent, fileSet))
+            return false;
+        String fileSetDir = fileSet.getDirectory();
+
         //trace("msgfmt: %d", fileSet.size());
         for (unsigned int i=0 ; i<fileSet.size() ; i++)
             {
@@ -5437,22 +6965,40 @@ public:
             if (getSuffix(fileName) != "po")
                 continue;
             String sourcePath;
-                       if (fileSetDir.size()>0)
-                           {
-                           sourcePath.append(fileSetDir);
+            if (fileSetDir.size()>0)
+                {
+                sourcePath.append(fileSetDir);
                 sourcePath.append("/");
                 }
             sourcePath.append(fileName);
             String fullSource = parent.resolve(sourcePath);
 
             String destPath;
-                       if (toDirName.size()>0)
-                           {
-                           destPath.append(toDirName);
+            if (toDirName.size()>0)
+                {
+                destPath.append(toDirName);
+                destPath.append("/");
+                }
+            if (owndir)
+                {
+                String subdir = fileName;
+                unsigned int pos = subdir.find_last_of('.');
+                if (pos != subdir.npos)
+                    subdir = subdir.substr(0, pos);
+                destPath.append(subdir);
                 destPath.append("/");
                 }
-            destPath.append(fileName);
-            destPath[destPath.size()-2] = 'm';
+            //Pick the output file name
+            if (outName.size() > 0)
+                {
+                destPath.append(outName);
+                }
+            else
+                {
+                destPath.append(fileName);
+                destPath[destPath.size()-2] = 'm';
+                }
+
             String fullDest = parent.resolve(destPath);
 
             if (!isNewerThan(fullSource, fullDest))
@@ -5490,8 +7036,19 @@ public:
 
     virtual bool parse(Element *elem)
         {
+        String s;
+        if (!parent.getAttribute(elem, "command", s))
+            return false;
+        if (s.size()>0)
+            command = s;
         if (!parent.getAttribute(elem, "todir", toDirName))
             return false;
+        if (!parent.getAttribute(elem, "out", outName))
+            return false;
+        if (!parent.getAttribute(elem, "owndir", s))
+            return false;
+        if (s.size()>0 && !getBool(s, owndir))
+            return false;
             
         std::vector<Element *> children = elem->getChildren();
         for (unsigned int i=0 ; i<children.size() ; i++)
@@ -5500,7 +7057,7 @@ public:
             String tagName = child->getName();
             if (tagName == "fileset")
                 {
-                if (!getFileSet(child, parent, fileSetDir, fileSet))
+                if (!parseFileSet(child, parent, fileSet))
                     return false;
                 }
             }
@@ -5509,15 +7066,155 @@ public:
 
 private:
 
-    String command;
-    String toDirName;
-    String fileSetDir;
-    std::vector<String> fileSet;
+    String  command;
+    String  toDirName;
+    String  outName;
+    FileSet fileSet;
+    bool    owndir;
 
 };
 
 
 
+/**
+ *  Perform a Package-Config query similar to pkg-config
+ */
+class TaskPkgConfig : public Task
+{
+public:
+
+    typedef enum
+        {
+        PKG_CONFIG_QUERY_CFLAGS,
+        PKG_CONFIG_QUERY_LIBS,
+        PKG_CONFIG_QUERY_ALL
+        } QueryTypes;
+
+    TaskPkgConfig(MakeBase &par) : Task(par)
+        {
+        type = TASK_PKG_CONFIG;
+        name = "pkg-config";
+        }
+
+    virtual ~TaskPkgConfig()
+        {}
+
+    virtual bool execute()
+        {
+        String path = parent.resolve(pkg_config_path);
+        PkgConfig pkgconfig;
+        pkgconfig.setPath(path);
+        pkgconfig.setPrefix(prefix);
+        if (!pkgconfig.query(pkgName))
+            {
+            error("<pkg-config> query failed for '%s", name.c_str());
+            return false;
+            }
+        String ret;
+        switch (query)
+            {
+            case PKG_CONFIG_QUERY_CFLAGS:
+                {
+                ret = pkgconfig.getCflags();
+                break;
+                }
+            case PKG_CONFIG_QUERY_LIBS:
+                {
+                ret = pkgconfig.getLibs();
+                break;
+                }
+            case PKG_CONFIG_QUERY_ALL:
+                {
+                ret = pkgconfig.getAll();
+                break;
+                }
+            default:
+                {
+                error("<pkg-config> unhandled query : %d", query);
+                return false;
+                }
+            
+            }
+        status("          : %s", ret.c_str());
+        parent.setProperty(propName, ret);
+        return true;
+        }
+
+    virtual bool parse(Element *elem)
+        {
+        String s;
+        //# NAME
+        if (!parent.getAttribute(elem, "name", s))
+            return false;
+        if (s.size()>0)
+           pkgName = s;
+        else
+            {
+            error("<pkg-config> requires 'name=\"package\"' attribute");
+            return false;
+            }
+
+        //# PROPERTY
+        if (!parent.getAttribute(elem, "property", s))
+            return false;
+        if (s.size()>0)
+           propName = s;
+        else
+            {
+            error("<pkg-config> requires 'property=\"name\"' attribute");
+            return false;
+            }
+        if (parent.hasProperty(propName))
+            {
+            error("<pkg-config> property '%s' is already defined",
+                          propName.c_str());
+            return false;
+            }
+        parent.setProperty(propName, "undefined");
+
+        //# PATH
+        if (!parent.getAttribute(elem, "path", s))
+            return false;
+        if (s.size()>0)
+           pkg_config_path = s;
+
+        //# PREFIX
+        if (!parent.getAttribute(elem, "prefix", s))
+            return false;
+        if (s.size()>0)
+           prefix = s;
+
+        //# QUERY
+        if (!parent.getAttribute(elem, "query", s))
+            return false;
+        if (s == "cflags")
+            query = PKG_CONFIG_QUERY_CFLAGS;
+        else if (s == "libs")
+            query = PKG_CONFIG_QUERY_LIBS;
+        else if (s == "both")
+            query = PKG_CONFIG_QUERY_ALL;
+        else
+            {
+            error("<pkg-config> requires 'query=\"type\"' attribute");
+            error("where type = cflags, libs, or both");
+            return false;
+            }
+        return true;
+        }
+
+private:
+
+    String pkgName;
+    String prefix;
+    String propName;
+    String pkg_config_path;
+    int query;
+
+};
+
+
+
+
 
 
 /**
@@ -5528,7 +7225,10 @@ class TaskRanlib : public Task
 public:
 
     TaskRanlib(MakeBase &par) : Task(par)
-        { type = TASK_RANLIB; name = "ranlib"; }
+        {
+        type = TASK_RANLIB; name = "ranlib";
+        command = "ranlib";
+        }
 
     virtual ~TaskRanlib()
         {}
@@ -5537,7 +7237,8 @@ public:
         {
         String fullName = parent.resolve(fileName);
         //trace("fullDir:%s", fullDir.c_str());
-        String cmd = "ranlib ";
+        String cmd = command;
+        cmd.append(" ");
         cmd.append(fullName);
         String outbuf, errbuf;
         if (!executeCommand(cmd, "", outbuf, errbuf))
@@ -5547,6 +7248,11 @@ public:
 
     virtual bool parse(Element *elem)
         {
+        String s;
+        if (!parent.getAttribute(elem, "command", s))
+            return false;
+        if (s.size()>0)
+           command = s;
         if (!parent.getAttribute(elem, "file", fileName))
             return false;
         if (fileName.size() == 0)
@@ -5560,6 +7266,211 @@ public:
 private:
 
     String fileName;
+    String command;
+};
+
+
+
+/**
+ * Run the "ar" command to archive .o's into a .a
+ */
+class TaskRC : public Task
+{
+public:
+
+    TaskRC(MakeBase &par) : Task(par)
+        {
+        type = TASK_RC; name = "rc";
+        command = "windres";
+        }
+
+    virtual ~TaskRC()
+        {}
+
+    virtual bool execute()
+        {
+        String fullFile = parent.resolve(fileName);
+        String fullOut  = parent.resolve(outName);
+        if (!isNewerThan(fullFile, fullOut))
+            return true;
+        String cmd = command;
+        cmd.append(" -o ");
+        cmd.append(fullOut);
+        cmd.append(" ");
+        cmd.append(flags);
+        cmd.append(" ");
+        cmd.append(fullFile);
+
+        String outString, errString;
+        if (!executeCommand(cmd.c_str(), "", outString, errString))
+            {
+            error("RC problem: %s", errString.c_str());
+            return false;
+            }
+        return true;
+        }
+
+    virtual bool parse(Element *elem)
+        {
+        if (!parent.getAttribute(elem, "command", command))
+            return false;
+        if (!parent.getAttribute(elem, "file", fileName))
+            return false;
+        if (!parent.getAttribute(elem, "out", outName))
+            return false;
+        std::vector<Element *> children = elem->getChildren();
+        for (unsigned int i=0 ; i<children.size() ; i++)
+            {
+            Element *child = children[i];
+            String tagName = child->getName();
+            if (tagName == "flags")
+                {
+                if (!parent.getValue(child, flags))
+                    return false;
+                }
+            }
+        return true;
+        }
+
+private:
+
+    String command;
+    String flags;
+    String fileName;
+    String outName;
+
+};
+
+
+
+/**
+ *  Collect .o's into a .so or DLL
+ */
+class TaskSharedLib : public Task
+{
+public:
+
+    TaskSharedLib(MakeBase &par) : Task(par)
+        {
+        type = TASK_SHAREDLIB; name = "dll";
+        command = "dllwrap";
+        }
+
+    virtual ~TaskSharedLib()
+        {}
+
+    virtual bool execute()
+        {
+        //trace("###########HERE %d", fileSet.size());
+        bool doit = false;
+        
+        String fullOut = parent.resolve(fileName);
+        //trace("ar fullout: %s", fullOut.c_str());
+        
+        if (!listFiles(parent, fileSet))
+            return false;
+        String fileSetDir = fileSet.getDirectory();
+
+        for (unsigned int i=0 ; i<fileSet.size() ; i++)
+            {
+            String fname;
+            if (fileSetDir.size()>0)
+                {
+                fname.append(fileSetDir);
+                fname.append("/");
+                }
+            fname.append(fileSet[i]);
+            String fullName = parent.resolve(fname);
+            //trace("ar : %s/%s", fullOut.c_str(), fullName.c_str());
+            if (isNewerThan(fullName, fullOut))
+                doit = true;
+            }
+        //trace("Needs it:%d", doit);
+        if (!doit)
+            {
+            return true;
+            }
+
+        String cmd = "dllwrap";
+        cmd.append(" -o ");
+        cmd.append(fullOut);
+        if (defFileName.size()>0)
+            {
+            cmd.append(" --def ");
+            cmd.append(defFileName);
+            cmd.append(" ");
+            }
+        if (impFileName.size()>0)
+            {
+            cmd.append(" --implib ");
+            cmd.append(impFileName);
+            cmd.append(" ");
+            }
+        for (unsigned int i=0 ; i<fileSet.size() ; i++)
+            {
+            String fname;
+            if (fileSetDir.size()>0)
+                {
+                fname.append(fileSetDir);
+                fname.append("/");
+                }
+            fname.append(fileSet[i]);
+            String fullName = parent.resolve(fname);
+
+            cmd.append(" ");
+            cmd.append(fullName);
+            }
+        cmd.append(" ");
+        cmd.append(libs);
+
+        String outString, errString;
+        if (!executeCommand(cmd.c_str(), "", outString, errString))
+            {
+            error("<sharedlib> problem: %s", errString.c_str());
+            return false;
+            }
+
+        return true;
+        }
+
+    virtual bool parse(Element *elem)
+        {
+        if (!parent.getAttribute(elem, "file", fileName))
+            return false;
+        if (!parent.getAttribute(elem, "import", impFileName))
+            return false;
+        if (!parent.getAttribute(elem, "def", defFileName))
+            return false;
+            
+        std::vector<Element *> children = elem->getChildren();
+        for (unsigned int i=0 ; i<children.size() ; i++)
+            {
+            Element *child = children[i];
+            String tagName = child->getName();
+            if (tagName == "fileset")
+                {
+                if (!parseFileSet(child, parent, fileSet))
+                    return false;
+                }
+            else if (tagName == "libs")
+                {
+                if (!parent.getValue(child, libs))
+                    return false;
+                libs = strip(libs);
+                }
+            }
+        return true;
+        }
+
+private:
+
+    String command;
+    String fileName;
+    String defFileName;
+    String impFileName;
+    FileSet fileSet;
+    String libs;
+
 };
 
 
@@ -5567,58 +7478,98 @@ private:
 /**
  * Run the "ar" command to archive .o's into a .a
  */
-class TaskRC : public Task
+class TaskStaticLib : public Task
 {
 public:
 
-    TaskRC(MakeBase &par) : Task(par)
+    TaskStaticLib(MakeBase &par) : Task(par)
         {
-               type = TASK_RC; name = "rc";
-               command = "windres -o";
-               }
+        type = TASK_STATICLIB; name = "staticlib";
+        command = "ar crv";
+        }
 
-    virtual ~TaskRC()
+    virtual ~TaskStaticLib()
         {}
 
     virtual bool execute()
         {
-        String fullFile = parent.resolve(fileName);
-        String fullOut  = parent.resolve(outName);
-        if (!isNewerThan(fullFile, fullOut))
+        //trace("###########HERE %d", fileSet.size());
+        bool doit = false;
+        
+        String fullOut = parent.resolve(fileName);
+        //trace("ar fullout: %s", fullOut.c_str());
+        
+        if (!listFiles(parent, fileSet))
+            return false;
+        String fileSetDir = fileSet.getDirectory();
+
+        for (unsigned int i=0 ; i<fileSet.size() ; i++)
+            {
+            String fname;
+            if (fileSetDir.size()>0)
+                {
+                fname.append(fileSetDir);
+                fname.append("/");
+                }
+            fname.append(fileSet[i]);
+            String fullName = parent.resolve(fname);
+            //trace("ar : %s/%s", fullOut.c_str(), fullName.c_str());
+            if (isNewerThan(fullName, fullOut))
+                doit = true;
+            }
+        //trace("Needs it:%d", doit);
+        if (!doit)
+            {
             return true;
+            }
+
         String cmd = command;
         cmd.append(" ");
         cmd.append(fullOut);
-        cmd.append(" ");
-        cmd.append(flags);
-        cmd.append(" ");
-        cmd.append(fullFile);
+        for (unsigned int i=0 ; i<fileSet.size() ; i++)
+            {
+            String fname;
+            if (fileSetDir.size()>0)
+                {
+                fname.append(fileSetDir);
+                fname.append("/");
+                }
+            fname.append(fileSet[i]);
+            String fullName = parent.resolve(fname);
+
+            cmd.append(" ");
+            cmd.append(fullName);
+            }
 
         String outString, errString;
         if (!executeCommand(cmd.c_str(), "", outString, errString))
             {
-            error("RC problem: %s", errString.c_str());
+            error("<staticlib> problem: %s", errString.c_str());
             return false;
             }
+
         return true;
         }
 
+
     virtual bool parse(Element *elem)
         {
-        if (!parent.getAttribute(elem, "command", command))
+        String s;
+        if (!parent.getAttribute(elem, "command", s))
             return false;
+        if (s.size()>0)
+            command = s;
         if (!parent.getAttribute(elem, "file", fileName))
             return false;
-        if (!parent.getAttribute(elem, "out", outName))
-            return false;
+            
         std::vector<Element *> children = elem->getChildren();
         for (unsigned int i=0 ; i<children.size() ; i++)
             {
             Element *child = children[i];
             String tagName = child->getName();
-            if (tagName == "flags")
+            if (tagName == "fileset")
                 {
-                if (!parent.getValue(child, flags))
+                if (!parseFileSet(child, parent, fileSet))
                     return false;
                 }
             }
@@ -5628,14 +7579,14 @@ public:
 private:
 
     String command;
-    String flags;
     String fileName;
-    String outName;
+    FileSet fileSet;
 
 };
 
 
 
+
 /**
  * Strip an executable
  */
@@ -5653,12 +7604,30 @@ public:
         {
         String fullName = parent.resolve(fileName);
         //trace("fullDir:%s", fullDir.c_str());
-        String cmd = "strip ";
-        cmd.append(fullName);
-
+        String cmd;
         String outbuf, errbuf;
+
+        if (symFileName.size()>0)
+            {
+            String symFullName = parent.resolve(symFileName);
+            cmd = "objcopy --only-keep-debug ";
+            cmd.append(getNativePath(fullName));
+            cmd.append(" ");
+            cmd.append(getNativePath(symFullName));
+            if (!executeCommand(cmd, "", outbuf, errbuf))
+                {
+                error("<strip> symbol file failed : %s", errbuf.c_str());
+                return false;
+                }
+            }
+            
+        cmd = "strip ";
+        cmd.append(getNativePath(fullName));
         if (!executeCommand(cmd, "", outbuf, errbuf))
+            {
+            error("<strip> failed : %s", errbuf.c_str());
             return false;
+            }
         return true;
         }
 
@@ -5666,9 +7635,11 @@ public:
         {
         if (!parent.getAttribute(elem, "file", fileName))
             return false;
+        if (!parent.getAttribute(elem, "symfile", symFileName))
+            return false;
         if (fileName.size() == 0)
             {
-            error("<strip> requires 'file=\"fileNname\"' attribute");
+            error("<strip> requires 'file=\"fileName\"' attribute");
             return false;
             }
         return true;
@@ -5677,6 +7648,63 @@ public:
 private:
 
     String fileName;
+    String symFileName;
+};
+
+
+/**
+ *
+ */
+class TaskTouch : public Task
+{
+public:
+
+    TaskTouch(MakeBase &par) : Task(par)
+        { type = TASK_TOUCH; name = "touch"; }
+
+    virtual ~TaskTouch()
+        {}
+
+    virtual bool execute()
+        {
+        String fullName = parent.resolve(fileName);
+        String nativeFile = getNativePath(fullName);
+        if (!isRegularFile(fullName) && !isDirectory(fullName))
+            {            
+            // S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH
+            int ret = creat(nativeFile.c_str(), 0666);
+            if (ret != 0) 
+                {
+                error("<touch> could not create '%s' : %s",
+                    nativeFile.c_str(), strerror(ret));
+                return false;
+                }
+            return true;
+            }
+        int ret = utime(nativeFile.c_str(), (struct utimbuf *)0);
+        if (ret != 0)
+            {
+            error("<touch> could not update the modification time for '%s' : %s",
+                nativeFile.c_str(), strerror(ret));
+            return false;
+            }
+        return true;
+        }
+
+    virtual bool parse(Element *elem)
+        {
+        //trace("touch parse");
+        if (!parent.getAttribute(elem, "file", fileName))
+            return false;
+        if (fileName.size() == 0)
+            {
+            error("<touch> requires 'file=\"fileName\"' attribute");
+            return false;
+            }
+        return true;
+        }
+
+    String fileName;
 };
 
 
@@ -5700,7 +7728,7 @@ public:
 
     virtual bool parse(Element *elem)
         {
-        trace("tstamp parse");
+        //trace("tstamp parse");
         return true;
         }
 };
@@ -5710,14 +7738,12 @@ public:
 /**
  *
  */
-Task *Task::createTask(Element *elem)
+Task *Task::createTask(Element *elem, int lineNr)
 {
     String tagName = elem->getName();
     //trace("task:%s", tagName.c_str());
     Task *task = NULL;
-    if (tagName == "ar")
-        task = new TaskAr(parent);
-    else if (tagName == "cc")
+    if (tagName == "cc")
         task = new TaskCC(parent);
     else if (tagName == "copy")
         task = new TaskCopy(parent);
@@ -5729,16 +7755,26 @@ Task *Task::createTask(Element *elem)
         task = new TaskJavac(parent);
     else if (tagName == "link")
         task = new TaskLink(parent);
+    else if (tagName == "makefile")
+        task = new TaskMakeFile(parent);
     else if (tagName == "mkdir")
         task = new TaskMkDir(parent);
     else if (tagName == "msgfmt")
         task = new TaskMsgFmt(parent);
+    else if (tagName == "pkg-config")
+        task = new TaskPkgConfig(parent);
     else if (tagName == "ranlib")
         task = new TaskRanlib(parent);
     else if (tagName == "rc")
         task = new TaskRC(parent);
+    else if (tagName == "sharedlib")
+        task = new TaskSharedLib(parent);
+    else if (tagName == "staticlib")
+        task = new TaskStaticLib(parent);
     else if (tagName == "strip")
         task = new TaskStrip(parent);
+    else if (tagName == "touch")
+        task = new TaskTouch(parent);
     else if (tagName == "tstamp")
         task = new TaskTstamp(parent);
     else
@@ -5747,6 +7783,8 @@ Task *Task::createTask(Element *elem)
         return NULL;
         }
 
+    task->setLine(lineNr);
+
     if (!task->parse(elem))
         {
         delete task;
@@ -5970,12 +8008,24 @@ public:
     /**
      *
      */
-    bool run();
+    virtual String version()
+        { return BUILDTOOL_VERSION; }
+
+    /**
+     * Overload a <property>
+     */
+    virtual bool specifyProperty(const String &name,
+                                 const String &value);
+
+    /**
+     *
+     */
+    virtual bool run();
 
     /**
      *
      */
-    bool run(const String &target);
+    virtual bool run(const String &target);
 
 
 
@@ -6006,7 +8056,7 @@ private:
      *
      */
     bool executeTarget(Target &target,
-                std::set<String> &targetsCompleted);
+             std::set<String> &targetsCompleted);
 
 
     /**
@@ -6024,18 +8074,13 @@ private:
      *
      */
     bool parsePropertyFile(const String &fileName,
-                              const String &prefix);
+                           const String &prefix);
 
     /**
      *
      */
     bool parseProperty(Element *elem);
 
-    /**
-     *
-     */
-    bool parseTask(Task &task, Element *elem);
-
     /**
      *
      */
@@ -6070,7 +8115,8 @@ private:
     std::map<String, Target> targets;
 
     std::vector<Task *> allTasks;
-
+    
+    std::map<String, String> specifiedProperties;
 
 };
 
@@ -6184,7 +8230,8 @@ bool Make::executeTarget(Target &target,
             }
         }
 
-    status("## Target : %s", name.c_str());
+    status("## Target : %s : %s", name.c_str(),
+            target.getDescription().c_str());
 
     //Now let's do the tasks
     std::vector<Task *> &tasks = target.getTasks();
@@ -6229,11 +8276,11 @@ bool Make::execute()
         }
 
     std::map<String, Target>::iterator iter =
-                  targets.find(currentTarget);
+               targets.find(currentTarget);
     if (iter == targets.end())
         {
         error("Initial target '%s' not found",
-                        currentTarget.c_str());
+                 currentTarget.c_str());
         return false;
         }
         
@@ -6352,54 +8399,64 @@ bool Make::parsePropertyFile(const String &fileName,
         if (p2 <= p)
             {
             error("property file %s, line %d: expected keyword",
-                               fileName.c_str(), linenr);
-                       return false;
-                       }
-               if (prefix.size() > 0)
-                   {
-                   key.insert(0, prefix);
-                   }
+                    fileName.c_str(), linenr);
+            return false;
+            }
+        if (prefix.size() > 0)
+            {
+            key.insert(0, prefix);
+            }
 
         //skip whitespace
-               for (p=p2 ; p<len ; p++)
-                   if (!isspace(s[p]))
-                       break;
+        for (p=p2 ; p<len ; p++)
+            if (!isspace(s[p]))
+                break;
 
         if (p>=len || s[p]!='=')
             {
             error("property file %s, line %d: expected '='",
-                               fileName.c_str(), linenr);
+                    fileName.c_str(), linenr);
             return false;
             }
         p++;
 
         //skip whitespace
-               for ( ; p<len ; p++)
-                   if (!isspace(s[p]))
-                       break;
+        for ( ; p<len ; p++)
+            if (!isspace(s[p]))
+                break;
 
         /* This way expects a word after the =
-               p2 = getword(p, s, val);
+        p2 = getword(p, s, val);
         if (p2 <= p)
             {
             error("property file %s, line %d: expected value",
-                               fileName.c_str(), linenr);
-                       return false;
-                       }
-               */
+                    fileName.c_str(), linenr);
+            return false;
+            }
+        */
         // This way gets the rest of the line after the =
-               if (p>=len)
+        if (p>=len)
             {
             error("property file %s, line %d: expected value",
-                               fileName.c_str(), linenr);
-                       return false;
-                       }
+                    fileName.c_str(), linenr);
+            return false;
+            }
         val = s.substr(p);
-               if (key.size()==0 || val.size()==0)
-                   continue;
+        if (key.size()==0)
+            continue;
+        //allow property to be set, even if val=""
 
         //trace("key:'%s' val:'%s'", key.c_str(), val.c_str());
-           properties[key] = val;
+        //See if we wanted to overload this property
+        std::map<String, String>::iterator iter =
+            specifiedProperties.find(key);
+        if (iter!=specifiedProperties.end())
+            {
+            val = iter->second;
+            status("overloading property '%s' = '%s'",
+                   key.c_str(), val.c_str());
+            }
+        properties[key] = val;
         }
     fclose(f);
     return true;
@@ -6422,27 +8479,35 @@ bool Make::parseProperty(Element *elem)
         if (attrName == "name")
             {
             String val;
-                       if (!getAttribute(elem, "value", val))
-                           return false;
+            if (!getAttribute(elem, "value", val))
+                return false;
             if (val.size() > 0)
                 {
                 properties[attrVal] = val;
-                continue;
                 }
-            if (!getAttribute(elem, "location", val))
-                return false;
-            if (val.size() > 0)
+            else
                 {
-                //TODO:  process a path relative to build.xml
+                if (!getAttribute(elem, "location", val))
+                    return false;
+                //let the property exist, even if not defined
+                properties[attrVal] = val;
+                }
+            //See if we wanted to overload this property
+            std::map<String, String>::iterator iter =
+                specifiedProperties.find(attrVal);
+            if (iter != specifiedProperties.end())
+                {
+                val = iter->second;
+                status("overloading property '%s' = '%s'",
+                    attrVal.c_str(), val.c_str());
                 properties[attrVal] = val;
-                continue;
                 }
             }
         else if (attrName == "file")
             {
             String prefix;
-                       if (!getAttribute(elem, "prefix", prefix))
-                           return false;
+            if (!getAttribute(elem, "prefix", prefix))
+                return false;
             if (prefix.size() > 0)
                 {
                 if (prefix[prefix.size()-1] != '.')
@@ -6473,16 +8538,20 @@ bool Make::parseProperty(Element *elem)
  */
 bool Make::parseFile()
 {
-    status("######## PARSE");
+    status("######## PARSE : %s", uri.getPath().c_str());
+
+    setLine(0);
 
     Parser parser;
     Element *root = parser.parseFile(uri.getNativePath());
     if (!root)
         {
         error("Could not open %s for reading",
-                     uri.getNativePath().c_str());
+              uri.getNativePath().c_str());
         return false;
         }
+    
+    setLine(root->getLine());
 
     if (root->getChildren().size()==0 ||
         root->getChildren()[0]->getName()!="project")
@@ -6509,6 +8578,7 @@ bool Make::parseFile()
     for (unsigned int i=0 ; i<children.size() ; i++)
         {
         Element *elem = children[i];
+        setLine(elem->getLine());
         String tagName = elem->getName();
 
         //########## DESCRIPTION
@@ -6543,7 +8613,7 @@ bool Make::parseFile()
                 {
                 Element *telem = telems[i];
                 Task breeder(*this);
-                Task *task = breeder.createTask(telem);
+                Task *task = breeder.createTask(telem, telem->getLine());
                 if (!task)
                     return false;
                 allTasks.push_back(task);
@@ -6565,6 +8635,12 @@ bool Make::parseFile()
             //more work than targets[tname]=target, but avoids default allocator
             targets.insert(std::make_pair<String, Target>(tname, target));
             }
+        //######### none of the above
+        else
+            {
+            error("unknown toplevel tag: <%s>", tagName.c_str());
+            return false;
+            }
 
         }
 
@@ -6586,6 +8662,22 @@ bool Make::parseFile()
 }
 
 
+/**
+ * Overload a <property>
+ */
+bool Make::specifyProperty(const String &name, const String &value)
+{
+    if (specifiedProperties.find(name) != specifiedProperties.end())
+        {
+        error("Property %s already specified", name.c_str());
+        return false;
+        }
+    specifiedProperties[name] = value;
+    return true;
+}
+
+
+
 /**
  *
  */
@@ -6593,27 +8685,62 @@ bool Make::run()
 {
     if (!parseFile())
         return false;
+        
     if (!execute())
         return false;
+
     return true;
 }
 
 
+
+
+/**
+ * Get a formatted MM:SS.sss time elapsed string
+ */ 
+static String
+timeDiffString(struct timeval &x, struct timeval &y)
+{
+    long microsX  = x.tv_usec;
+    long secondsX = x.tv_sec;
+    long microsY  = y.tv_usec;
+    long secondsY = y.tv_sec;
+    if (microsX < microsY)
+        {
+        microsX += 1000000;
+        secondsX -= 1;
+        }
+
+    int seconds = (int)(secondsX - secondsY);
+    int millis  = (int)((microsX - microsY)/1000);
+
+    int minutes = seconds/60;
+    seconds -= minutes*60;
+    char buf[80];
+    snprintf(buf, 79, "%dm %d.%03ds", minutes, seconds, millis);
+    String ret = buf;
+    return ret;
+    
+}
+
 /**
  *
  */
 bool Make::run(const String &target)
 {
-    status("##################################");
-    status("#   BuildTool");
-    status("#   version 0.2");
-    status("##################################");
+    status("####################################################");
+    status("#   %s", version().c_str());
+    status("####################################################");
+    struct timeval timeStart, timeEnd;
+    ::gettimeofday(&timeStart, NULL);
     specifiedTarget = target;
     if (!run())
         return false;
-    status("##################################");
-    status("#   BuildTool Completed");
-    status("##################################");
+    ::gettimeofday(&timeEnd, NULL);
+    String timeStr = timeDiffString(timeEnd, timeStart);
+    status("####################################################");
+    status("#   BuildTool Completed : %s", timeStr.c_str());
+    status("####################################################");
     return true;
 }
 
@@ -6628,10 +8755,12 @@ bool Make::run(const String &target)
 //# M A I N
 //########################################################################
 
+typedef buildtool::String String;
+
 /**
  *  Format an error message in printf() style
  */
-static void error(char *fmt, ...)
+static void error(const char *fmt, ...)
 {
     va_list ap;
     va_start(ap, fmt);
@@ -6642,12 +8771,39 @@ static void error(char *fmt, ...)
 }
 
 
+static bool parseProperty(const String &s, String &name, String &val)
+{
+    int len = s.size();
+    int i;
+    for (i=0 ; i<len ; i++)
+        {
+        char ch = s[i];
+        if (ch == '=')
+            break;
+        name.push_back(ch);
+        }
+    if (i>=len || s[i]!='=')
+        {
+        error("property requires -Dname=value");
+        return false;
+        }
+    i++;
+    for ( ; i<len ; i++)
+        {
+        char ch = s[i];
+        val.push_back(ch);
+        }
+    return true;
+}
+
+
 /**
  * Compare a buffer with a key, for the length of the key
  */
-static bool sequ(const buildtool::String &buf, char *key)
+static bool sequ(const String &buf, const char *key)
 {
-    for (int i=0 ; key[i] ; i++)
+    int len = buf.size();
+    for (int i=0 ; key[i] && i<len ; i++)
         {
         if (key[i] != buf[i])
             return false;
@@ -6655,6 +8811,21 @@ static bool sequ(const buildtool::String &buf, char *key)
     return true;
 }
 
+static void usage(int argc, char **argv)
+{
+    printf("usage:\n");
+    printf("   %s [options] [target]\n", argv[0]);
+    printf("Options:\n");
+    printf("  -help, -h              print this message\n");
+    printf("  -version               print the version information and exit\n");
+    printf("  -file <file>           use given buildfile\n");
+    printf("  -f <file>                 ''\n");
+    printf("  -D<property>=<value>   use value for given property\n");
+}
+
+
+
+
 /**
  * Parse the command-line args, get our options,
  * and run this thing
@@ -6667,18 +8838,47 @@ static bool parseOptions(int argc, char **argv)
         return false;
         }
 
-    buildtool::String buildFile;
-    buildtool::String target;
+    buildtool::Make make;
+
+    String target;
 
     //char *progName = argv[0];
     for (int i=1 ; i<argc ; i++)
         {
-        buildtool::String arg = argv[i];
-        if (sequ(arg, "--"))
+        String arg = argv[i];
+        if (arg.size()>1 && arg[0]=='-')
             {
-            if (sequ(arg, "--file=") && arg.size()>7)
+            if (arg == "-h" || arg == "-help")
+                {
+                usage(argc,argv);
+                return true;
+                }
+            else if (arg == "-version")
                 {
-                buildFile = arg.substr(7, arg.size()-7);
+                printf("%s", make.version().c_str());
+                return true;
+                }
+            else if (arg == "-f" || arg == "-file")
+                {
+                if (i>=argc)
+                   {
+                   usage(argc, argv);
+                   return false;
+                   }
+                i++; //eat option
+                make.setURI(argv[i]);
+                }
+            else if (arg.size()>2 && sequ(arg, "-D"))
+                {
+                String s = arg.substr(2, s.size());
+                String name, value;
+                if (!parseProperty(s, name, value))
+                   {
+                   usage(argc, argv);
+                   return false;
+                   }
+                if (!make.specifyProperty(name, value))
+                    return false;
                 }
             else
                 {
@@ -6686,33 +8886,19 @@ static bool parseOptions(int argc, char **argv)
                 return false;
                 }
             }
-        else if (sequ(arg, "-"))
+        else
             {
-            for (unsigned int p=1 ; p<arg.size() ; p++)
+            if (target.size()>0)
                 {
-                int ch = arg[p];
-                if (0)//put options here
-                    {
-                    }
-                else
-                    {
-                    error("Unknown option '%c'", ch);
-                    return false;
-                    }
+                error("only one initial target");
+                usage(argc, argv);
+                return false;
                 }
-            }
-        else
-            {
             target = arg;
             }
         }
 
     //We have the options.  Now execute them
-    buildtool::Make make;
-    if (buildFile.size() > 0)
-        {
-        make.setURI(buildFile);
-        }
     if (!make.run(target))
         return false;
 
@@ -6748,9 +8934,9 @@ static bool depTest()
     deptool.setSourceDirectory("/dev/ink/inkscape/src");
     if (!deptool.generateDependencies("build.dep"))
         return false;
-    std::vector<buildtool::DepRec> res =
-              deptool.loadDepFile("build.dep");
-       if (res.size() == 0)
+    std::vector<buildtool::FileRec> res =
+           deptool.loadDepFile("build.dep");
+    if (res.size() == 0)
         return false;
     return true;
 }
@@ -6759,7 +8945,7 @@ static bool popenTest()
 {
     buildtool::Make make;
     buildtool::String out, err;
-       bool ret = make.executeCommand("gcc xx.cpp", "", out, err);
+    bool ret = make.executeCommand("gcc xx.cpp", "", out, err);
     printf("Popen test:%d '%s' '%s'\n", ret, out.c_str(), err.c_str());
     return true;
 }