summaryrefslogtreecommitdiff
path: root/src/seq.c
blob: d1317a776b17d8c11587ac5405eb784e735af725 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/* seq - print sequence of numbers to standard output.
   Copyright (C) 94, 95, 96, 1997, 1998 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

/* Written by Ulrich Drepper.  */

#include <config.h>
#include <getopt.h>
#include <math.h>
#include <stdio.h>
#include <sys/types.h>

#include "system.h"
#include "error.h"
#include "xstrtod.h"

static double scan_double_arg PARAMS ((const char *arg));
static int check_format PARAMS ((const char *format_string));
static char *get_width_format PARAMS ((void));
static int print_numbers PARAMS ((const char *format_str));

/* If nonzero print all number with equal width.  */
static int equal_width;

/* The printf(3) format used for output.  */
static char *format_str;

/* The starting number.  */
static double first;

/* The name that this program was run with.  */
char *program_name;

/* The string used to separate two numbers.  */
static char *separator;

/* The string output after all numbers have been output.
   Usually "\n" or "\0".  */
/* FIXME: make this an option.  */
static char *terminator = "\n";

/* If nonzero, display usage information and exit.  */
static int show_help;

/* If nonzero, print the version on standard output and exit.  */
static int show_version;

/* The increment.  */
static double step;

/* The last number.  */
static double last;

static struct option const long_options[] =
{
  { "equal-width", no_argument, NULL, 'w'},
  { "format", required_argument, NULL, 'f'},
  { "help", no_argument, &show_help, 1},
  { "separator", required_argument, NULL, 's'},
  { "version", no_argument, &show_version, 1},
  { NULL, 0, NULL, 0}
};

static void
usage (int status)
{
  if (status != 0)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
	     program_name);
  else
    {
      printf (_("\
Usage: %s [OPTION]... LAST\n\
  or:  %s [OPTION]... FIRST LAST\n\
  or:  %s [OPTION]... FIRST INCREMENT LAST\n\
"), program_name, program_name, program_name);
      printf (_("\
Print numbers from FIRST to LAST, in steps of INCREMENT.\n\
\n\
  -f, --format FORMAT      use printf(3) style FORMAT (default: %%g)\n\
  -s, --separator STRING   use STRING to separate numbers (default: \\n)\n\
  -w, --equal-width        equalize width by padding with leading zeroes\n\
      --help               display this help and exit\n\
      --version            output version information and exit\n\
\n\
If FIRST or INCREMENT is omitted, it defaults to 1.\n\
FIRST, INCREMENT, and LAST are interpreted as floating point values.\n\
INCREMENT should be positive if FIRST is smaller than LAST, and negative\n\
otherwise.  When given, the FORMAT argument must contain exactly one of\n\
the printf-style, floating point output formats %%e, %%f, or %%g.\n\
"));
      puts (_("\nReport bugs to <sh-utils-bugs@gnu.org>."));
    }
  exit (status);
}

int
main (int argc, char **argv)
{
  int errs;
  int optc;
  int step_is_set;

  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  equal_width = 0;
  format_str = NULL;
  separator = "\n";
  first = 1.0;
  step_is_set = 0;

  /* We have to handle negative numbers in the command line but this
     conflicts with the command line arguments.  So the getopt mode is
     REQUIRE_ORDER (the '+' in the format string) and it abort on the
     first non-option or negative number.  */
  while ((optc = getopt_long (argc, argv, "+0123456789f:s:w", long_options,
			      NULL)) != -1)
    {
      if ('0' <= optc && optc <= '9')
	{
	  /* means negative number */
	  break;
	}

      switch (optc)
	{
	case 0:
	  break;

	case 'f':
	  format_str = optarg;
	  break;

	case 's':
	  separator = optarg;
	  break;

	case 'w':
	  equal_width = 1;
	  break;

	default:
	  usage (1);
	  /* NOTREACHED */
	}
    }

  if (show_version)
    {
      printf ("seq (%s) %s\n", GNU_PACKAGE, VERSION);
      exit (0);
    }

  if (show_help)
    {
      usage (0);
      /* NOTREACHED */
    }

  if (optind >= argc)
    {
      error (0, 0, _("too few arguments"));
      usage (1);
      /* NOTREACHED */
    }
  last = scan_double_arg (argv[optind++]);

  if (optind < argc)
    {
      first = last;
      last = scan_double_arg (argv[optind++]);

      if (optind < argc)
	{
	  step = last;
	  step_is_set = 1;
	  last = scan_double_arg (argv[optind++]);

	  if (optind < argc)
	    {
	      usage (1);
	      /* NOTREACHED */
	    }
	}
    }

  if (format_str != NULL && equal_width)
    {
      error (0, 0, _("\
format string may not be specified when printing equal width strings"));
      usage (1);
    }

  if (!step_is_set)
    {
      step = first <= last ? 1.0 : -1.0;
    }

  if (format_str != NULL)
    {
      if (!check_format (format_str))
	{
	  error (0, 0, _("invalid format string: `%s'"), format_str);
	  usage (1);
	}
    }
  else
    {
      if (equal_width)
	format_str = get_width_format ();
      else
	format_str = "%g";
    }

  errs = print_numbers (format_str);

  exit (errs);
  /* NOTREACHED */
}

/* Read a double value from the command line.
   Return if the string is correct else signal error.  */

static double
scan_double_arg (const char *arg)
{
  double ret_val;

  if (xstrtod (arg, NULL, &ret_val))
    {
      error (0, 0, _("invalid floating point argument: %s"), arg);
      usage (1);
      /* NOTREACHED */
    }

  return ret_val;
}

/* Check whether the format string is valid for a single double
   argument.
   Return 0 if not, 1 if correct.  */

static int
check_format (const char *fmt)
{
  while (*fmt != '\0')
    {
      if (*fmt == '%')
	{
	  fmt++;
	  if (*fmt != '%')
	    break;
	}

      fmt++;
    }
  if (*fmt == '\0')
    return 0;

  fmt += strspn (fmt, "-+#0");
  if (ISDIGIT (*fmt))
    {
      fmt += strspn (fmt, "0123456789");

      if (*fmt == '.')
	fmt += strspn (++fmt, "0123456789");
    }

  if (*fmt != 'e' && *fmt != 'f' && *fmt != 'g')
    return 0;

  fmt++;
  while (*fmt != '\0')
    {
      if (*fmt == '%')
	{
	  fmt++;
	  if (*fmt != '%')
	    return 0;
	}

      fmt++;
    }

  return 1;
}

#if defined (HAVE_RINT) && defined (HAVE_MODF) && defined (HAVE_FLOOR)

/* Return a printf-style format string with which all selected numbers
   will format to strings of the same width.  */

static char *
get_width_format ()
{
  static char buffer[256];
  int full_width;
  int frac_width;
  int width1, width2;
  double max_val;
  double min_val;
  double temp;

  if (first > last)
    {
      min_val = first - step * floor ((first - last) / step);
      max_val = first;
    }
  else
    {
      min_val = first;
      max_val = first + step * floor ((last - first) / step);
    }

  sprintf (buffer, "%g", rint (max_val));
  if (buffer[strspn (buffer, "0123456789")] != '\0')
    return "%g";
  width1 = strlen (buffer);

  if (min_val < 0.0)
    {
      sprintf (buffer, "%g", rint (min_val));
      if (buffer[strspn (buffer, "-0123456789")] != '\0')
	return "%g";
      width2 = strlen (buffer);

      width1 = width1 > width2 ? width1 : width2;
    }
  full_width = width1;

  sprintf (buffer, "%g", 1.0 + modf (min_val, &temp));
  width1 = strlen (buffer);
  if (width1 == 1)
    width1 = 0;
  else
    {
      if (buffer[0] != '1' || buffer[1] != '.' ||
	  buffer[2 + strspn (&buffer[2], "0123456789")] != '\0')
	return "%g";
      width1 -= 2;
    }

  sprintf (buffer, "%g", 1.0 + modf (step, &temp));
  width2 = strlen (buffer);
  if (width2 == 1)
    width2 = 0;
  else
    {
      if (buffer[0] != '1' || buffer[1] != '.' ||
	  buffer[2 + strspn (&buffer[2], "0123456789")] != '\0')
	return "%g";
      width2 -= 2;
    }
  frac_width = width1 > width2 ? width1 : width2;

  if (frac_width)
    sprintf (buffer, "%%0%d.%df", full_width + 1 + frac_width, frac_width);
  else
    sprintf (buffer, "%%0%dg", full_width);

  return buffer;
}

#else	/* one of the math functions rint, modf, floor is missing.  */

static char *
get_width_format (void)
{
  /* We cannot compute the needed information to determine the correct
     answer.  So we simply return a value that works for all cases.  */
  return "%g";
}

#endif

/* Actually print the sequence of numbers in the specified range, with the
   given or default stepping and format.  */
static int
print_numbers (const char *fmt)
{
  if (first > last)
    {
      int i;

      if (step >= 0)
	{
	  error (0, 0,
		 _("when the starting value is larger than the limit,\n\
the increment must be negative"));
	  usage (1);
	  /* NOTREACHED */
	}

      printf (fmt, first);
      for (i = 1; /* empty */; i++)
	{
	  double x = first + i * step;

	  if (x < last)
	    break;

	  fputs (separator, stdout);
	  printf (fmt, x);
	}
    }
  else
    {
      int i;

      if (step <= 0)
	{
	  error (0, 0,
		 _("when the starting value is smaller than the limit,\n\
the increment must be positive"));
	  usage (1);
	  /* NOTREACHED */
	}

      printf (fmt, first);
      for (i = 1; /* empty */; i++)
	{
	  double x = first + i * step;

	  if (x > last)
	    break;

	  fputs (separator, stdout);
	  printf (format_str, x);
	}
    }
  fputs (terminator, stdout);

  return 0;
}