#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

#include "bas.h"
#include "bcdfp.h"
#include "linetab.h"

void print_ref_table(void) {
	char c;
	int i, j;
	for(i = 0; i < 32768; i++) {
		if(refcounts[i]) {
			if(!lines_exist[i]) putchar('!');
			printf("%d: ", i);
			for(j = 0; j < refcounts[i]; j++) {
				printf("%d:", linerefs[i][j].lineno);
				switch(linerefs[i][j].cmd) {
					case CMD_GOTO:    c = 'G'; break;
					case CMD_GO_TO:   c = 'G'; break;
					case CMD_GOSUB:   c = 'S'; break;
					case CMD_RESTORE: c = 'R'; break;
					case CMD_TRAP:    c = 'T'; break;
					case CMD_IF:      c = 'I'; break;
					case CMD_ON:      c = 'O'; break;
					case CMD_LIST:    c = 'L'; break;
					default:          c = '?'; break;
				}
				putchar(c);
				putchar(' ');
			}
			putchar('\n');
		}
	}
}

void print_help(void) {
	printf("Usage: %s [-v] program.bas\n", self);
	exit(0);
}

void parse_args(int argc, char **argv) {
	int opt;

	while( (opt = getopt(argc, argv, "v")) != -1) {
		switch(opt) {
			case 'v': verbose = 1; break;
			default: print_help(); exit(1);
		}
	}

	if(optind >= argc)
		die("No input file given (use - for stdin).");
	else
		open_input(argv[optind]);
}

int main(int argc, char **argv) {
	set_self(*argv);
	parse_general_args(argc, argv, print_help);
	parse_args(argc, argv);

	readfile();
	parse_header();

	build_ref_table();
	print_ref_table();
	free_ref_table();

	return 0;
}
