/* simtrade.c. This program simulates fluctuating 
	stock prices for the WWWS system. */

#include <stdlib.h>
#include <time.h>

#include "parse.h"

#define PATH_SPACE 256
#define SYMBOL_SPACE 64
#define HISTORY_SIZE 30

#define DATA_PATH "/CHANGE/THIS/PATH/wwwws"

int main(int argc, char *argv[]) {
	FILE *in, *out;
	char s[PATH_SPACE], snew[PATH_SPACE];
	int iterations = 1;
	time_t now;
	int i;
	/* Now we should have a different random seed */
	time(&now);
	srand((int) now);	
	if (argc == 2) {
		iterations = atoi(argv[1]);
	} else if (argc == 1) {
		/* OK, assume 1 iteration */
	} else {
		fprintf(stderr, "Usage: simtrade [# of iterations]\n");
		return 1;
	}
	for (i=0; (i < iterations); i++) {
		int stocks = 0;
		sprintf(s, "%s/database", DATA_PATH);
		sprintf(snew, "%s/database.new", DATA_PATH);
		in = fopen(s, "r");
		if (!in) {
			fprintf(stderr, "Can't open database file %s for reading.\n",
				s);
			exit(1);
		}
		out = fopen(snew, "w");
		if (!out) {
			fprintf(stderr, "Can't open temporary file %s for writing.\n", 
				snew);
			fclose(in);
			exit(1);
		}
		SetFieldSeparator(' ');
		do {
			char symbol[SYMBOL_SPACE];
			char priceString[SYMBOL_SPACE];		
			double history[HISTORY_SIZE];
			int historyPos = 0;
			int i;
			if (!GetField(in, symbol, SYMBOL_SPACE)) {
				break;
			}
			while (GetField(in, priceString, SYMBOL_SPACE)) {
				/* Discard the oldest price. */
				history[historyPos++] = atof(priceString);
			}	
			/* If the history is full, discard the oldest price. */
			if (historyPos == HISTORY_SIZE) {
				for (i = 0; (i < (HISTORY_SIZE - 1)); i++) {
					history[i] = history[i+1];
				}
				historyPos--;
			}
			/* Generate a price fluctuation at random. Some would say this
				method is quite realistic. */
			if (historyPos) {
				history[historyPos] = 
					history[historyPos-1] + 
					((double)(abs(rand() >> 8) % 40) - 19.5) * .125;
				if (history[historyPos] < 0.0) {
					history[historyPos] = 0.125;
				}	
			} else {
				history[historyPos] = (double)(abs(rand() >> 8) % 80 + 80) 
					/ 2.0;
			}
			historyPos++;
			/* Write the updated record. */
			fprintf(out, "%s ", symbol);
			for (i=0; (i < historyPos); i++) {
				fprintf(out, "%f ", history[i]);
			}
			fprintf(out, "\n");
			stocks++;
		} while (NextRecord(in));
		printf("%d stocks updated.\n", stocks);		
		fclose(in);
		fclose(out);
		unlink(s);
		rename(snew, s);
	}
	return 0;
}
