#include "utio.h"
#include <unistd.h>

#define MAXLIST 100

/* NODELIST - given a string of the form list[,[list]] where list is
 * either a range (like 1-10) or a single value (like 11), output the
 * individual numbers that the list represents.
 * Example:  nodelist 1-4  prints 1 2 3 4.
 * Example:  nodelist 1-3,5,7-9 prints 1 2 3 5 7 8 9.
 * Options:
 *  -n    : print only the number of values in the list.
 *          Example: nodelist -n 1-3,5 prints 4.
 *  -p prefix : prefix each number with the given string.
 *          Example: nodelist -n 1-3 -p node   prints node1 node2 node3
 *          The -p option is ignored if -n is also specified.
 *  The specified list can enumerate up to MAXLIST elements.
 *
 *  Programmer:  Eric Kostelich, Dept. of Mathematics,
 *               Arizona State University, Tempe, AZ 85287-1804.
 *               kostelich@asu.edu
 */
/* ------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
    extern int optind;
    extern char *optarg;
    char *str;
    char *prefix = "";
    int ch;
    int num_only = 0;
    int n;
    int list[MAXLIST];
    static const char *usage = "%s: [-n (number only)] [-p prefix] list";

    while((ch = getopt(argc, argv, "np:")) > 0)  {
        switch(ch)  {
        case 'n':
            num_only = 1;
	 break;
        case 'p':
            prefix = optarg;
	 break;
        default:    /* getopt prints message */
	 fprintf(stderr, usage, argv[0]);
            return(1);
        }
    }
    if(optind >= argc)  {
       fprintf(stderr, usage, argv[0]);
       return(1);
    }
    str = argv[optind];
    if((n = utscanrange(str, list, MAXLIST)) <= 0)  {
        fprintf(stderr, "%s: error in list\n", argv[0]);
        return(1);
    }
    if(num_only)
        printf("%d\n", n);
    else {
        int j;
        for(j = 0; j < n; j++)
            printf("%s%d ", prefix, list[j]);
        putchar('\n');
    }
    return(0);
}
