// sattool - visual satellite tracking and prediction tool.
// Copyright 2000 Tom Rothamel <tom-idbg@onegeek.org>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  

#include "sattool.h"
#include "filter.h"
#include <stdlib.h>

// Utility function for comparing doubles.
int compared(double a, CompareStep *cs, char cmp) {
	double b = cs->d;

	switch (cmp) {
	case '<':
		return a < b;
	case '>':
		return a > b;
	case '=':
		return a == b;
	default:
		return 0;
	}
}

// Utility function for comparing ints.
int comparei(int a, CompareStep *cs, char cmp) {
	int b = cs->i;

	switch (cmp) {
	case '<':
		return a < b;
	case '>':
		return a > b;
	case '=':
		return a == b;
	default:
		return 0;
	}
}

// The MergeStep functions.

int merge_or(int a, int b) {
	if (a || b) return 1;
	return 0;
}

int merge_and(int a, int b) {
	if (a && b) return 1;
	return 0;
}


// This attempts to find the appropriate CompareStep, looking it up
// in the table defined in filter_funcs.cc
Step *GetCompareStep(char *name, char connector, char *value) {
	compare_tab *ct;

	ct = compare_func_table;

	while (ct->name != NULL) {
		if (!strcmp(ct->name, name)) {
			return new CompareStep(ct->func, connector, value);
		}
		ct++;
	}

	error("Couldn't find filter function '%s'.\n", name);
	return NULL;
}

////////////////////////// CompareStep //////////////////////////////

int CompareStep::eval(Thing *t) {
	return func(t, this, cmp);
}

CompareStep::CompareStep(int(*function)(Thing *, CompareStep *,  char),
			 char cmpin, char *val) {
	func = function;
	cmp = cmpin;

	i = atoi(val);
	d = atof(val);
	str = strdup(val);
}

CompareStep::~CompareStep() {
	free(str);
}

////////////////////////// MergeStep ////////////////////////////////

int MergeStep::eval(Thing *t) {
	return func(as->eval(t), bs->eval(t));
}

MergeStep::MergeStep(Step *a, Step *b, int (*f)(int, int)) {
	as = a;
	bs = b;
	func = f;
}


// This trys to parse a filter expression from the command line.
Step *filter_setup(int argc, int optoff, char **argv) {
	char *cmd;
	Step *s;
	
	cmd = strdup("");
	
	while (optoff < argc) {
		cmd = stradd(cmd, argv[optoff]);
		cmd = stradd(cmd, " ");
		optoff++;
	}

	filter_scan(cmd);
	filter_parse((void *) &s);

	return s;
}
	
	
	
