commit dd8acb3ca5ee35f5d8d6c9080191b1c9d276b627
parent 5d4a2cef872d8b3cbb45892042bf5df43a0c7616
Author: Anders Damsgaard <anders@adamsgaard.dk>
Date:   Tue, 24 Mar 2020 16:10:47 +0100
Rewrite shear_flux program in C
Diffstat:
| M | Makefile |  |  | 10 | ++++++++-- | 
| D | shear_flux |  |  | 16 | ---------------- | 
| A | shear_flux.c |  |  | 78 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | 
3 files changed, 86 insertions(+), 18 deletions(-)
diff --git a/Makefile b/Makefile
@@ -6,6 +6,7 @@ MANPREFIX ?= ${PREFIX}/man
 DOCPREFIX ?= ${PREFIX}/share/doc/${NAME}
 
 HDR = \
+	arg.h\
 	arrays.h\
 	fluid.h\
 	parameter_defaults.h\
@@ -22,8 +23,8 @@ DOC = \
 	README.md\
 	LICENSE
 
-HERE_CFLAGS = ${CFLAGS} -std=c99 -pedantic -Wall -O2 -g
-HERE_LDFLAGS = ${LDFLAGS} -lm
+HERE_CFLAGS = ${CFLAGS} -std=c99 -pedantic -Wall -O0 -g
+HERE_LDFLAGS = ${LDFLAGS} -lm -g
 GLOBALCONST = -DVERSION=\"${VERSION}\"
 
 all: ${BIN}
@@ -44,6 +45,11 @@ max_depth_simple_shear: max_depth_simple_shear.o arrays.o fluid.o simulation.o $
 		max_depth_simple_shear.o arrays.o fluid.o simulation.o\
 		-o $@
 
+shear_flux: shear_flux.o ${HDR}
+	${CC} ${HERE_LDFLAGS}\
+		shear_flux.o\
+		-o $@
+
 install: ${BIN}
 	# installing executables
 	mkdir -p ${DESTDIR}${PREFIX}/bin
diff --git a/shear_flux b/shear_flux
@@ -1,16 +0,0 @@
-#!/usr/bin/awk -f
-BEGIN {
-	getline
-	integral = 0.0
-}
-NF{
-	if (NR > 1)
-	{
-		integral += ($2 + v_prev)/2.0*($1 - z_prev);
-	}
-	z_prev = $1;
-	v_prev = $2;
-}
-END{
-	print integral
-}
diff --git a/shear_flux.c b/shear_flux.c
@@ -0,0 +1,78 @@
+#include <err.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+
+#include "arg.h"
+
+char *argv0;
+
+static void
+usage(void)
+{
+	dprintf(2, "usage: %s "
+		"[-v] "
+		"[-h] "
+		"[file ...] "
+		"\n", argv0);
+	exit(1);
+}
+
+/* input format: positions<TAB>shear_velocities */
+double
+find_flux(FILE *f)
+{
+	int i;
+	double pos, vel, pos_prev, vel_prev, flux;
+
+	i = 0;
+	flux = 0.0;
+	while (fscanf(f, "%lf\t%lf%*[^\n]", &pos, &vel) == 2) {
+		if (i++ > 0)
+			flux += (vel + vel_prev)/2.0*(pos - pos_prev);
+		pos_prev = pos;
+		vel_prev = vel;
+	}
+
+	return flux;
+}
+
+int
+main(int argc, char* argv[])
+{
+	int i;
+	FILE *fp;
+
+#ifdef __OpenBSD__
+	if (pledge("stdio rpath", NULL) == -1) {
+		fprintf(stderr, "error: pledge failed");
+		exit(1);
+	}
+#endif
+
+	ARGBEGIN {
+	case 'h':
+		usage();
+		break;
+	case 'v':
+		printf("%s-"VERSION"\n", argv0);
+		return 0;
+		break;
+	default:
+		usage();
+	} ARGEND;
+
+	if (argc > 0) {
+		for (i = 0; i < argc; i++) {
+			if (!(fp = fopen(argv[i], "r")))
+				err(1, "fopen: %s", argv[i]);
+
+			printf("%.17g\n", find_flux(fp));
+			fclose(fp);
+		}
+	} else
+		printf("%.17g\n", find_flux(stdin));
+
+	return 0;
+}