Correctly assign %propmt%.
[reactos.git] / reactos / subsys / system / cmd / cmd.c
index 7fc6c66..ec01e36 100644 (file)
@@ -1,5 +1,4 @@
-/* $Id: cmd.c,v 1.16 2004/06/21 18:57:22 weiden Exp $
- *
+/*
  *  CMD.C - command-line interface.
  *
  *
@@ -37,7 +36,7 @@
  *        message!
  *
  *        changed the format to call internal commands (again) so that if
- *        they want to split their commands, they can do it themselves 
+ *        they want to split their commands, they can do it themselves
  *        (none of the internal functions so far need that much power, anyway)
  *
  *    27 Aug 1996 (Tim Norman)
  *       Make MakeSureDirectoryPathExistsEx unicode safe.
  *
  *    28-Mai-2004 (Hartmut Birr)
- *       Removed MakeSureDirectoryPathExistsEx. 
+ *       Removed MakeSureDirectoryPathExistsEx.
  *       Use the current directory if GetTempPath fails.
+ *
+ *    12-Jul-2004 (Jens Collin <jens.collin@lakhei.com>)
+ *       Added ShellExecute call when all else fails to be able to "launch" any file.
+ *
+ *    02-Apr-2005 (Magnus Olsen <magnus@greatlord.com>)
+ *        Remove all hardcode string to En.rc
+ *
+ *    06-May-2005 (Klemens Friedl <frik85@gmail.com>)
+ *        Add 'help' command (list all commands plus description)
+ *
+ *    06-jul-2005 (Magnus Olsen <magnus@greatlord.com>)
+ *        translate '%errorlevel%' to the internal value.
+ *        Add proper memmory alloc ProcessInput, the error 
+ *        handling for memmory handling need to be improve
  */
 
-#include "config.h"
-
-#include <windows.h>
-#include <tchar.h>
-#include <string.h>
-#include <stdlib.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <winnt.h>
-#include <winternl.h>
+#include <precomp.h>
+#include "resource.h"
 
 #ifndef NT_SUCCESS
 #define NT_SUCCESS(StatCode)  ((NTSTATUS)(StatCode) >= 0)
 #endif
 
-#include "cmd.h"
-#include "batch.h"
-
 typedef NTSTATUS (STDCALL *NtQueryInformationProcessProc)(HANDLE, PROCESSINFOCLASS,
                                                           PVOID, ULONG, PULONG);
 typedef NTSTATUS (STDCALL *NtReadVirtualMemoryProc)(HANDLE, PVOID, PVOID, ULONG, PULONG);
@@ -161,10 +163,11 @@ OSVERSIONINFO osvi;
 HANDLE hIn;
 HANDLE hOut;
 HANDLE hConsole;
+HANDLE CMD_ModuleHandle;
+HMODULE NtDllModule;
 
-static NtQueryInformationProcessProc NtQueryInformationProcessPtr;
-static NtReadVirtualMemoryProc       NtReadVirtualMemoryPtr;
-static BOOL NtDllChecked = FALSE;
+static NtQueryInformationProcessProc NtQueryInformationProcessPtr = NULL;
+static NtReadVirtualMemoryProc       NtReadVirtualMemoryPtr = NULL;
 
 #ifdef INCLUDE_CMD_COLOR
 WORD wColor;              /* current color */
@@ -190,28 +193,6 @@ static BOOL IsConsoleProcess(HANDLE Process)
        PROCESS_BASIC_INFORMATION Info;
        PEB ProcessPeb;
        ULONG BytesRead;
-       HMODULE NtDllModule;
-
-       /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
-           build process. So don't link implicitly against ntdll.dll, load it
-           dynamically instead */
-       if (! NtDllChecked)
-       {
-               NtDllChecked = TRUE;
-               NtDllModule = LoadLibrary(_T("ntdll.dll"));
-               if (NULL == NtDllModule)
-               {
-                       /* Probably non-WinNT system. Just wait for the commands
-                           to finish. */
-                       NtQueryInformationProcessPtr = NULL;
-                       NtReadVirtualMemoryPtr = NULL;
-                       return TRUE;
-               }
-               NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)
-                                               GetProcAddress(NtDllModule, "NtQueryInformationProcess");
-               NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)
-                                        GetProcAddress(NtDllModule, "NtReadVirtualMemory");
-       }
 
        if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
        {
@@ -241,17 +222,83 @@ static BOOL IsConsoleProcess(HANDLE Process)
 }
 
 
+
+#ifdef _UNICODE
+#define SHELLEXECUTETEXT       "ShellExecuteW"
+#else
+#define SHELLEXECUTETEXT       "ShellExecuteA"
+#endif
+
+typedef HINSTANCE (WINAPI *MYEX)(
+    HWND hwnd,
+    LPCTSTR lpOperation,
+    LPCTSTR lpFile,
+    LPCTSTR lpParameters,
+    LPCTSTR lpDirectory,
+    INT nShowCmd
+);
+
+
+
+static BOOL RunFile(LPTSTR filename)
+{
+       HMODULE         hShell32;
+       MYEX            hShExt;
+       HINSTANCE       ret;
+
+#ifdef _DEBUG
+               DebugPrintf (_T("RunFile(%s)\n"), filename);
+#endif
+       hShell32 = LoadLibrary(_T("SHELL32.DLL"));
+       if (!hShell32)
+       {
+#ifdef _DEBUG
+               DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
+#endif
+               return FALSE;
+       }
+
+       hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
+       if (!hShExt)
+       {
+#ifdef _DEBUG
+               DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
+#endif
+               FreeLibrary(hShell32);
+               return FALSE;
+       }
+
+#ifdef _DEBUG
+       DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt);
+#endif
+
+       ret = (hShExt)(NULL, _T("open"), filename, NULL, NULL, SW_SHOWNORMAL);
+
+#ifdef _DEBUG
+       DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD)ret);
+#endif
+
+       FreeLibrary(hShell32);
+       return (((DWORD)ret) > 32);
+}
+
+
+
 /*
  * This command (in first) was not found in the command table
  *
- * first - first word on command line
- * rest  - rest of command line
+ * Full  - whole command line
+ * First - first word on command line
+ * Rest  - rest of command line
  */
 
 static VOID
-Execute (LPTSTR full, LPTSTR first, LPTSTR rest)
+Execute (LPTSTR Full, LPTSTR First, LPTSTR Rest)
 {
        TCHAR szFullName[MAX_PATH];
+       TCHAR first[CMDLINE_LENGTH];
+       TCHAR rest[CMDLINE_LENGTH];
+       TCHAR full[CMDLINE_LENGTH];
 #ifndef __REACTOS__
        TCHAR szWindowTitle[MAX_PATH];
 #endif
@@ -261,9 +308,54 @@ Execute (LPTSTR full, LPTSTR first, LPTSTR rest)
        DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first, rest);
 #endif
 
+       /* Though it was already parsed once, we have a different set of rules
+          for parsing before we pass to CreateProccess */
+       if(!_tcschr(Full,_T('\"')))
+       {
+               _tcscpy(first,First);
+               _tcscpy(rest,Rest);
+               _tcscpy(full,Full);
+       }
+       else
+       {
+               INT i = 0;              
+               BOOL bInside = FALSE;
+               rest[0] = _T('\0');
+               full[0] = _T('\0');
+               first[0] = _T('\0');
+               _tcscpy(first,Full);
+               /* find the end of the command and start of the args */
+               for(i = 0; i < _tcslen(first); i++)
+               {
+                       if(!_tcsncmp(&first[i], _T("\""), 1))
+                               bInside = !bInside;
+                       if(!_tcsncmp(&first[i], _T(" "), 1) && !bInside)
+                       {
+                               _tcscpy(rest,&first[i]);
+                               first[i] = _T('\0');
+                               break;
+                       }
+
+               }
+               i = 0;
+               /* remove any slashes */
+               while(i < _tcslen(first))
+               {
+                       if(first[i] == _T('\"'))
+                               memmove(&first[i],&first[i + 1], _tcslen(&first[i]) * sizeof(TCHAR));
+                       else
+                               i++;
+               }
+               /* Drop quotes around it just in case there is a space */
+               _tcscpy(full,_T("\""));
+               _tcscat(full,first);
+               _tcscat(full,_T("\" "));
+               _tcscat(full,rest);
+       }
+
        /* check for a drive change */
        if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
-       {       
+       {
                BOOL working = TRUE;
                if (!SetCurrentDirectory(first))
                /* Guess they changed disc or something, handle that gracefully and get to root */
@@ -276,7 +368,7 @@ Execute (LPTSTR full, LPTSTR first, LPTSTR rest)
                        working = SetCurrentDirectory(str);
                }
 
-               if (!working) ConErrPuts (INVALIDDRIVE);
+               if (!working) ConErrResPuts (STRING_FREE_ERROR1);
 
                return;
        }
@@ -353,14 +445,26 @@ Execute (LPTSTR full, LPTSTR first, LPTSTR rest)
                }
                else
                {
-                       ErrorMessage (GetLastError (),
-                                     _T("Error executing CreateProcess()!!\n"));
+#ifdef _DEBUG
+                       DebugPrintf (_T("[ShellExecute: %s]\n"), full);
+#endif
+                       // See if we can run this with ShellExecute() ie myfile.xls
+                       if (!RunFile(full))
+                       {
+#ifdef _DEBUG
+                               DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full);
+#endif
+                               error_bad_command ();
+                       }
                }
                // restore console mode
                SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
                                ENABLE_PROCESSED_INPUT );
        }
 
+       /* Get code page if it has been change */
+       InputCodePage= GetConsoleCP();
+    OutputCodePage = GetConsoleOutputCP();
 #ifndef __REACTOS__
        SetConsoleTitle (szWindowTitle);
 #endif
@@ -420,7 +524,7 @@ DoCommand (LPTSTR line)
 
                /* Terminate first word */
                *cp = _T('\0');
-               
+
                /* commands are limited to MAX_PATH */
                if(_tcslen(com) > MAX_PATH)
                {
@@ -484,6 +588,7 @@ DoCommand (LPTSTR line)
 
 VOID ParseCommandLine (LPTSTR cmd)
 {
+       TCHAR szMsg[RC_STRING_MAX_SIZE];
        TCHAR cmdline[CMDLINE_LENGTH];
        LPTSTR s;
 #ifdef FEATURE_REDIRECTION
@@ -498,7 +603,7 @@ VOID ParseCommandLine (LPTSTR cmd)
        INT  nRedirFlags = 0;
        INT  Length;
        UINT Attributes;
-
+       BOOL bNewBatch = TRUE;
        HANDLE hOldConIn;
        HANDLE hOldConOut;
        HANDLE hOldConErr;
@@ -551,6 +656,20 @@ VOID ParseCommandLine (LPTSTR cmd)
                ;
        _tcscpy (err, t);
 
+       if(bc && !_tcslen (in) && _tcslen (bc->In))
+               _tcscpy(in, bc->In);
+       if(bc && !out[0] && _tcslen(bc->Out))
+       {
+               nRedirFlags |= OUTPUT_APPEND;
+               _tcscpy(out, bc->Out);
+       }
+       if(bc && !_tcslen (err) && _tcslen (bc->Err))
+       {
+               nRedirFlags |= ERROR_APPEND;
+               _tcscpy(err, bc->Err);
+       }
+               
+
        /* Set up the initial conditions ... */
        /* preserve STDIN, STDOUT and STDERR handles */
        hOldConIn  = GetStdHandle (STD_INPUT_HANDLE);
@@ -563,17 +682,23 @@ VOID ParseCommandLine (LPTSTR cmd)
                HANDLE hFile;
                SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
 
+    /* we need make sure the LastError msg is zero before calling CreateFile */
+               SetLastError(0); 
+
+    /* Set up pipe for the standard input handler */
                hFile = CreateFile (in, GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
                                    FILE_ATTRIBUTE_NORMAL, NULL);
                if (hFile == INVALID_HANDLE_VALUE)
                {
-                       ConErrPrintf (_T("Can't redirect input from file %s\n"), in);
+                       LoadString(CMD_ModuleHandle, STRING_CMD_ERROR1, szMsg, RC_STRING_MAX_SIZE);
+                       ConErrPrintf(szMsg, in);
                        return;
                }
 
                if (!SetStdHandle (STD_INPUT_HANDLE, hFile))
-               {
-                       ConErrPrintf (_T("Can't redirect input from file %s\n"), in);
+               {      
+                       LoadString(CMD_ModuleHandle, STRING_CMD_ERROR1, szMsg, RC_STRING_MAX_SIZE);
+                       ConErrPrintf(szMsg, in);
                        return;
                }
 #ifdef _DEBUG
@@ -588,19 +713,24 @@ VOID ParseCommandLine (LPTSTR cmd)
        while (num-- > 1)
        {
                SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
-
-               /* Create unique temporary file name */
+    
+    /* Create unique temporary file name */
                GetTempFileName (szTempPath, _T("CMD"), 0, szFileName[1]);
-      
+
+    /* we need make sure the LastError msg is zero before calling CreateFile */
+                SetLastError(0); 
+
                /* Set current stdout to temporary file */
                hFile[1] = CreateFile (szFileName[1], GENERIC_WRITE, 0, &sa,
                                       TRUNCATE_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
-                   
-      if (hFile[1] == INVALID_HANDLE_VALUE){
-         ConErrPrintf (_T("Error creating temporary file for pipe data\n"));
-         return;
-      }
-                   
+               
+    if (hFile[1] == INVALID_HANDLE_VALUE)
+               {            
+                       LoadString(CMD_ModuleHandle, STRING_CMD_ERROR2, szMsg, RC_STRING_MAX_SIZE);
+                       ConErrPrintf(szMsg);
+                       return;
+               }
+
                SetStdHandle (STD_OUTPUT_HANDLE, hFile[1]);
 
                DoCommand (s);
@@ -628,6 +758,9 @@ VOID ParseCommandLine (LPTSTR cmd)
                _tcscpy (szFileName[0], szFileName[1]);
                *szFileName[1] = _T('\0');
 
+    /* we need make sure the LastError msg is zero before calling CreateFile */
+               SetLastError(0); 
+
                /* open new stdin file */
                hFile[0] = CreateFile (szFileName[0], GENERIC_READ, 0, &sa,
                                       OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
@@ -643,19 +776,43 @@ VOID ParseCommandLine (LPTSTR cmd)
                /* Final output to here */
                HANDLE hFile;
                SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
+               
+    /* we need make sure the LastError msg is zero before calling CreateFile */
+               SetLastError(0); 
 
-               hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_READ, &sa,
+    hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
                                    (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
-                                   FILE_ATTRIBUTE_NORMAL, NULL);
-               if (hFile == INVALID_HANDLE_VALUE)
+                                   FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
+               
+    if (hFile == INVALID_HANDLE_VALUE)
                {
-                       ConErrPrintf (_T("Can't redirect to file %s\n"), out);
-                       return;
+      INT size = _tcslen(out)-1;
+      
+      if (out[size] != _T(':'))
+      {
+                          LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
+                          ConErrPrintf(szMsg, out);
+                          return;
+      }
+      
+      out[size]=_T('\0');
+      hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
+                                   (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
+                                   FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
+
+     if (hFile == INVALID_HANDLE_VALUE)
+     {
+                          LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
+                          ConErrPrintf(szMsg, out);
+                          return;
+      }
+      
                }
 
                if (!SetStdHandle (STD_OUTPUT_HANDLE, hFile))
                {
-                       ConErrPrintf (_T("Can't redirect to file %s\n"), out);
+                       LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
+                       ConErrPrintf(szMsg, out);
                        return;
                }
 
@@ -701,20 +858,23 @@ VOID ParseCommandLine (LPTSTR cmd)
                {
                        hFile = CreateFile (err,
                                            GENERIC_WRITE,
-                                           0,
+                                           FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
                                            &sa,
                                            (nRedirFlags & ERROR_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
-                                           FILE_ATTRIBUTE_NORMAL,
+                                           FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
                                            NULL);
                        if (hFile == INVALID_HANDLE_VALUE)
                        {
-                               ConErrPrintf (_T("Can't redirect to file %s\n"), err);
+                               LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
+                               ConErrPrintf(szMsg, err);
                                return;
                        }
                }
+
                if (!SetStdHandle (STD_ERROR_HANDLE, hFile))
                {
-                       ConErrPrintf (_T("Can't redirect to file %s\n"), err);
+                       LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
+                       ConErrPrintf(szMsg, err);
                        return;
                }
 
@@ -738,16 +898,21 @@ VOID ParseCommandLine (LPTSTR cmd)
                        CloseHandle (hErr);
                hOldConErr = INVALID_HANDLE_VALUE;
        }
+
+       if(bc)
+               bNewBatch = FALSE;
 #endif
 
        /* process final command */
        DoCommand (s);
 
 #ifdef FEATURE_REDIRECTION
+       if(bNewBatch && bc)
+               AddBatchRedirection(in, out, err);
        /* close old stdin file */
 #if 0  /* buggy implementation */
        SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
-       if ((hFile[0] != INVALID_HANDLE_VALUE) && 
+       if ((hFile[0] != INVALID_HANDLE_VALUE) &&
                (hFile[0] != hOldConIn))
        {
                /* delete old stdin file, if it is a real file */
@@ -835,7 +1000,7 @@ VOID ParseCommandLine (LPTSTR cmd)
  *
  */
 
-static INT 
+static INT
 ProcessInput (BOOL bFlag)
 {
        TCHAR commandline[CMDLINE_LENGTH];
@@ -845,6 +1010,7 @@ ProcessInput (BOOL bFlag)
        LPTSTR cp;
        BOOL bEchoThisLine;
 
+
        do
        {
                /* if no batch input then... */
@@ -861,7 +1027,7 @@ ProcessInput (BOOL bFlag)
                cp = commandline;
                while (*ip)
                {
-                       if (*ip == _T('%'))
+         if (*ip == _T('%'))
                        {
                                switch (*++ip)
                                {
@@ -898,25 +1064,134 @@ ProcessInput (BOOL bFlag)
                                                if ((tp != NULL) &&
                                                    (tp <= _tcschr(ip, _T(' ')) - 1))
                                                {
-                                                       TCHAR evar[512];
+              INT size = 512;
+                                                       TCHAR *evar;
                                                        *tp = _T('\0');
 
-                                                       /* FIXME: This is just a quick hack!! */
-                                                       /* Do a proper memory allocation!! */
-                                                       if (GetEnvironmentVariable (ip, evar, 512))
-                                                               cp = _stpcpy (cp, evar);
-
+              /* FIXME: Correct error handling when it can not alloc memmory */
+                               
+              /* %CD% */
+              if (_tcsicmp(ip,_T("cd")) ==0)
+              {
+                TCHAR szPath[MAX_PATH];
+                           GetCurrentDirectory (MAX_PATH, szPath);
+                cp = _stpcpy (cp, szPath);                 
+              }
+              /* %TIME% */
+              else if (_tcsicmp(ip,_T("time")) ==0)
+              {
+                TCHAR szTime[40];                                                                               
+                SYSTEMTIME t;
+                GetSystemTime(&t); 
+
+                _sntprintf(szTime ,40,_T("%02d%c%02d%c%02d%c%02d"), t.wHour, cTimeSeparator,t.wMinute , cTimeSeparator,t.wSecond , cDecimalSeparator, t.wMilliseconds );
+                cp = _stpcpy (cp, szTime);                                   
+              }
+              
+              /* %DATE% */
+              else if (_tcsicmp(ip,_T("date")) ==0)
+              {
+              TCHAR szDate[40];
+
+                   GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, _T("ddd"), szDate, sizeof (szDate));
+              cp = _stpcpy (cp, szDate);        
+              cp = _stpcpy (cp, _T(" "));        
+              GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, szDate, sizeof (szDate));
+              cp = _stpcpy (cp, szDate);        
+              }
+
+              /* %RANDOM% */
+              else if (_tcsicmp(ip,_T("random")) ==0)
+              {
+               TCHAR szRand[40];               
+               /* Get random number */
+               _itot(rand(),szRand,10);
+               cp = _stpcpy (cp, szRand); 
+              }
+               
+              /* %CMDCMDLINE% */
+              else if (_tcsicmp(ip,_T("cmdcmdline")) ==0)
+              {                      
+               TCHAR *pargv;               
+               /* Get random number */        
+               pargv = GetCommandLine();
+               cp = _stpcpy (cp, pargv); 
+              }
+
+              /* %CMDEXTVERSION% */
+              else if (_tcsicmp(ip,_T("cmdextversion")) ==0)
+              {
+               TCHAR szVER[40];               
+               /* Set version number to 2 */
+               _itot(2,szVER,10);
+               cp = _stpcpy (cp, szVER); 
+              }
+                       
+              /* %ERRORLEVEL% */
+              else if (_tcsicmp(ip,_T("errorlevel")) ==0)
+              {
+                evar = malloc ( size * sizeof(TCHAR));
+                if (evar==NULL) 
+                    return 1; 
+
+                memset(evar,0,512 * sizeof(TCHAR));
+                _itot(nErrorLevel,evar,10);        
+                cp = _stpcpy (cp, evar);
+
+                free(evar);
+              }               
+                                                       else 
+              {
+                evar = malloc ( 512 * sizeof(TCHAR));
+                if (evar==NULL) 
+                    return 1; 
+                                        SetLastError(0);
+                size = GetEnvironmentVariable (ip, evar, 512);
+                                        if(GetLastError() == ERROR_ENVVAR_NOT_FOUND)
+                                        {
+                                                /* if no env var is found you must 
+                                                   continue with what was input*/
+                                          cp = _stpcpy (cp, _T("%"));
+                                               cp = _stpcpy (cp, ip);
+                                               cp = _stpcpy (cp, _T("%"));
+                                        }
+                                        else
+                                        {
+                if (size > 512)
+                {
+                    evar = realloc(evar,size * sizeof(TCHAR) );
+                    if (evar==NULL)
+                    {
+                      return 1;
+                    }
+                    size = GetEnvironmentVariable (ip, evar, size);
+                }
+
+                if (size)
+                {
+                                                                cp = _stpcpy (cp, evar);
+                }
+                                        }
+
+                free(evar);
+              }
+               
                                                        ip = tp + 1;
+
                                                }
                                                else
                                                {
                                                        *cp++ = _T('%');
-                                               }
+                                               }              
+           
                                                break;
                                }
                                continue;
                        }
 
+
+     
+
                        if (_istcntrl (*ip))
                                *ip = _T(' ');
                        *cp++ = *ip++;
@@ -925,10 +1200,10 @@ ProcessInput (BOOL bFlag)
                *cp = _T('\0');
 
                /* strip trailing spaces */
-               while ((--cp >= commandline) && _istspace (*cp));
+               while ((--cp >= commandline) && _istspace (*cp));     
 
                *(cp + 1) = _T('\0');
-
+   
                /* JPP 19980807 */
                /* Echo batch file line */
                if (bEchoThisLine)
@@ -956,6 +1231,7 @@ ProcessInput (BOOL bFlag)
  */
 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
 {
+
        if ((dwCtrlType != CTRL_C_EVENT) &&
            (dwCtrlType != CTRL_BREAK_EVENT))
                return FALSE;
@@ -997,27 +1273,28 @@ static VOID
 ShowCommands (VOID)
 {
        /* print command list */
-       ConOutPrintf (_T("\nInternal commands available:\n"));
-       PrintCommandList ();
+       ConOutResPuts(STRING_CMD_HELP1);
+       PrintCommandList();
 
        /* print feature list */
-       ConOutPuts (_T("\nFeatures available:"));
+       ConOutResPuts(STRING_CMD_HELP2);
+
 #ifdef FEATURE_ALIASES
-       ConOutPuts (_T("  [aliases]"));
+       ConOutResPuts(STRING_CMD_HELP3);
 #endif
 #ifdef FEATURE_HISTORY
-       ConOutPuts (_T("  [history]"));
+       ConOutResPuts(STRING_CMD_HELP4);
 #endif
 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
-       ConOutPuts (_T("  [unix filename completion]"));
+       ConOutResPuts(STRING_CMD_HELP5);
 #endif
 #ifdef FEATURE_DIRECTORY_STACK
-       ConOutPuts (_T("  [directory stack]"));
+       ConOutResPuts(STRING_CMD_HELP6);
 #endif
 #ifdef FEATURE_REDIRECTION
-       ConOutPuts (_T("  [redirections and piping]"));
+       ConOutResPuts(STRING_CMD_HELP7);
 #endif
-       ConOutChar (_T('\n'));
+       ConOutChar(_T('\n'));
 }
 #endif
 
@@ -1034,8 +1311,34 @@ Initialize (int argc, TCHAR* argv[])
        TCHAR commandline[CMDLINE_LENGTH];
        TCHAR ModuleName[_MAX_PATH + 1];
        INT i;
+
        //INT len;
        //TCHAR *ptr, *cmdLine;
+       
+       /* get version information */
+       osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+       GetVersionEx (&osvi);
+
+       /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
+           build process. So don't link implicitly against ntdll.dll, load it
+           dynamically instead */
+
+       if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
+       {
+               /* ntdll is always present on NT */
+               NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
+       }
+       else
+       {
+               /* not all 9x versions have a ntdll.dll, try to load it */
+               NtDllModule = LoadLibrary(TEXT("ntdll.dll"));
+       }
+
+       if (NtDllModule != NULL)
+       {
+               NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
+               NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
+       }
 
 
 #ifdef _DEBUG
@@ -1049,29 +1352,19 @@ Initialize (int argc, TCHAR* argv[])
        DebugPrintf (_T("]\n"));
 #endif
 
-       /* get version information */
-       osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
-       GetVersionEx (&osvi);
-
        InitLocale ();
 
        /* get default input and output console handles */
        hOut = GetStdHandle (STD_OUTPUT_HANDLE);
        hIn  = GetStdHandle (STD_INPUT_HANDLE);
 
+       SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
+
 
        if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
        {
-               ConOutPuts (_T("Starts a new instance of the ReactOS command line interpreter.\n"
-                              "\n"
-                              "CMD [/[C|K] command][/P][/Q][/T:bf]\n"
-                              "\n"
-                              "  /C command  Runs the specified command and terminates.\n"
-                              "  /K command  Runs the specified command and remains.\n"
-                              "  /P          CMD becomes permanent and runs autoexec.bat\n"
-                              "              (cannot be terminated).\n"
-                              "  /T:bf       Sets the background/foreground color (see COLOR command)."));
-               ExitProcess (0);
+               ConOutResPaging(TRUE,STRING_CMD_HELP8);
+               ExitProcess(0);
        }
        SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
 
@@ -1089,7 +1382,7 @@ Initialize (int argc, TCHAR* argv[])
                {
                        if (!_tcsicmp (argv[i], _T("/p")))
                        {
-                               if (!IsValidFileName (_T("\\autoexec.bat")))
+                               if (!IsExistingFile (_T("\\autoexec.bat")))
                                {
 #ifdef INCLUDE_CMD_DATE
                                        cmd_date (_T(""), _T(""));
@@ -1154,11 +1447,11 @@ Initialize (int argc, TCHAR* argv[])
        }
 
        /* run cmdstart.bat */
-       if (IsValidFileName (_T("cmdstart.bat")))
+       if (IsExistingFile (_T("cmdstart.bat")))
        {
                ParseCommandLine (_T("cmdstart.bat"));
        }
-       else if (IsValidFileName (_T("\\cmdstart.bat")))
+       else if (IsExistingFile (_T("\\cmdstart.bat")))
        {
                ParseCommandLine (_T("\\cmdstart.bat"));
        }
@@ -1172,9 +1465,10 @@ Initialize (int argc, TCHAR* argv[])
                p = _tcsrchr (commandline, _T('\\')) + 1;
                _tcscpy (p, _T("cmdstart.bat"));
 
-               if (IsValidFileName (_T("commandline")))
+               if (IsExistingFile (_T("commandline")))
                {
-                       ConErrPrintf (_T("Running %s...\n", commandline));
+                       LoadString(CMD_ModuleHandle, STRING_CMD_ERROR4, szMsg, RC_STRING_MAX_SIZE);
+                       ConErrPrintf(szMsg, commandline);
                        ParseCommandLine (commandline);
                }
        }
@@ -1205,15 +1499,20 @@ Initialize (int argc, TCHAR* argv[])
 
 static VOID Cleanup (int argc, TCHAR *argv[])
 {
+#ifndef __REACTOS__
+       TCHAR szMsg[RC_STRING_MAX_SIZE];
+#endif
+
        /* run cmdexit.bat */
-       if (IsValidFileName (_T("cmdexit.bat")))
+       if (IsExistingFile (_T("cmdexit.bat")))
        {
-               ConErrPrintf (_T("Running cmdexit.bat...\n"));
+               ConErrResPuts(STRING_CMD_ERROR5);
+
                ParseCommandLine (_T("cmdexit.bat"));
        }
-       else if (IsValidFileName (_T("\\cmdexit.bat")))
+       else if (IsExistingFile (_T("\\cmdexit.bat")))
        {
-               ConErrPrintf (_T("Running \\cmdexit.bat...\n"));
+               ConErrResPuts (STRING_CMD_ERROR5);
                ParseCommandLine (_T("\\cmdexit.bat"));
        }
 #ifndef __REACTOS__
@@ -1227,9 +1526,10 @@ static VOID Cleanup (int argc, TCHAR *argv[])
                p = _tcsrchr (commandline, _T('\\')) + 1;
                _tcscpy (p, _T("cmdexit.bat"));
 
-               if (IsValidFileName (_T("commandline")))
+               if (IsExistingFile (_T("commandline")))
                {
-                       ConErrPrintf (_T("Running %s...\n"), commandline);
+                       LoadString(CMD_ModuleHandle, STRING_CMD_ERROR4, szMsg, RC_STRING_MAX_SIZE);
+                       ConErrPrintf(szMsg, commandline);
                        ParseCommandLine (commandline);
                }
        }
@@ -1248,7 +1548,7 @@ static VOID Cleanup (int argc, TCHAR *argv[])
        FreeLastPath ();
 #endif
 
-#ifdef FEATURE_HISTORY 
+#ifdef FEATURE_HISTORY
        CleanHistory();
 #endif
 
@@ -1257,6 +1557,11 @@ static VOID Cleanup (int argc, TCHAR *argv[])
        RemoveBreakHandler ();
        SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
                        ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
+
+       if (NtDllModule != NULL)
+       {
+               FreeLibrary(NtDllModule);
+       }
 }
 
 #ifdef __REACTOS__
@@ -1310,11 +1615,12 @@ PWCHAR * _CommandLineToArgvW(PWCHAR lpCmdLine, int *pNumArgs)
  * main function
  */
 #ifdef _UNICODE
-int main(void)
+int _main(void)
 #else
-int main (int argc, char *argv[])
+int _main (int argc, char *argv[])
 #endif
 {
+  TCHAR startPath[MAX_PATH];
   CONSOLE_SCREEN_BUFFER_INFO Info;
   INT nExitCode;
 #ifdef _UNICODE
@@ -1326,29 +1632,40 @@ int main (int argc, char *argv[])
   argv = CommandLineToArgvW(GetCommandLineW(), &argc);
 #endif
 #endif
+      
+  GetCurrentDirectory(MAX_PATH,startPath);
+  _tchdir(startPath);
 
   SetFileApisToOEM();
+  InputCodePage= 0;
+  OutputCodePage = 0;
 
-  hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE, 
-                        FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, 
+  hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
+                        FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
                        OPEN_EXISTING, 0, NULL);
   if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
     {
-      ConOutFormatMessage(GetLastError());
+      ConErrFormatMessage(GetLastError());
       return(1);
     }
   wColor = Info.wAttributes;
   wDefColor = wColor;
 
+  InputCodePage= GetConsoleCP();
+  OutputCodePage = GetConsoleOutputCP();
+  CMD_ModuleHandle = GetModuleHandle(NULL);
+  
   /* check switches on command-line */
   Initialize(argc, argv);
 
   /* call prompt routine */
   nExitCode = ProcessInput(FALSE);
 
+  
   /* do the cleanup */
   Cleanup(argc, argv);
 
+  
   return(nExitCode);
 }