// // Simple filter to average every N input lines. // // - Assumes one data point per line. // - Displays output with same precision as input. // #include #include #include long SkipCount = 0; long Window = 1; void main (int argc, char *argv[]) { long In, Out, Index; char Line[1000]; int Dp = 0; void MaxDp (char *p, int *dp); double Sum, Value; if (argc > 1 && strcmp(argv[1], "/?") == 0) { fprintf(stderr, "%s [Window] [skip]\n", argv[0]); exit(0); } if (argc > 1) { sscanf(argv[1], "%ld", &Window); if (Window < 1) { Window = 1; } } if (argc > 2) { sscanf(argv[2], "%ld", &SkipCount); if (SkipCount < 0) { SkipCount = 0; } } In = Out = Index = 0; Sum = 0.0; while (1) { if (fgets(Line, sizeof(Line), stdin) == NULL) { break; } In += 1; if (In > SkipCount) { MaxDp(Line, &Dp); sscanf(Line, "%lf", &Value); Sum += Value; Index += 1; if (Index == Window) { printf("%.*lf\n", Dp, Sum / (double)Window); Out += 1; Index = 0; Sum = 0.0; } } } fprintf(stderr, "%ld lines in, %ld lines skipped, %ld lines out, %ld lines left\n", In, SkipCount, Out, Index); return; } // // Recalculate maximum number of decimal places. // void MaxDp (char *p, int *dp) { int n = 0; p = strchr(p, '.'); if (p) { for (p++; *p != '\0'; p++, n++) { if (*p < '0' || *p > '9') { break; } } } if (n > *dp) { *dp = n; } return; }