#include <stdio.h>
#include <string.h>
#include <sys/poll.h>
#include <sys/time.h>

// five minute average
#define AV_BUF_SIZE	300

int g_must_run = 1;
static unsigned int avbuf[AV_BUF_SIZE];

int main(int argc, char **argv)
{
	unsigned char tmpbuf[1024];
	int t_delta_ms;
	int average;
	struct pollfd pfd;
	int res, i;
	int max=0;
	int speed = 0;
	struct timeval tv_lastupdate, tv_now;
	FILE *logfile;
	static int buf_empty = 1;
	unsigned long long total;

	if (argc<2) {
		printf("Usage: ./windmon logfile\n");
		return 1;
	}

	logfile = fopen(argv[1], "a");
	if (!logfile) { perror("fopen"); return 1; }
	
	gettimeofday(&tv_lastupdate, NULL);
	
	while (!feof(stdin) && g_must_run)
	{
		pfd.fd = 0;
		pfd.events = POLLIN;
	
		res = poll(&pfd, 1, 1000);
		if (res>0) 
		{
		
			fgets(tmpbuf, 1024, stdin);

			if (strncmp("delta: ", tmpbuf, 7)==0) {
				t_delta_ms = strtol(tmpbuf+7, NULL, 10);

				speed = 60000/t_delta_ms;
			}

			if (strncmp("status: stopped", tmpbuf, 15)==0) {
				speed = 0;
			}
		}

		if (buf_empty && speed==0) { 
			// dont update the average buffer and
			// output the average value until
			// we have received some rotation.
			printf("Idle\n");
			continue;
		}
		// approximate 1 sec update
		gettimeofday(&tv_now, NULL);
		if (tv_now.tv_sec != tv_lastupdate.tv_sec) {
			memcpy(&tv_lastupdate, &tv_now, sizeof(struct timeval));

			if (buf_empty) {
				for (i=0; i<AV_BUF_SIZE; i++) {
					avbuf[i] = speed;
				}
				buf_empty = 0;
			} else {
				memmove(&avbuf[1], avbuf, (AV_BUF_SIZE-1)*sizeof(int));
				avbuf[0] = speed;
			}
		
			// calculate average and find max
			total = 0;
			max = 0;
			for (i=0; i<AV_BUF_SIZE; i++) {
				if (avbuf[i]>max) { max = avbuf[i]; }
				total += avbuf[i];		
			}
			average = total/((long)AV_BUF_SIZE);
		
			printf("cur speed: %d\n", speed);
			printf("average rpm: %d\n", average);
			printf("max rpm: %d\n", max);
			fprintf(logfile, "%d,%d\n", average,max); fflush(logfile);
		}
	}

	fclose(logfile);
	
	return 0;
}
