/* 
  write good, tight, code. plenty of bad code examples in TPOP
  handle EOF correctly with fgets()
  check for leaks - add to inspection list
  do pwd and cd inline, not in a child!
  this is not robust input and parsing
  <cr> by itself doesn't complete the fscanf() call
  dangers of using strtok() - not reentrant, destroys string
  trapping control-c?
  dangers of using gets(), no buffer size check
*/
#include <stdio.h>
#include <string.h>
/* #include <unistd.h> */ 

int main( void ) {
  const int CommBuffSize = 128;
  const int MsgBuffSize = 256;
  char input[CommBuffSize]; 
  int totalChildren; 
  int status; 
  
  while ( 1 ) { 
    fprintf( stdout, "_$ " ); 
    status = (int)gets( input ); 
    
    if ( status == NULL )
      exit( status );
      
    else if ( strcmp( input, "exit" ) == 0 ) 
      exit( status );
      
    else if ( strcmp( input, "pwd" ) == 0 )
      fprintf( stdout, "%s\n", "here" ); 
      
    else if ( strncmp( input, "cd", 2 ) == 0 ) {
      char s[CommBuffSize]; 
      char *where; 
      
      fprintf( stdout, "cd detected, command line = \n", input ); 
      strcpy( s, input ); 
      where = strtok( s, " " );
      where = strtok( NULL, " " ); 
      fprintf( stdout, "where = %s\n", where ); 
      
      /* status = chdir( const char *path );
      if ( status != 0 ) {
         char msg[MsgBuffSize]; 
         
         sprintf( msg, "%s %s", "Error changing to directory ", where ); 
         perror( msg ); 
         break; 
      } */ 
    }

    else 
      fprintf( stdout, "%s\n", input ); 
  }
}

