/* Copyright (c) 2001 by SoftIntegration, Inc. All Rights Reserved */
/***********************************************************
* command name: popd [n]
* Note: (1) Pop the directory stack and cd to  the  new  top
*               directory.   The  elements  of the directory stack
*               are numbered from 0 starting at the top.
*          +n   Discard the n'th entry in the stack.
*       (2) popd is C-shell compatible.
*       (2) global variable g_dirstack is defined in 
*           $CHHOME/config/chrc
*
* History: created by Harry H. Cheng, 11/5/1996
**********************************************************/
#include<stdio.h>
int main(int argc, char *argv[]) {
  struct dirstack_t{ 
    string_t dir;  
    struct dirstack_t *next;
  } *cwdir, *tmpdir;
  string_t dir;
  int n;
  
  if(argc == 2 && isnum(argv[1]))
     n = atoi(argv[1]);
  else if (argc>2) {
    fprintf(stderr, "popd: Invalid argument \n");
    fprintf(stderr, "Usage: popd [n] \n");
    return(1);
  }
    
  if(g_dirstack!=NULL) {
     cwdir = (struct dirstack_t *) g_dirstack;
     if(n == 0) { /* no argument or value is 0 */
       g_dirstack = (char *)cwdir->next;
       dir = cwdir->dir;
       free(cwdir);
       chdir(dir);
       _cwd = dir;
     }
     else {
       tmpdir = (struct dirstack_t *)g_dirstack;
       while(tmpdir->next!=NULL && n>1) {
         tmpdir = tmpdir->next;
         n--;
       }
       if(tmpdir->next==NULL) {
         fprintf(stderr, "popd: Directory stack not that deep\n");
         fprintf(stderr, "Usage: popd [n] \n");
       }
       else {
         cwdir = tmpdir->next;
         tmpdir->next = tmpdir->next->next;
         dir = cwdir->dir;
         free(cwdir);
         chdir(dir);
         _cwd = dir;
       }
     }
     tmpdir = (struct dirstack_t *)g_dirstack;
     n = 0;
     while(tmpdir!=NULL) {
       printf("%d\t%s\n", n++, tmpdir->dir);
       tmpdir = tmpdir->next;
     }
  }
  else 
    fprintf(stderr, "popd: Directory stack empty\n");

}
