aboutsummaryrefslogtreecommitdiffstats
path: root/spark.c
blob: 789b8130eb69b0ff3feb350fbd9ad291cb37a786 (plain) (blame)
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
#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
	if (isatty(fileno(stdin)) && (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
		fprintf(stderr, "Spark\n  by Jason A. Donenfeld <Jason@zx2c4.com>\n\n");
		fprintf(stderr, "Usage: %s [number] [number] [number] ...\n", argv[0]);
		fprintf(stderr, "If no arguments are given, read from stdin numbers delimited by\n");
		fprintf(stderr, "any characters except 0 1 2 3 4 5 6 7 8 9 . - e E.\n");
		return 1;
	}
	double *values;
	int total;
	double max = DBL_MIN;
	double min = DBL_MAX;
	if (argc > 1) {
		total = argc - 1;
		values = malloc(sizeof(double) * total);
		if (!values) {
			perror("malloc");
			return 2;
		}
		for (int i = 0; i < total; ++i) {
			values[i] = atof(argv[i + 1]);
			if (values[i] > max)
				max = values[i];
			if (values[i] < min)
				min = values[i];
		}
	} else {
		char buffer[32];
		int i = 0;
		int c = 0;
		int size = 16;
		total = 0;
		values = malloc(sizeof(double) * size);
		if (!values) {
			perror("malloc");
			return 2;
		}
		while (c != EOF) {
			for (;;) {
				c = getchar();
				if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == 'e' || c == 'E')
					buffer[i++] = c;
				else
					break;
				if (i == 31)
					break;
			}
			buffer[i] = '\0';
			if (i) {
				if (total == size) {
					size *= 2;
					values = realloc(values, sizeof(double) * size);
					if (!values) {
						perror("realloc");
						return 2;
					}
				}
				values[total] = atof(buffer);
				if (values[total] > max)
					max = values[total];
				if (values[total] < min)
					min = values[total];
				++total;
			}
			i = 0;
		}
	}

	double difference = max - min + 1;
	if (difference < 1)
		difference = 1;
	const int levels = 8;
	for (int i = 0; i < total; ++i) {
		putchar('\xe2');
		putchar('\x96');
		putchar('\x81' + (int)round((values[i] - min + 1) / difference * (levels - 1)));
	}
	putchar('\n');

	free(values);
	return 0;
}