wined3d: Trace output corrections and cleanups.
[wine] / programs / wcmd / wcmdmain.c
1 /*
2  * WCMD - Wine-compatible command line interface.
3  *
4  * Copyright (C) 1999 - 2001 D A Pickles
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /*
22  * FIXME:
23  * - Cannot handle parameters in quotes
24  * - Lots of functionality missing from builtins
25  */
26
27 #include "config.h"
28 #include "wcmd.h"
29
30 const char * const inbuilt[] = {"ATTRIB", "CALL", "CD", "CHDIR", "CLS", "COPY", "CTTY",
31                 "DATE", "DEL", "DIR", "ECHO", "ERASE", "FOR", "GOTO",
32                 "HELP", "IF", "LABEL", "MD", "MKDIR", "MOVE", "PATH", "PAUSE",
33                 "PROMPT", "REM", "REN", "RENAME", "RD", "RMDIR", "SET", "SHIFT",
34                 "TIME", "TITLE", "TYPE", "VERIFY", "VER", "VOL", 
35                 "ENDLOCAL", "SETLOCAL", "EXIT" };
36
37 HINSTANCE hinst;
38 DWORD errorlevel;
39 int echo_mode = 1, verify_mode = 0;
40 const char nyi[] = "Not Yet Implemented\n\n";
41 const char newline[] = "\n";
42 const char version_string[] = "WCMD Version " PACKAGE_VERSION "\n\n";
43 const char anykey[] = "Press Return key to continue: ";
44 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
45 BATCH_CONTEXT *context = NULL;
46 static HANDLE old_stdin = INVALID_HANDLE_VALUE, old_stdout = INVALID_HANDLE_VALUE;
47
48 /*****************************************************************************
49  * Main entry point. This is a console application so we have a main() not a
50  * winmain().
51  */
52
53 int main (int argc, char *argv[])
54 {
55   char string[1024];
56   char* cmd=NULL;
57   DWORD count;
58   HANDLE h;
59   int opt_c, opt_k, opt_q;
60
61   opt_c=opt_k=opt_q=0;
62   while (*argv!=NULL)
63   {
64       if (lstrcmpi(*argv,"/c")==0) {
65           opt_c=1;
66           argv++;
67           break;
68       } else if (lstrcmpi(*argv,"/q")==0) {
69           opt_q=1;
70       } else if (lstrcmpi(*argv,"/k")==0) {
71           opt_k=1;
72           argv++;
73           break;
74       } else if (lstrcmpi(*argv,"/t")==0 || lstrcmpi(*argv,"/x")==0 ||
75                  lstrcmpi(*argv,"/y")==0) {
76           /* Ignored for compatibility with Windows */
77       }
78       argv++;
79   }
80
81   if (opt_q) {
82     WCMD_echo("OFF");
83   }
84
85   if (opt_c || opt_k) {
86       int len;
87       char** arg;
88       char* p;
89
90       /* Build the command to execute */
91       len = 0;
92       for (arg = argv; *arg; arg++)
93       {
94           int has_space,bcount;
95           char* a;
96
97           has_space=0;
98           bcount=0;
99           a=*arg;
100           if( !*a ) has_space=1;
101           while (*a!='\0') {
102               if (*a=='\\') {
103                   bcount++;
104               } else {
105                   if (*a==' ' || *a=='\t') {
106                       has_space=1;
107                   } else if (*a=='"') {
108                       /* doubling of '\' preceding a '"',
109                        * plus escaping of said '"'
110                        */
111                       len+=2*bcount+1;
112                   }
113                   bcount=0;
114               }
115               a++;
116           }
117           len+=(a-*arg)+1 /* for the separating space */;
118           if (has_space)
119               len+=2; /* for the quotes */
120       }
121
122       cmd = HeapAlloc(GetProcessHeap(), 0, len);
123       if (!cmd)
124           exit(1);
125
126       p = cmd;
127       for (arg = argv; *arg; arg++)
128       {
129           int has_space,has_quote;
130           char* a;
131
132           /* Check for quotes and spaces in this argument */
133           has_space=has_quote=0;
134           a=*arg;
135           if( !*a ) has_space=1;
136           while (*a!='\0') {
137               if (*a==' ' || *a=='\t') {
138                   has_space=1;
139                   if (has_quote)
140                       break;
141               } else if (*a=='"') {
142                   has_quote=1;
143                   if (has_space)
144                       break;
145               }
146               a++;
147           }
148
149           /* Now transfer it to the command line */
150           if (has_space)
151               *p++='"';
152           if (has_quote) {
153               int bcount;
154               char* a;
155
156               bcount=0;
157               a=*arg;
158               while (*a!='\0') {
159                   if (*a=='\\') {
160                       *p++=*a;
161                       bcount++;
162                   } else {
163                       if (*a=='"') {
164                           int i;
165
166                           /* Double all the '\\' preceding this '"', plus one */
167                           for (i=0;i<=bcount;i++)
168                               *p++='\\';
169                           *p++='"';
170                       } else {
171                           *p++=*a;
172                       }
173                       bcount=0;
174                   }
175                   a++;
176               }
177           } else {
178               strcpy(p,*arg);
179               p+=strlen(*arg);
180           }
181           if (has_space)
182               *p++='"';
183           *p++=' ';
184       }
185       if (p > cmd)
186           p--;  /* remove last space */
187       *p = '\0';
188   }
189
190   if (opt_c) {
191       /* If we do a "wcmd /c command", we don't want to allocate a new
192        * console since the command returns immediately. Rather, we use
193        * the currently allocated input and output handles. This allows
194        * us to pipe to and read from the command interpreter.
195        */
196       if (strchr(cmd,'|') != NULL)
197           WCMD_pipe(cmd);
198       else
199           WCMD_process_command(cmd);
200       HeapFree(GetProcessHeap(), 0, cmd);
201       return 0;
202   }
203
204   SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
205                  ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
206   SetConsoleTitle("Wine Command Prompt");
207
208   if (opt_k) {
209       WCMD_process_command(cmd);
210       HeapFree(GetProcessHeap(), 0, cmd);
211   }
212
213 /*
214  *      If there is an AUTOEXEC.BAT file, try to execute it.
215  */
216
217   GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
218   h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
219   if (h != INVALID_HANDLE_VALUE) {
220     CloseHandle (h);
221 #if 0
222     WCMD_batch_command (string);
223 #endif
224   }
225
226 /*
227  *      Loop forever getting commands and executing them.
228  */
229
230   WCMD_version ();
231   while (TRUE) {
232     WCMD_show_prompt ();
233     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
234     if (count > 1) {
235       string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
236       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
237       if (lstrlen (string) != 0) {
238         if (strchr(string,'|') != NULL) {
239           WCMD_pipe (string);
240         }
241         else {
242           WCMD_process_command (string);
243         }
244       }
245     }
246   }
247 }
248
249
250 /*****************************************************************************
251  * Process one command. If the command is EXIT this routine does not return.
252  * We will recurse through here executing batch files.
253  */
254
255
256 void WCMD_process_command (char *command)
257 {
258     char *cmd, *p;
259     int status, i, len;
260     DWORD count, creationDisposition;
261     HANDLE h;
262     char *whichcmd;
263     SECURITY_ATTRIBUTES sa;
264
265 /*
266  *      Expand up environment variables.
267  */
268     len = ExpandEnvironmentStrings (command, NULL, 0);
269     cmd = HeapAlloc( GetProcessHeap(), 0, len );
270     status = ExpandEnvironmentStrings (command, cmd, len);
271     if (!status) {
272       WCMD_print_error ();
273       HeapFree( GetProcessHeap(), 0, cmd );
274       return;
275     }
276
277 /*
278  *      Changing default drive has to be handled as a special case.
279  */
280
281     if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
282       status = SetCurrentDirectory (cmd);
283       if (!status) WCMD_print_error ();
284       HeapFree( GetProcessHeap(), 0, cmd );
285       return;
286     }
287
288     /* Don't issue newline WCMD_output (newline);           @JED*/
289
290     sa.nLength = sizeof(sa);
291     sa.lpSecurityDescriptor = NULL;
292     sa.bInheritHandle = TRUE;
293 /*
294  *      Redirect stdin and/or stdout if required.
295  */
296
297     if ((p = strchr(cmd,'<')) != NULL) {
298       h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
299                 FILE_ATTRIBUTE_NORMAL, NULL);
300       if (h == INVALID_HANDLE_VALUE) {
301         WCMD_print_error ();
302         HeapFree( GetProcessHeap(), 0, cmd );
303         return;
304       }
305       old_stdin = GetStdHandle (STD_INPUT_HANDLE);
306       SetStdHandle (STD_INPUT_HANDLE, h);
307     }
308     if ((p = strchr(cmd,'>')) != NULL) {
309       *p++ = '\0';
310       if ('>' == *p) {
311         creationDisposition = OPEN_ALWAYS;
312         p++;
313       }
314       else {
315         creationDisposition = CREATE_ALWAYS;
316       }
317       h = CreateFile (WCMD_parameter (p, 0, NULL), GENERIC_WRITE, 0, &sa, creationDisposition,
318                 FILE_ATTRIBUTE_NORMAL, NULL);
319       if (h == INVALID_HANDLE_VALUE) {
320         WCMD_print_error ();
321         HeapFree( GetProcessHeap(), 0, cmd );
322         return;
323       }
324       if (SetFilePointer (h, 0, NULL, FILE_END) ==
325           INVALID_SET_FILE_POINTER) {
326         WCMD_print_error ();
327       }
328       old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
329       SetStdHandle (STD_OUTPUT_HANDLE, h);
330     }
331     if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
332
333 /*
334  * Strip leading whitespaces, and a '@' if supplied
335  */
336     whichcmd = WCMD_strtrim_leading_spaces(cmd);
337     if (whichcmd[0] == '@') whichcmd++;
338
339 /*
340  *      Check if the command entered is internal. If it is, pass the rest of the
341  *      line down to the command. If not try to run a program.
342  */
343
344     count = 0;
345     while (IsCharAlphaNumeric(whichcmd[count])) {
346       count++;
347     }
348     for (i=0; i<=WCMD_EXIT; i++) {
349       if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
350           whichcmd, count, inbuilt[i], -1) == 2) break;
351     }
352     p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
353     WCMD_parse (p, quals, param1, param2);
354     switch (i) {
355
356       case WCMD_ATTRIB:
357         WCMD_setshow_attrib ();
358         break;
359       case WCMD_CALL:
360         WCMD_run_program (p, 1);
361         break;
362       case WCMD_CD:
363       case WCMD_CHDIR:
364         WCMD_setshow_default ();
365         break;
366       case WCMD_CLS:
367         WCMD_clear_screen ();
368         break;
369       case WCMD_COPY:
370         WCMD_copy ();
371         break;
372       case WCMD_CTTY:
373         WCMD_change_tty ();
374         break;
375       case WCMD_DATE:
376         WCMD_setshow_date ();
377         break;
378       case WCMD_DEL:
379       case WCMD_ERASE:
380         WCMD_delete (0);
381         break;
382       case WCMD_DIR:
383         WCMD_directory ();
384         break;
385       case WCMD_ECHO:
386         WCMD_echo(&whichcmd[count]);
387         break;
388       case WCMD_FOR:
389         WCMD_for (p);
390         break;
391       case WCMD_GOTO:
392         WCMD_goto ();
393         break;
394       case WCMD_HELP:
395         WCMD_give_help (p);
396         break;
397       case WCMD_IF:
398         WCMD_if (p);
399         break;
400       case WCMD_LABEL:
401         WCMD_volume (1, p);
402         break;
403       case WCMD_MD:
404       case WCMD_MKDIR:
405         WCMD_create_dir ();
406         break;
407       case WCMD_MOVE:
408         WCMD_move ();
409         break;
410       case WCMD_PATH:
411         WCMD_setshow_path (p);
412         break;
413       case WCMD_PAUSE:
414         WCMD_pause ();
415         break;
416       case WCMD_PROMPT:
417         WCMD_setshow_prompt ();
418         break;
419       case WCMD_REM:
420         break;
421       case WCMD_REN:
422       case WCMD_RENAME:
423         WCMD_rename ();
424         break;
425       case WCMD_RD:
426       case WCMD_RMDIR:
427         WCMD_remove_dir ();
428         break;
429       case WCMD_SETLOCAL:
430         WCMD_setlocal(p);
431         break;
432       case WCMD_ENDLOCAL:
433         WCMD_endlocal();
434         break;
435       case WCMD_SET:
436         WCMD_setshow_env (p);
437         break;
438       case WCMD_SHIFT:
439         WCMD_shift ();
440         break;
441       case WCMD_TIME:
442         WCMD_setshow_time ();
443         break;
444       case WCMD_TITLE:
445         if (strlen(&whichcmd[count]) > 0)
446           WCMD_title(&whichcmd[count+1]);
447         break;
448       case WCMD_TYPE:
449         WCMD_type ();
450         break;
451       case WCMD_VER:
452         WCMD_version ();
453         break;
454       case WCMD_VERIFY:
455         WCMD_verify (p);
456         break;
457       case WCMD_VOL:
458         WCMD_volume (0, p);
459         break;
460       case WCMD_EXIT:
461         ExitProcess (0);
462       default:
463         WCMD_run_program (whichcmd, 0);
464     }
465     HeapFree( GetProcessHeap(), 0, cmd );
466     if (old_stdin != INVALID_HANDLE_VALUE) {
467       CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
468       SetStdHandle (STD_INPUT_HANDLE, old_stdin);
469       old_stdin = INVALID_HANDLE_VALUE;
470     }
471     if (old_stdout != INVALID_HANDLE_VALUE) {
472       CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
473       SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
474       old_stdout = INVALID_HANDLE_VALUE;
475     }
476 }
477
478 static void init_msvcrt_io_block(STARTUPINFO* st)
479 {
480     STARTUPINFO st_p;
481     /* fetch the parent MSVCRT info block if any, so that the child can use the
482      * same handles as its grand-father
483      */
484     st_p.cb = sizeof(STARTUPINFO);
485     GetStartupInfo(&st_p);
486     st->cbReserved2 = st_p.cbReserved2;
487     st->lpReserved2 = st_p.lpReserved2;
488     if (st_p.cbReserved2 && st_p.lpReserved2 &&
489         (old_stdin != INVALID_HANDLE_VALUE || old_stdout != INVALID_HANDLE_VALUE))
490     {
491         /* Override the entries for fd 0,1,2 if we happened
492          * to change those std handles (this depends on the way wcmd sets
493          * it's new input & output handles)
494          */
495         size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
496         BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
497         if (ptr)
498         {
499             unsigned num = *(unsigned*)st_p.lpReserved2;
500             char* flags = (char*)(ptr + sizeof(unsigned));
501             HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
502
503             memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
504             st->cbReserved2 = sz;
505             st->lpReserved2 = ptr;
506
507 #define WX_OPEN 0x01    /* see dlls/msvcrt/file.c */
508             if (num <= 0 || (flags[0] & WX_OPEN))
509             {
510                 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
511                 flags[0] |= WX_OPEN;
512             }
513             if (num <= 1 || (flags[1] & WX_OPEN))
514             {
515                 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
516                 flags[1] |= WX_OPEN;
517             }
518             if (num <= 2 || (flags[2] & WX_OPEN))
519             {
520                 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
521                 flags[2] |= WX_OPEN;
522             }
523 #undef WX_OPEN
524         }
525     }
526 }
527
528 /******************************************************************************
529  * WCMD_run_program
530  *
531  *      Execute a command line as an external program. If no extension given then
532  *      precedence is given to .BAT files. Must allow recursion.
533  *      
534  *      called is 1 if the program was invoked with a CALL command - removed
535  *      from command -. It is only used for batch programs.
536  *
537  *      FIXME: Case sensitivity in suffixes!
538  */
539
540 void WCMD_run_program (char *command, int called) {
541
542 STARTUPINFO st;
543 PROCESS_INFORMATION pe;
544 SHFILEINFO psfi;
545 DWORD console;
546 BOOL status;
547 HANDLE h;
548 HINSTANCE hinst;
549 char filetorun[MAX_PATH];
550
551   WCMD_parse (command, quals, param1, param2);  /* Quick way to get the filename */
552   if (!(*param1) && !(*param2))
553     return;
554   if (strpbrk (param1, "/\\:") == NULL) {  /* No explicit path given */
555     char *ext = strrchr( param1, '.' );
556     if (!ext || !strcasecmp( ext, ".bat"))
557     {
558       if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
559         WCMD_batch (filetorun, command, called);
560         return;
561       }
562     }
563     if (!ext || !strcasecmp( ext, ".cmd"))
564     {
565       if (SearchPath (NULL, param1, ".cmd", sizeof(filetorun), filetorun, NULL)) {
566         WCMD_batch (filetorun, command, called);
567         return;
568       }
569     }
570   }
571   else {                                        /* Explicit path given */
572     char *ext = strrchr( param1, '.' );
573     if (ext && (!strcasecmp( ext, ".bat" ) || !strcasecmp( ext, ".cmd" )))
574     {
575       WCMD_batch (param1, command, called);
576       return;
577     }
578
579     if (ext && strpbrk( ext, "/\\:" )) ext = NULL;
580     if (!ext)
581     {
582       strcpy (filetorun, param1);
583       strcat (filetorun, ".bat");
584       h = CreateFile (filetorun, GENERIC_READ, FILE_SHARE_READ,
585                       NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
586       if (h != INVALID_HANDLE_VALUE) {
587         CloseHandle (h);
588         WCMD_batch (param1, command, called);
589         return;
590       }
591     }
592   }
593
594         /* No batch file found, assume executable */
595
596   hinst = FindExecutable (param1, NULL, filetorun);
597   if ((int)hinst < 32)
598     console = 0;
599   else
600     console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
601
602   ZeroMemory (&st, sizeof(STARTUPINFO));
603   st.cb = sizeof(STARTUPINFO);
604   init_msvcrt_io_block(&st);
605
606   status = CreateProcess (NULL, command, NULL, NULL, TRUE, 
607                           0, NULL, NULL, &st, &pe);
608   if (!status) {
609     WCMD_print_error ();
610     return;
611   }
612   if (!console) errorlevel = 0;
613   else
614   {
615       if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
616       GetExitCodeProcess (pe.hProcess, &errorlevel);
617       if (errorlevel == STILL_ACTIVE) errorlevel = 0;
618   }
619   CloseHandle(pe.hProcess);
620   CloseHandle(pe.hThread);
621 }
622
623 /******************************************************************************
624  * WCMD_show_prompt
625  *
626  *      Display the prompt on STDout
627  *
628  */
629
630 void WCMD_show_prompt (void) {
631
632 int status;
633 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
634 char *p, *q;
635
636   status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
637   if ((status == 0) || (status > sizeof(prompt_string))) {
638     lstrcpy (prompt_string, "$P$G");
639   }
640   p = prompt_string;
641   q = out_string;
642   *q = '\0';
643   while (*p != '\0') {
644     if (*p != '$') {
645       *q++ = *p++;
646       *q = '\0';
647     }
648     else {
649       p++;
650       switch (toupper(*p)) {
651         case '$':
652           *q++ = '$';
653           break;
654         case 'B':
655           *q++ = '|';
656           break;
657         case 'D':
658           GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
659           while (*q) q++;
660           break;
661         case 'E':
662           *q++ = '\E';
663           break;
664         case 'G':
665           *q++ = '>';
666           break;
667         case 'L':
668           *q++ = '<';
669           break;
670         case 'N':
671           status = GetCurrentDirectory (sizeof(curdir), curdir);
672           if (status) {
673             *q++ = curdir[0];
674           }
675           break;
676         case 'P':
677           status = GetCurrentDirectory (sizeof(curdir), curdir);
678           if (status) {
679             lstrcat (q, curdir);
680             while (*q) q++;
681           }
682           break;
683         case 'Q':
684           *q++ = '=';
685           break;
686         case 'T':
687           GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
688           while (*q) q++;
689           break;
690        case 'V':
691            lstrcat (q, version_string);
692            while (*q) q++;
693          break;
694         case '_':
695           *q++ = '\n';
696           break;
697       }
698       p++;
699       *q = '\0';
700     }
701   }
702   WCMD_output_asis (out_string);
703 }
704
705 /****************************************************************************
706  * WCMD_print_error
707  *
708  * Print the message for GetLastError
709  */
710
711 void WCMD_print_error (void) {
712 LPVOID lpMsgBuf;
713 DWORD error_code;
714 int status;
715
716   error_code = GetLastError ();
717   status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
718                         NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
719   if (!status) {
720     WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
721                         error_code, GetLastError());
722     return;
723   }
724   WCMD_output_asis (lpMsgBuf);
725   LocalFree ((HLOCAL)lpMsgBuf);
726   WCMD_output_asis (newline);
727   return;
728 }
729
730 /*******************************************************************
731  * WCMD_parse - parse a command into parameters and qualifiers.
732  *
733  *      On exit, all qualifiers are concatenated into q, the first string
734  *      not beginning with "/" is in p1 and the
735  *      second in p2. Any subsequent non-qualifier strings are lost.
736  *      Parameters in quotes are handled.
737  */
738
739 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
740
741 int p = 0;
742
743   *q = *p1 = *p2 = '\0';
744   while (TRUE) {
745     switch (*s) {
746       case '/':
747         *q++ = *s++;
748         while ((*s != '\0') && (*s != ' ') && *s != '/') {
749           *q++ = toupper (*s++);
750         }
751         *q = '\0';
752         break;
753       case ' ':
754       case '\t':
755         s++;
756         break;
757       case '"':
758         s++;
759         while ((*s != '\0') && (*s != '"')) {
760           if (p == 0) *p1++ = *s++;
761           else if (p == 1) *p2++ = *s++;
762           else s++;
763         }
764         if (p == 0) *p1 = '\0';
765         if (p == 1) *p2 = '\0';
766         p++;
767         if (*s == '"') s++;
768         break;
769       case '\0':
770         return;
771       default:
772         while ((*s != '\0') && (*s != ' ') && (*s != '\t')) {
773           if (p == 0) *p1++ = *s++;
774           else if (p == 1) *p2++ = *s++;
775           else s++;
776         }
777         if (p == 0) *p1 = '\0';
778         if (p == 1) *p2 = '\0';
779         p++;
780     }
781   }
782 }
783
784 /*******************************************************************
785  * WCMD_output - send output to current standard output device.
786  *
787  */
788
789 void WCMD_output (const char *format, ...) {
790
791 va_list ap;
792 char string[1024];
793 int ret;
794
795   va_start(ap,format);
796   ret = vsnprintf (string, sizeof( string), format, ap);
797   va_end(ap);
798   if( ret >= sizeof( string)) {
799        WCMD_output_asis("ERR: output truncated in WCMD_output\n" );
800        string[sizeof( string) -1] = '\0';
801   }
802   WCMD_output_asis(string);
803 }
804
805
806 static int line_count;
807 static int max_height;
808 static BOOL paged_mode;
809
810 void WCMD_enter_paged_mode(void)
811 {
812 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
813
814   if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
815     max_height = consoleInfo.dwSize.Y;
816   else
817     max_height = 25;
818   paged_mode = TRUE;
819   line_count = 5; /* keep 5 lines from previous output */
820 }
821
822 void WCMD_leave_paged_mode(void)
823 {
824   paged_mode = FALSE;
825 }
826
827 /*******************************************************************
828  * WCMD_output_asis - send output to current standard output device.
829  *        without formatting eg. when message contains '%'
830  */
831
832 void WCMD_output_asis (const char *message) {
833   DWORD count;
834   char* ptr;
835   char string[1024];
836
837   if (paged_mode) {
838     do {
839       if ((ptr = strchr(message, '\n')) != NULL) ptr++;
840       WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, 
841                  (ptr) ? ptr - message : lstrlen(message), &count, NULL);
842       if (ptr) {
843         if (++line_count >= max_height - 1) {
844           line_count = 0;
845           WCMD_output_asis (anykey);
846           ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
847         }
848       }
849     } while ((message = ptr) != NULL);
850   } else {
851       WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
852   }
853 }
854
855
856 /***************************************************************************
857  * WCMD_strtrim_leading_spaces
858  *
859  *      Remove leading spaces from a string. Return a pointer to the first
860  *      non-space character. Does not modify the input string
861  */
862
863 char *WCMD_strtrim_leading_spaces (char *string) {
864
865 char *ptr;
866
867   ptr = string;
868   while (*ptr == ' ') ptr++;
869   return ptr;
870 }
871
872 /*************************************************************************
873  * WCMD_strtrim_trailing_spaces
874  *
875  *      Remove trailing spaces from a string. This routine modifies the input
876  *      string by placing a null after the last non-space character
877  */
878
879 void WCMD_strtrim_trailing_spaces (char *string) {
880
881 char *ptr;
882
883   ptr = string + lstrlen (string) - 1;
884   while ((*ptr == ' ') && (ptr >= string)) {
885     *ptr = '\0';
886     ptr--;
887   }
888 }
889
890 /*************************************************************************
891  * WCMD_pipe
892  *
893  *      Handle pipes within a command - the DOS way using temporary files.
894  */
895
896 void WCMD_pipe (char *command) {
897
898 char *p;
899 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
900
901   GetTempPath (sizeof(temp_path), temp_path);
902   GetTempFileName (temp_path, "WCMD", 0, temp_file);
903   p = strchr(command, '|');
904   *p++ = '\0';
905   wsprintf (temp_cmd, "%s > %s", command, temp_file);
906   WCMD_process_command (temp_cmd);
907   command = p;
908   while ((p = strchr(command, '|'))) {
909     *p++ = '\0';
910     GetTempFileName (temp_path, "WCMD", 0, temp_file2);
911     wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
912     WCMD_process_command (temp_cmd);
913     DeleteFile (temp_file);
914     lstrcpy (temp_file, temp_file2);
915     command = p;
916   }
917   wsprintf (temp_cmd, "%s < %s", command, temp_file);
918   WCMD_process_command (temp_cmd);
919   DeleteFile (temp_file);
920 }