Index: tool/lemon.c
==================================================================
--- tool/lemon.c
+++ tool/lemon.c
@@ -1541,10 +1541,23 @@
   if( user_templatename==0 ){
     memory_error();
   }
   lemon_strcpy(user_templatename, z);
 }
+
+static char *output_directory = NULL;
+static void handle_d_option(char *z){
+  if ( output_directory!=0 ){
+    fprintf(stderr,"output directory specified more than once\n");
+    exit(1);
+  }
+  output_directory = (char *) malloc( lemonStrlen(z)+1 );
+  if ( output_directory==0 ){
+    memory_error();
+  }
+  lemon_strcpy(output_directory, z);
+}
 
 /* Merge together to lists of rules ordered by rule.iRule */
 static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
   struct rule *pFirst = 0;
   struct rule **ppPrev = &pFirst;
@@ -1617,10 +1630,11 @@
   static int nolinenosflag = 0;
   static int noResort = 0;
   static struct s_options options[] = {
     {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
     {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
+    {OPT_FSTR, "d", (char*)handle_d_option, "Specify output directtory."},
     {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
     {OPT_FSTR, "f", 0, "Ignored.  (Placeholder for -f compiler options.)"},
     {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
     {OPT_FSTR, "I", 0, "Ignored.  (Placeholder for '-I' compiler options.)"},
     {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
@@ -3024,16 +3038,31 @@
 PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
 {
   char *name;
   char *cp;
 
-  name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
+  name = (char*)malloc(lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5
+                       + (output_directory ? lemonStrlen(output_directory)+1 : 0));
   if( name==0 ){
     fprintf(stderr,"Can't allocate space for a filename.\n");
     exit(1);
   }
-  lemon_strcpy(name,lemp->filename);
+  *name = '\0';
+  if ( output_directory ){
+      lemon_strcat(name, output_directory);
+#ifdef __WIN32__
+      lemon_strcat(name, "\\");
+      cp = strrchr(lemp->filename,'\\');
+#else
+      lemon_strcat(name, "/");
+      cp = strrchr(lemp->filename,'/');
+#endif
+  } else {
+      cp = NULL;
+  }
+
+  lemon_strcat(name, cp ? cp+1 : lemp->filename);
   cp = strrchr(name,'.');
   if( cp ) *cp = 0;
   lemon_strcat(name,suffix);
   return name;
 }

