/* Code to sort Netrom node listing  */
/* All code in NRCMD.C               */
/* D. Crompton  2/92                 */
				       
/* Define the initial sort for netrom list dumps */
/*  1=alias / 0=call                             */
/* Add after includes in nrcmd.c                 */

unsigned Nr_sorttype=1;

/* Add to prototypes in nrcmd.c */

static int doroutesort __ARGS((int argc,char *argv[],void *p));
	
/* Add struct cmds in nrcmd.c    */        
/* The sort command lines below  */        

static struct cmds Routecmds[] = {
	"add",  dorouteadd,     0, 6,
		"netrom route add <alias> <destination> <interface> <quality> <neighbor>",
	"drop", doroutedrop, 0, 4,
		"netrom route drop <destination> <neighbor> <interface>",
	"info", dorouteinfo, 0, 2,
		"netrom route info <destination>",
	"sort", doroutesort, 0, 1,
		"",
	NULLCHAR,
} ;




/* Dump a list of known netrom routes in   */
/* sorted order determined by sort         */
/* flag - default = sort by alias          */
/* Insert this funtion in place of current */
/* function in nrcmd.c                     */

int
doroutedump()
{
	extern unsigned Nr_sorttype;
	register struct nrroute_tab *rp ;
	register int i,j,k, column ;
	char buf[17] ;
	char *cp,*temp ;
	
	column = 1 ;
	
	for(i = 0,j=0 ; i < NRNUMCHAINS ; i++)
		for(rp = Nrroute_tab[i] ; rp != NULLNRRTAB ;j++,rp = rp->next);
	if (j) {
	
	 temp = mallocw (j*17);
	
	 for(i = 0,k=0 ; i < NRNUMCHAINS ; i++)
		for(rp = Nrroute_tab[i] ; rp != NULLNRRTAB ; rp = rp->next,k+=17) {
		     if (Nr_sorttype)   
			{  
			 strcpy(buf,rp->alias) ;
			 /* remove trailing spaces */
			 if((cp = strchr(buf,' ')) == NULLCHAR)
				cp = &buf[strlen(buf)] ;
			 if(cp != buf)           /* don't include colon for null alias */
				*cp++ = ':' ;
			 pax25(cp,rp->call) ;
		       
			} 
		      else 
			 {
			  pax25(buf,rp->call);
			  cp=&buf[strlen(buf)];
			  *cp++=':';
			  strcpy(cp,rp->alias);
			 }
			sprintf(&temp[k],"%-16s",buf);
			}

		 qsort(temp,(size_t)j,17,strcmp);
	    
		 for (i=0,k=0;i<j;i++,k+=17) {       
			tprintf("%-16s  ",&temp[k]) ;
			if(column++ == 4) {
				if(tprintf("\n") == EOF)
				       { 
					free(temp);
					return 0;
				       }
				column = 1 ;
			}
		}

	 if(column != 1)
		tprintf("\n") ;
	 free(temp);        
	} 
	return 0 ;
}

/* netrom Route Dump Sort - ALIAS or CALL first */
/* Add this function in nrcmd.c                 */

static
doroutesort(argc,argv,p)
int argc ;
char *argv[] ;
void *p ;
{
	extern unsigned Nr_sorttype;

	if(argc < 2) {
		tprintf("Netrom Sort by %s\n", Nr_sorttype ? "Alias" : "Call" ) ;
		return 0 ;
	}
	
	switch(argv[1][0]) {
		case 'A':
		case 'a':
			Nr_sorttype = 1 ;
			break ;
		case 'C':
		case 'c':
			Nr_sorttype = 0 ;
			break ;
		default:
			tprintf("usage: netrom sort [alias|call]\n") ;
			return -1 ;
	}

	return 0 ;
}

