static int handle_event(GR_EVENT *event)
{
	int i;
    switch (event->type)
    {
		case GR_EVENT_TYPE_KEY_DOWN:
			switch (event->keystroke.ch)
			{
				case 'm': /* Menu button */
					pz_close_window (tictactoe_wid);
					break;
					
				case 'l': 
					if (gameRunning == 1) {
						for (i = currSquare - 1; board[i] != '-' && i != currSquare; i--)
							if (i <= -1)
								i = 9;
						if (board[currSquare] == '-')
							drawXO(currSquare, WHITE, 'x');
						drawXO(i, GRAY, 'x');
						currSquare = i;
					}
					break;	
				case 'r': 
					if (gameRunning == 1) {
						for (i = currSquare + 1; board[i] != '-' && i != currSquare; i++)
							if (i >= 9)
								i = -1;
						if (board[currSquare] == '-')
							drawXO(currSquare, WHITE, 'x');
						drawXO(i, GRAY, 'x');
						currSquare = i;
					}
					break;						
				case 'f':
					reset_board();
					break;	
				case 'w':
					if (!gameRunning)
						reset_board();
					break;
				case '\r':
					if (gameRunning)
						playerMadeMove(currSquare);
					else
						reset_board();
					break;
				default:
					break;
			}
			break; 
    }
	return 0;
}
Exemple #2
0
// The task to process Console events
static void btn_task(iptr_t timer) {
	ticks_t start = timer_clock();
	ticks_t elapsed;
	(void)timer;

	DB2(LOG_INFO("Button timer...\r\n"));

	// LightUp all LEDS to notify calibration/reset pending
	LED_NOTIFY_ON();

	// Wait for button release or reset timeout
	while (!signal_status(SIGNAL_PLAT_BUTTON)) {
		elapsed = timer_clock() - start;
		if ( ms_to_ticks(BTN_RESET_SEC*1000) <= elapsed ) {
			// Button pressed fot t > BTN_CHECK_SEC+BTN_RESET_SEC
			reset_board();
		}
		DELAY(100);
	}

	// Button pressed BTN_CHECK_SEC < t < BTN_CHECK_SEC+BTN_RESET_SEC
	LED_NOTIFY_OFF();
	ERR_OFF();

	controlCalibration();

}
static void sudoku_replay(void)
{
	completed=0;
	reset_board();
    sudoku_draw_board();

	cur_row = 0;
	cur_col = 0;
	sudoku_draw_cursor(cur_row, cur_col);
}
void reset_game()
{
	int x, y;
	board *b = grid;

	set_big_int(&score, 0);

	reset_board(b);

	/* Add two tiles with the value two. */
	/* Do not use add_tile() as this can generate fours as well. */
	(*b)[os_get_random(0, 1)][os_get_random(0, 3)] = 2;
	(*b)[os_get_random(2, 3)][os_get_random(0, 3)] = 2;
}
Exemple #5
0
Fichier : game.c Projet : jes/zoe
/* reset the given game to the initial state */
void reset_game(Game *game) {
    int i, j;

    reset_board(&(game->board));

    /* set castling rights for each player for each side */
    for(i = 0; i < 2; i++)
        for(j = 0; j < 2; j++)
            game->can_castle[i][j] = 1;

    game->quiet_moves = 0;
    game->turn = WHITE;
    game->engine = BLACK;
    game->ep = 9;
    game->eval = 0;
}
void new_tictactoe_window(void)
{
	
    tictactoe_gc = pz_get_gc(1);       /* Get the graphics context */
	
    /* Open the window: */
    tictactoe_wid = pz_new_window (0,
								   21,
								   screen_info.cols,
								   screen_info.rows - (HEADER_TOPLINE+1),
								   draw_header,
								   handle_event);
	
	GrGetWindowInfo(tictactoe_wid, &wi); /* Get screen info */	
	
    /* Select the types of events you need for your window: */
    GrSelectEvents (tictactoe_wid, GR_EVENT_MASK_EXPOSURE|GR_EVENT_MASK_KEY_DOWN|GR_EVENT_MASK_KEY_UP);
	
    /* Display the window: */
    GrMapWindow (tictactoe_wid);
	
	reset_board(); 
}
int main() {
	reset_board();
	print_board_start();
	play_game();
	return 0;
}
Exemple #8
0
 game_core::game_core(int board_size):map_size(board_size),game_over(false),
                                 num_container(board_size)
 {
     reset_board();
     generate_random_numbers();
 }
Exemple #9
0
void loop(char *input, render_callback render_board){
	
	/* case where it's the computer's turn to move: */
	if (!is_edit_mode && (comp_color == white_to_move || automode) 
		&& !force_mode && !must_sit && !result) {
		
		/* whatever happens, never allow pondering in normal search */
		is_pondering = FALSE_C;
		
		cpu_start = clock ();
		comp_move = think ();
		cpu_end = clock();
		
		ply = 0;
		
		/* must_sit can be changed by search */
		if (!must_sit || must_go != 0)
		{
			/* check for a game end: */
			if ((
				 ((Variant == Losers || Variant == Suicide)
				  && 
				  ((result != white_is_mated) && (result != black_is_mated)))
				 || 
				 ((Variant == Normal || Variant == Crazyhouse || Variant == Bughouse)
				  && ((comp_color == 1 && result != white_is_mated) 
					  ||
					  (comp_color == 0 && result != black_is_mated)
					  ))) 
				&& result != stalemate 
				&& result != draw_by_fifty 
				&& result != draw_by_rep) 
			{
				
				comp_to_coord (comp_move, output);
				
				hash_history[move_number] = hash;
				
				game_history[move_number] = comp_move;
				make (&comp_move, 0);
				
				/* saves state info */
				game_history_x[move_number++] = path_x[0];
				
				userealholdings = 0;
				must_go--;
				
				/* check to see if we draw by rep/fifty after our move: */
				if (is_draw ()) {
					result = draw_by_rep;
				}
				else if (fifty > 100) {
					result = draw_by_fifty;
				}
				
				root_to_move ^= 1;
				
				reset_piece_square ();
				
				if (book_ply < 40) {
					if (!book_ply) {
						strcpy(opening_history, output);
					}
					else {
						strcat(opening_history, output);
					}
				}
				
				book_ply++;
				
				printf ("\nNodes: %d (%0.2f%% qnodes)\n", nodes,
						(float) ((float) qnodes / (float) nodes * 100.0));
				
				elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
				nps = (float) nodes/(float) elapsed;
				
				if (!elapsed)
					printf ("NPS: N/A\n");
				else
					printf ("NPS: %d\n", (int32_t) nps);
				
				printf("ECacheProbes : %d   ECacheHits : %d   HitRate : %f%%\n", 
					   ECacheProbes, ECacheHits, 
					   ((float)ECacheHits/((float)ECacheProbes+1)) * 100);
				
				printf("TTStores : %d TTProbes : %d   TTHits : %d   HitRate : %f%%\n", 
					   TTStores, TTProbes, TTHits, 
					   ((float)TTHits/((float)TTProbes+1)) * 100);
				
				printf("NTries : %d  NCuts : %d  CutRate : %f%%  TExt: %d\n", 
					   NTries, NCuts, (((float)NCuts*100)/((float)NTries+1)), TExt);
				
				printf("Check extensions: %d  Razor drops : %d  Razor Material : %d\n", ext_check, razor_drop, razor_material);
				
				printf("EGTB Hits: %d  EGTB Probes: %d  Efficiency: %3.1f%%\n", EGTBHits, EGTBProbes,
					   (((float)EGTBHits*100)/(float)(EGTBProbes+1)));
				
				printf("Move ordering : %f%%\n", (((float)FHF*100)/(float)(FH+1)));
				
				printf("Material score: %d   Eval : %d  White hand: %d  Black hand : %d\n", 
					   Material, (int)eval(), white_hand_eval, black_hand_eval);
				
				printf("Hash : %X  HoldHash : %X\n", (unsigned)hash, (unsigned)hold_hash);
				
				/* check to see if we mate our opponent with our current move: */
				if (!result) {
					if (xb_mode) {
						
						/* safety in place here */
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("move %s\n", output);
						
						if (Variant == Bughouse)
						{
							CheckBadFlow(FALSE_C);
						}	
					}
					else {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("\n%s\n", output);
					}
				}
				else {
					if (xb_mode) {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("move %s\n", output);
					}
					else {
						if (comp_move.from != dummy.from || comp_move.target != dummy.target)
							printf ("\n%s\n", output);
					}
					if (result == white_is_mated) {
						printf ("0-1 {Black Mates}\n");
					}
					else if (result == black_is_mated) {
						printf ("1-0 {White Mates}\n");
					}
					else if (result == draw_by_fifty) {
						printf ("1/2-1/2 {Fifty move rule}\n");
					}
					else if (result == draw_by_rep) {
						printf ("1/2-1/2 {3 fold repetition}\n");
					}
					else {
						printf ("1/2-1/2 {Draw}\n");
					}
					automode = 0;
				}
			}
			/* we have been mated or stalemated: */
			else {
				if (result == white_is_mated) {
					printf ("0-1 {Black Mates}\n");
				}
				else if (result == black_is_mated) {
					printf ("1-0 {White Mates}\n");
				}
				else if (result == draw_by_fifty) {
					printf ("1/2-1/2 {Fifty move rule}\n");
				}
				else if (result == draw_by_rep) {
					printf ("1/2-1/2 {3 fold repetition}\n");
				}
				else {
					printf ("1/2-1/2 {Draw}\n");
				}
				automode = 0;
			}
		}
	}
	
	/* get our input: */
	if (!xb_mode) {
		if (show_board) {
			printf ("\n");
			display_board (stdout, 1-comp_color);
			render_board(1-comp_color);
		}
		if (!automode)
		{
			printf ("Sjeng: ");
			//readStr(input, STR_BUFF);
			//			rinput (input, STR_BUFF, stdin);
		}
	}
	else {
		/* start pondering */
		
		if ((must_sit || (allow_pondering && !is_edit_mode && !force_mode &&
						  move_number != 0) || is_analyzing) && !result && !automode)
		{
			is_pondering = TRUE_C;
			think();
			is_pondering = FALSE_C;
			
			ply = 0;
		}
		if (!automode)
		{
			//rinput (input, STR_BUFF, stdin);
		}
	}
	
	/* check to see if we have a move.  If it's legal, play it. */
	if (!is_edit_mode && is_move (&input[0])) {
		if (verify_coord (input, &human_move)) {
			
			if (confirm_moves) printf ("Legal move: %s\n", input);
			
			game_history[move_number] = human_move;
			hash_history[move_number] = hash;
			
			make (&human_move, 0);
			game_history_x[move_number++] = path_x[0];
			
			reset_piece_square ();
			
			root_to_move ^= 1;
			
			if (book_ply < 40) {
				if (!book_ply) {
					strcpy(opening_history, input);
				}
				else {
					strcat(opening_history, input);
				}
			}
			
			book_ply++;
			
			if (show_board) {
				printf ("\n");
				display_board (stdout, 1-comp_color);
				render_board(1-comp_color);
			}
		}
		else {
			printf ("Illegal move: %s\n", input);
		}
	}
	else {
		
		/* make everything lower case for convenience: */
		/* GCP: except for setboard, which is case sensitive */
		if (!strstr(input, "setboard")){
			for (p = input; *p; p++) {
				*p = tolower (*p);
			}
		}
		
		/* command parsing: */
		if (!strcmp (input, "quit") || (!input[0] && feof(stdin))) {
			safe_fclose(lrn_standard);
			safe_fclose(lrn_zh);
			safe_fclose(lrn_suicide);
			safe_fclose(lrn_losers);
			free_hash();
			free_ecache();
			exit (EXIT_SUCCESS);
		}
		else if (!strcmp (input, "exit"))
		{
			if (is_analyzing)
			{
				is_analyzing = FALSE_C;
				is_pondering = FALSE_C;
				time_for_move = 0;
			}
			else
			{
				safe_fclose(lrn_standard);
				safe_fclose(lrn_zh);
				safe_fclose(lrn_suicide);
				safe_fclose(lrn_losers);
				free_hash();
				free_ecache();
				exit (EXIT_SUCCESS);
			}
		}
		else if (!strcmp (input, "diagram") || !strcmp (input, "d")) {
			toggle_bool_c (&show_board);
		}
		else if (!strncmp (input, "perft", 5)) {
			sscanf (input+6, "%d", &depth);
			raw_nodes = 0;
			xstart_time = rtime();
			perft (depth);
			printf ("Raw nodes for depth %d: %d\n", depth, raw_nodes);
			printf("Time : %.2f\n", (float)rdifftime(rtime(), xstart_time)/100.);
		}
		else if (!strcmp (input, "confirm_moves")) {
			confirm_moves = TRUE_C;
			printf("Will now confirm moves.\n");
		}
		else if (!strcmp (input, "new")) {
			
			if (xb_mode)
			{
				printf("tellics set 1 Sjeng " VERSION " (2001-9-28/%s)\n", setcode);
			}
			
			if (!is_analyzing)
			{	
				memcpy(material, std_material, sizeof(std_material));
				Variant = Normal;
				
				// memcpy(material, zh_material, sizeof(zh_material));
				//Variant = Crazyhouse;
				
				init_game ();
				initialize_hash();
				
				if (!braindeadinterface)
				{
					clear_tt();
					init_book();
					reset_ecache();
				}
				
				force_mode = FALSE_C;
				must_sit = FALSE_C;
				go_fast = FALSE_C;
				piecedead = FALSE_C;
				partnerdead = FALSE_C;
				kibitzed = FALSE_C;
				fixed_time = FALSE_C;
				
				root_to_move = WHITE;
				
				comp_color = 0;
				move_number = 0;
				hash_history[move_number] = 0;
				bookidx = 0;
				my_rating = opp_rating = 2000;
				must_go = 0;
				tradefreely = 1;
				automode = 0;
				
				CheckBadFlow(TRUE_C);
				ResetHandValue();
			}
			else
			{
				init_game ();
				move_number = 0;
			}
			
		}
		else if (!strcmp (input, "xboard")) {
			xb_mode = TRUE_C;
			toggle_bool_c (&show_board);
			signal (SIGINT, SIG_IGN);
			printf ("\n");
			
			/* Reset f5 in case we left with partner */
			printf("tellics set f5 1=1\n");
			
			BegForPartner();
		}
		else if (!strcmp (input, "nodes")) {
			printf ("Number of nodes: %d (%0.2f%% qnodes)\n", nodes,
					(float) ((float) qnodes / (float) nodes * 100.0));
		}
		else if (!strcmp (input, "nps")) {
			elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
			nps = (float) nodes/(float) elapsed;
			if (!elapsed)
				printf ("NPS: N/A\n");
			else
				printf ("NPS: %d\n", (int32_t) nps);
		}
		else if (!strcmp (input, "post")) {
			toggle_bool_c (&post);
			if (xb_mode)
				post = TRUE_C;
		}
		else if (!strcmp (input, "nopost")) {
			post = FALSE_C;
		}
		else if (!strcmp (input, "random")) {
			return;
		}
		else if (!strcmp (input, "hard")) {
			
			allow_pondering = TRUE_C;
			
			return;
		}
		else if (!strcmp (input, "easy")) {
			
			allow_pondering = FALSE_C;
			
			return;
		}
		else if (!strcmp (input, "?")) {
			return;
		}
		else if (!strcmp (input, "white")) {
			white_to_move = 1;
			root_to_move = WHITE;
			comp_color = 0;
		}
		else if (!strcmp (input, "black")) {
			white_to_move = 0;
			root_to_move = BLACK;
			comp_color = 1;
		}
		else if (!strcmp (input, "force")) {
			force_mode = TRUE_C;
		}
		else if (!strcmp (input, "eval")) {
			check_phase();
			printf("Eval: %d\n", (int)eval());
		}
		else if (!strcmp (input, "go")) {
			comp_color = white_to_move;
			force_mode = FALSE_C;
		}
		else if (!strncmp (input, "time", 4)) {
			sscanf (input+5, "%d", &time_left);
		}
		else if (!strncmp (input, "otim", 4)) {
			sscanf (input+5, "%d", &opp_time);
		}
		else if (!strncmp (input, "level", 5)) {
			if (strstr(input+6, ":"))
			{
				/* time command with seconds */
				sscanf (input+6, "%d %d:%d %d", &moves_to_tc, &min_per_game, 
						&sec_per_game, &inc);
				time_left = (min_per_game*6000) + (sec_per_game * 100);
				opp_time = time_left;
			}
			else
			{
				/* extract the time controls: */
				sscanf (input+6, "%d %d %d", &moves_to_tc, &min_per_game, &inc);
				time_left = min_per_game*6000;
				opp_time = time_left;
			}
			fixed_time = FALSE_C;
			time_cushion = 0; 
		}
		else if (!strncmp (input, "rating", 6)) {
			sscanf (input+7, "%d %d", &my_rating, &opp_rating);
			if (my_rating == 0) my_rating = 2000;
			if (opp_rating == 0) opp_rating = 2000;
		}
		else if (!strncmp (input, "holding", 7)) {
			ProcessHoldings(input);     
		}
		else if (!strncmp (input, "variant", 7)) {
			if (strstr(input, "normal"))
			{
				Variant = Normal;
				memcpy(material, std_material, sizeof(std_material));
				init_book();
			}
			else if (strstr(input, "crazyhouse"))
			{
				Variant = Crazyhouse;
				memcpy(material, zh_material, sizeof(zh_material));
				init_book();
			}
			else if (strstr(input, "bughouse"))
			{
				Variant = Bughouse;
				memcpy(material, zh_material, sizeof(zh_material));
				init_book();
			}
			else if (strstr(input, "suicide"))
			{
				Variant = Suicide;
				Giveaway = FALSE_C;
				memcpy(material, suicide_material, sizeof(suicide_material));
				init_book();
			}
			else if (strstr(input, "giveaway"))
			{
				Variant = Suicide;
				Giveaway = TRUE_C;
				memcpy(material, suicide_material, sizeof(suicide_material));
				init_book();
			}
			else if (strstr(input, "losers"))
			{
				Variant = Losers;
				memcpy(material, losers_material, sizeof(losers_material));
				init_book();
			}
			
			initialize_hash();
			clear_tt();
			reset_ecache();
			
		}
		else if (!strncmp (input, "analyze", 7)) {
			is_analyzing = TRUE_C;
			is_pondering = TRUE_C;
			think();
			ply = 0;
		}
		else if (!strncmp (input, "undo", 4)) {
			printf("Move number : %d\n", move_number);
			if (move_number > 0)
			{
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
				root_to_move ^= 1;
			}
			result = 0;
		}
		else if (!strncmp (input, "remove", 5)) {
			if (move_number > 1)
			{
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
				
				path_x[0] = game_history_x[--move_number];
				unmake(&game_history[move_number], 0);
				reset_piece_square();
			}
			result = 0;
		}
		else if (!strncmp (input, "edit", 4)) {
			is_edit_mode = TRUE_C;
			edit_color = WHITE;
		}
		else if (!strncmp (input, ".", 1) && is_edit_mode) {
			is_edit_mode = FALSE_C;
			if (wking_loc == 30) white_castled = no_castle;
			if (bking_loc == 114) black_castled = no_castle;
			book_ply = 50;
			ep_square = 0;
			move_number = 0;
			memset(opening_history, 0, sizeof(opening_history));
			clear_tt();
			initialize_hash();
			reset_piece_square();
		}
		else if (is_edit_mode && !strncmp (input, "c", 1)) {
			if (edit_color == WHITE) edit_color = BLACK; else edit_color = WHITE;
		}
		else if (is_edit_mode && !strncmp (input, "#", 1)) {
			reset_board();
			move_number = 0;
		}
		else if (is_edit_mode 
				 && isalpha(input[0]) 
				 && isalpha(input[1]) 
				 && isdigit(input[2])) {
			PutPiece(edit_color, input[0], input[1], input[2]);
		}
		else if (!strncmp (input, "partner", 7)) {
			HandlePartner(input+7);
		}
		else if (!strncmp (input, "$partner", 8)) {
			HandlePartner(input+8);
		}
		else if (!strncmp (input, "ptell", 5)) {
			HandlePtell(input);
		}
		else if (!strncmp (input, "test", 4)) {
			run_epd_testsuite();
		}
		else if (!strncmp (input, "st", 2)) {
			sscanf(input+3, "%d", &fixed_time);
			fixed_time = fixed_time * 100;
		}
		else if (!strncmp (input, "book", 4)) {
			build_book();
		}
		else if (!strncmp (input, "speed",  5)) {
			speed_test();
		}
		else if (!strncmp (input, "result", 6)) {
			if (cfg_booklearn)
			{
				if (strstr (input+7, "1-0"))
				{
					if (comp_color == 1)
						book_learning(WIN);
					else
						book_learning(LOSS);
				}
				else if (strstr(input+7, "0-1"))
				{
					if (comp_color == 1)
						book_learning(LOSS);
					else
						book_learning(WIN);
				}
				else if (strstr(input+7, "1/2-1/2"))
				{
					book_learning(DRAW);
				};
			}
		}
		else if (!strncmp (input, "prove", 5)) {
			printf("\nMax time to search (s): ");
			start_time = rtime();
			rinput(readbuff, STR_BUFF, stdin);
			pn_time = atoi(readbuff) * 100;
			printf("\n");
			proofnumbersearch();      
		}
		else if (!strncmp (input, "ping", 4)) {
			sscanf (input+5, "%d", &pingnum);
			printf("pong %d\n", pingnum);
		}
		else if (!strncmp (input, "fritz", 5)) {
			braindeadinterface = TRUE_C;
		}
		else if (!strncmp (input, "reset", 5)) {
			
			memcpy(material, std_material, sizeof(std_material));
			Variant = Normal;
			
			init_game ();
			initialize_hash();
			
			clear_tt();
			init_book();
			reset_ecache();       
			
			force_mode = FALSE_C;
			fixed_time = FALSE_C;
			
			root_to_move = WHITE;
			
			comp_color = 0;
			move_number = 0;
			bookidx = 0;
			my_rating = opp_rating = 2000;
		}
		else if (!strncmp (input, "setboard", 8)) {
			setup_epd_line(input+9);
		}
		else if (!strncmp (input, "buildegtb", 9)) {
			Variant = Suicide;
			gen_all_tables();
		}
		else if (!strncmp (input, "lookup", 6)) {
			Variant = Suicide;
			printf("Value : %d\n", egtb(white_to_move));
		}
		else if (!strncmp (input, ".", 1)) {
			/* periodic updating and were not searching */
			/* most likely due to proven mate */
			return;
		}
		else if (!strncmp (input, "sd", 2)) {
			sscanf(input+3, "%d", &maxdepth);
			printf("New max depth set to: %d\n", maxdepth);
			return;
		}
		else if (!strncmp (input, "auto", 4)) {
			automode = 1;
			return;
		}
		else if (!strncmp (input, "protover", 8)) {
			printf("feature ping=1 setboard=1 playother=0 san=0 usermove=0 time=1\n");
			printf("feature draw=0 sigint=0 sigterm=0 reuse=1 analyze=1\n");
			printf("feature myname=\"Sjeng " VERSION "\"\n");
			printf("feature variants=\"normal,bughouse,crazyhouse,suicide,giveaway,losers\"\n");
			printf("feature colors=1 ics=0 name=0 pause=0 done=1\n");
			xb_mode = 2;
		}
		else if (!strncmp (input, "accepted", 8)) {
			/* do nothing as of yet */
		}
		else if (!strncmp (input, "rejected", 8)) {
			printf("Interface does not support a required feature...expect trouble.\n");
		}
		else if (!strncmp (input, "warranty", 8)) {
			printf("\n  BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n"
				   "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\n"
				   "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n"
				   "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n"
				   "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n"
				   "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\n"
				   "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\n"
				   "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n"
				   "REPAIR OR CORRECTION.\n"
				   "\n");
			printf("  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n"
				   "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n"
				   "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n"
				   "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n"
				   "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n"
				   "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n"
				   "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n"
				   "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n"
				   "POSSIBILITY OF SUCH DAMAGES.\n\n");
			
		}
		else if (!strncmp (input, "distribution", 12)) {
			printf("\n  You may copy and distribute verbatim copies of the Program's\n"
				   "source code as you receive it, in any medium, provided that you\n"
				   "conspicuously and appropriately publish on each copy an appropriate\n"
				   "copyright notice and disclaimer of warranty; keep intact all the\n"
				   "notices that refer to this License and to the absence of any warranty;\n"
				   "and give any other recipients of the Program a copy of this License\n"
				   "along with the Program.\n"
				   "\n"
				   "You may charge a fee for the physical act of transferring a copy, and\n"
				   "you may at your option offer warranty protection in exchange for a fee.\n\n");
			
		}
		else if (!strcmp (input, "help")) {
			printf ("\n%s\n\n", divider);
			printf ("diagram/d:       toggle diagram display\n");
			printf ("exit/quit:       terminate Sjeng\n");
			printf ("go:              make Sjeng play the side to move\n");
			printf ("new:             start a new game\n");
			printf ("level <x>:       the xboard style command to set time\n");
			printf ("  <x> should be in the form: <a> <b> <c> where:\n");
			printf ("  a -> moves to TC (0 if using an ICS style TC)\n");
			printf ("  b -> minutes per game\n");
			printf ("  c -> increment in seconds\n");
			printf ("nodes:           outputs the number of nodes searched\n");
			printf ("nps:             outputs Sjeng's NPS in search\n");
			printf ("perft <x>:       compute raw nodes to depth x\n");
			printf ("post:            toggles thinking output\n");
			printf ("xboard:          put Sjeng into xboard mode\n");
			printf ("test:            run an EPD testsuite\n");
			printf ("speed:           test movegen and evaluation speed\n");
			printf ("warranty:        show warranty details\n");
			printf ("distribution:    show distribution details\n");
			printf( "proof:           try to prove or disprove the current pos\n");
			printf( "sd <x>:          limit thinking to depth x\n");
			printf( "st <x>:          limit thinking to x centiseconds\n");
			printf( "setboard <FEN>:  set board to a specified FEN string\n");
			printf( "undo:            back up a half move\n");
			printf( "remove:          back up a full move\n");
			printf( "force:           disable computer moving\n");
			printf( "auto:            computer plays both sides\n");
			printf ("\n%s\n\n", divider);
			
			show_board = 0;
		}
		else if (!xb_mode) {
			printf ("Illegal move: %s\n", input);
		}
		
	}
	
}
int main()
{


/*
    DECLARE LOCAL DATA AREAS:
*/

    char cmd_buff[80];		/* command line input buffer */
    unsigned finished, finished1; /* flag to exit program */
    int hstatus;		/* returned status of routines */
    int item;			/* menu item selection variable */
    float ideal_volt_span;	/* storage span info */
    float f_data;
    long addr;			/* board address */
    int flag;			/* general flag for exiting loops */
    int i,j;			/* loop index */
    int temp;
    struct conf_blk c_block;	/* configuration block */
    int hflag;                  /* interrupt handler installed flag */
    struct handler_data hdata;  /* interrupt data structure (see exception.h) */
    float fb[MAXSIZE];		/* storage buffer for floats */
    float fs, zs, slope, ge;

/*
    ENTRY POINT OF ROUTINE:
    INITIALIZATION
*/

    flag = 0;		/* indicate board address not yet assigned */
    finished = 0;	/* indicate not finished with program */
    hflag = 0;          /* indicate interrupt handler not installed yet */

    for(j = 0; j < MAXSIZE; j++)	/* clear float buffer */
    	fb[j] = 0.0;
    
    for(i = 0; i < NUM_CHAN;i++)
    {
      for(j = 0; j < MAXSIZE; j++)
      {
	c_block.ideal_data[i][j] = 0;	/* clear ideal data buffer */
	c_block.cor_data[i][j] = 0;	/* clear corrected data buffer */
      }
      c_block.coef_bufu10[i][0] = c_block.coef_bufu10[i][1] = 0;
      c_block.coef_bufb10[i][0] = c_block.coef_bufb10[i][1] = 0;
      c_block.coef_bufb5[i][0]  = c_block.coef_bufb5[i][1] = 0;

      /* Initialize the Configuration Parameter Block to default values */

      c_block.mode[i] = 0;		/* mode */
      c_block.trigger[i] = 0;		/* default triggering */
      c_block.interrupt_enable[i] = 0;	/* interrupt enable */
      c_block.threshold[i] = 0;	/* empty threshold */
      c_block.range[i] = BIPOLAR_10;/* channel range storage */
      c_block.prescaler[i] = 53;	/* timer prescaler */
      c_block.counter[i] = 1;		/* conversion counter */
      c_block.write_size[i] = 1;
    }
    c_block.interrupt_flag = 0;	/* default to no interrupts */
    c_block.current_channel = 0;	/* default channel */

    c_block.interrupt_vector = VECTOR;	/* default interrupt vector */
    c_block.bCarrier = FALSE;		/* indicate no carrier initialized and set up yet */
    c_block.bInitialized = FALSE;	/* indicate not ready to talk to IP */
    c_block.slotLetter = SLOT_A;
    c_block.nHandle = 0;		/* make handle to a closed carrier board */

    hdata.h_pid = getpid();		/* save it in the interrupt handler data structure */
    hdata.hd_ptr = (char *)&c_block;/* put in address of c_block structure also */

/*
	Initialize the Carrier library
*/
    if(InitCarrierLib() != S_OK)
    {
	printf("\nUnable to initialize the carrier library. Exiting program.\n");
	exit(0);
    }

/*
	Open an instance of a carrier device 
*/
    if(CarrierOpen(0, &c_block.nHandle) != S_OK)
    {
	printf("\nUnable to Open instance of carrier.\n");
	finished = 1;	 /* indicate finished with program */
    }
    else
	flag = 1;


/* Enter main loop */

    while(!finished)
    {
      printf("\nIP236 Library Demonstration  Rev. A \n\n");
      printf(" 1. Exit this Program\n");
      printf(" 2. Set Board Base Address\n");
      printf(" 3. Set IP Slot Letter\n");
      printf(" 4. Read Module I.D./Display Event Status\n");
      printf(" 5. Read Calibration Coefficients\n");
      printf(" 6. Set/Change Channel Number\n");
      printf(" 7. Issue Software Reset to Board\n");
      printf(" 8. Set Up Configuration Parameters\n");
      printf(" 9. Configure Channel\n");
      printf("10. Enter/Change Output Values\n");
      printf("11. Correct Output Values\n");
      printf("12. Write Values to Output FIFO\n");
      printf("13. N/A\n");
      printf("14. Start/Stop Conversions\n");
      printf("15. View Data Buffers & Offset/Gain Coefficients\n");
      printf("16. Clear All Data Buffers\n");
      printf("17. Modify Offset/Gain Coefficients\n");
      printf("18. N/A\n\n");
      printf("Select: ");
      scanf("%d",&item);

/*
    perform the menu item selected.
*/  

      switch(item)
      {
       case 1: /* exit program command */
            printf("Exit program(y/n)?: ");
            scanf("%s",cmd_buff);
            if( cmd_buff[0] == 'y' || cmd_buff[0] == 'Y' )
                finished++;
            break;
        

	case 2: /* set board address command */
	    do 
	    {
		if(flag == 0)
		{
		  printf("\n\nenter base address of carrier board in hex: ");
		  scanf("%lx",&addr);
		  /* Set Carrier Address for Open Carrier Device */
		  SetCarrierAddress(c_block.nHandle, addr);	/* Set Carrier Address */
		}
		GetCarrierAddress(c_block.nHandle, &addr);	/* Read back carrier address */
		printf("address: %lX\n",addr);
		printf("is this value correct(y/n)?: ");
		scanf("%s",cmd_buff);
		if( cmd_buff[0] == 'y' || cmd_buff[0] == 'Y' )
		{
          SetCarrierAddress(c_block.nHandle, addr);	/* Set Carrier Address */
		  if(CarrierInitialize(c_block.nHandle) == S_OK)/* Initialize Carrier */
		  {
		        c_block.bCarrier = TRUE;
			SetInterruptLevel(c_block.nHandle, INTERRUPT_LEVEL);/* Set carrier interrupt level */
		  }
		  flag = 1;
		}
		else
		  flag = 0;

            }while( cmd_buff[0] != 'y' && cmd_buff[0] != 'Y' );
        break;


	  case 3: /* set IP Slot Letter */
		if(flag == 0 || c_block.bCarrier == FALSE)
			printf("\n>>> ERROR: BOARD ADDRESS NOT SET <<<\n");
		else
		{
			printf("\n\nEnter IP slot letter (A, B etc...): ");
			scanf("%s",cmd_buff);
			cmd_buff[0] = toupper(cmd_buff[0]);
			if(cmd_buff[0] < 'A' || cmd_buff[0] > GetLastSlotLetter())
			{
				printf("\nInvalid Slot Letter!\n");
				c_block.bCarrier = FALSE;
			}
			else
			{
				c_block.slotLetter = cmd_buff[0];
																					
/*
	Get the IPACK's base address based on the Slot letter,
        and initialize the IPACK's data structure with the returned address
*/
				if(GetIpackAddress(c_block.nHandle, c_block.slotLetter, &addr) != S_OK)
				{
					printf("\nUnable to Get Ipack Address.\n");
					c_block.bInitialized = FALSE;
				}
				else	              
				{	
			            c_block.brd_ptr = (struct map236 *)addr;
					c_block.bInitialized = TRUE;
				}
			}
		}
	  break;


        case 4: /* Read ID Prom */
            if(!c_block.bInitialized)
                printf("\n>>> ERROR: BOARD ADDRESS NOT SET <<<\n");
            else
		 readid(&c_block);
        break;

        case 5: /* Read calibration coeficients*/
            if(!c_block.bInitialized)
                printf("\n>>> ERROR: BOARD ADDRESS NOT SET <<<\n");
            else
	      {
	       for( i = 0; i < NUM_CHAN; i++ )
	       {
		  c_block.coef_bufu10[i][0] = (word)ReadOffsetError( &c_block, i, UNIPOLAR_10 );
                  c_block.coef_bufu10[i][1] = (word)ReadGainError( &c_block, i, UNIPOLAR_10 );

                  c_block.coef_bufb5[i][0]  = (word)ReadOffsetError( &c_block, i, BIPOLAR_5 );
                  c_block.coef_bufb5[i][1]  = (word)ReadGainError( &c_block, i, BIPOLAR_5 );

                  c_block.coef_bufb10[i][0] = (word)ReadOffsetError( &c_block, i, BIPOLAR_10 );
                  c_block.coef_bufb10[i][1] = (word)ReadGainError( &c_block, i, BIPOLAR_10 );
	       }
	    }
            break;    

        case 6: /* channel number */
	    finished1 = 0;
	    while(!finished1)
	    {
 	       printf("\n\nChannel: %x\n\n",c_block.current_channel);
	       printf(" 1. Return to Previous Menu\n");
	       printf(" 2. Change Channel Number\n");
	       printf("\nSelect: ");
	       scanf("%d",&temp);
	       switch(temp)
	       {
		 case 1: /* return to previous menu */
		    finished1++;
		 break;

		 case 2: /* Select channel */
		     printf("New Channel Number (0 - %d)\n",(NUM_CHAN - 1));
		     c_block.current_channel = (int)get_param();
		 break;
	       }
	    }
	    break;

        case 7: /* Reset channel */
            if(!c_block.bInitialized)
                printf("\n>>> ERROR: BOARD ADDRESS NOT SET <<<\n");
            else
		    reset_board(&c_block);
        break;

        case 8: /* set up configuration block parameters */
	      setconf236(&c_block);
        break;

        case 9: /* configure */
            if(!c_block.bInitialized)
                printf("\n>>> ERROR: BOARD ADDRESS NOT SET <<<\n");
            else
	          cnfg236(&c_block);
        break;

        case 10: /* Enter Ideal Data */
	    finished1 = 0;
	    while(!finished1)
	    {
	 	printf("\n\nChannel: %x\n\n",c_block.current_channel);
		printf(" 1. Return to Previous Menu\n");
		printf(" 2. Enter Value(s)\n");
		printf("\nSelect: ");
		scanf("%d",&temp);
		switch(temp)
		{
			case 1: /* return to previous menu */
			    finished1++;
			break;

			case 2: /* enter channel values */
	 		    printf("\nEnter desired voltage: ie: 1.25, follow each with CR %d max)",MAXSIZE);
			    printf("\n  CR alone moves to next value,");
       			    printf("\n  SPACE CR moves to previous value,");
	       		    printf("\n  Q CR quits:\n\n");
			    gets( &cmd_buff[0] );	      /* purge input stream */
         	 	    for( j = 0; j < MAXSIZE; j++ )
           	            {
              		      printf("[%02X]: %f ",j,fb[j]);
              		      gets( &cmd_buff[0] );

	                      if(( cmd_buff[0] == 'Q') || ( cmd_buff[0] == 'q'))
	                           break;
	                      else
	                      {
	                        if( cmd_buff[0] == ' ' )      /* check for space */
 	                            j -= 2; 	   	      /* back up if so */

	                        if( cmd_buff[0] != 0 && cmd_buff[0] != ' ' ) /* check for CR */
	                            sscanf( &cmd_buff[0], "%f", &fb[j]);  /* save */
 	                      }
  	                    }

                            for( i = 0; i < j; i++ )	/* convert data */
                            {
			      if(c_block.range[c_block.current_channel] == BIPOLAR_10)
 			         ideal_volt_span = VOLT_SPAN_B10;
			      else	
			         ideal_volt_span = VOLT_SPAN;

			      f_data = (((float)65536 * fb[i]) / ideal_volt_span);

			      if( c_block.range[c_block.current_channel] == UNIPOLAR_10 )
			    	f_data -= 32768.0;

			      if( f_data < 0.0)		/* round */
		 		f_data -= 0.5;
		 	      else
				f_data += 0.5;

			      if( f_data > 32767.0 )	/* clip high */
				f_data = 32767.0;

			      if( f_data < -32768.0 )	/* clip low */
				f_data = -32768.0;

			      c_block.ideal_data[c_block.current_channel][i] = (short)f_data;
			    }

			    c_block.write_size[c_block.current_channel] = j;
			break;
		}
	    }
        break;

        case 11: /* Correct Data */
	    cd236(&c_block);		/* correct data */ 
        break;

        case 12: /* Write Data to output */
            if(!c_block.bInitialized)
                printf("\n>>> ERROR: BOARD ADDRESS NOT SET <<<\n");
            else
	      {
	      finished1 = 0;
	      while(!finished1)
	      {

 	        printf("\n\nChannel: %x\n\n",c_block.current_channel);
	        printf(" 1. Return to Previous Menu\n");
	        printf(" 2. Write Ideal Data Values\n");
	        printf(" 3. Write Corrected Data Values\n");
	        printf("\nSelect: ");
	        scanf("%d",&temp);
	        switch(temp)
	       { 
		      case 1: /* return to previous menu */
			    finished1++;
	   	      break;
		      case 2: /* Ideal */
			    c_block.current_ptr[c_block.current_channel] =
			    c_block.head_ptr[c_block.current_channel] = &c_block.ideal_data[c_block.current_channel][0];
			    c_block.tail_ptr[c_block.current_channel] = &c_block.ideal_data[c_block.current_channel][0] + c_block.write_size[c_block.current_channel];
			    wro236(&c_block, c_block.current_channel);
		      break;
		      case 3: /* Corrected */
			    c_block.current_ptr[c_block.current_channel] =
			    c_block.head_ptr[c_block.current_channel] = &c_block.cor_data[c_block.current_channel][0];
			    c_block.tail_ptr[c_block.current_channel] = &c_block.cor_data[c_block.current_channel][0] + c_block.write_size[c_block.current_channel];
			    wro236(&c_block, c_block.current_channel);
		      break;
	       }
	      }
	    }
	break;

        case 13:     /* attach exception handler */

            if(!c_block.bInitialized)
                printf("\n>>> ERROR: BOARD ADDRESS NOT SET <<<\n");
        break;

        case 14:  /* Start Conversion */
	    finished1 = 0;
	    while(!finished1)
	    {
 	       printf("\n\nChannel: %x\n\n",c_block.current_channel);
	       printf(" 1. Return to Previous Menu\n");
	       printf(" 2. Start Current Channel\n");
	       printf(" 3. Start Multiple Channels\n");
	       printf(" 4. Stop/Reset Current Channel\n");
	       printf(" 5. Stop/Reset Multiple Channels\n");
	       printf("\nSelect: ");
	       scanf("%d",&temp);
	       switch(temp)
	       { 
		      case 1: /* return to previous menu */
			    finished1++;
	   	      break;
		      case 2: /* Current channel */
		           start_single(&c_block);
		      break;
		      case 3: /* multiple channels */
		          printf("8 Bit Channel Mask to Start\n");
		          start_multiple(&c_block,(byte)get_param());
		      break;
		      case 4: /* Current channel */
			   reset_channel(&c_block);
		      break;
		      case 5: /* stop multiple channels */
		          printf("8 Bit Channel Mask to Stop\n");
		          stop_multiple(&c_block,(byte)get_param());
		      break;
	       }
	    }
           break;

        case 15:	/* Display Ideal/Corrected Data, Offset/Gain Coefficients */
previous:
	    printf("\n\nChannel: %1d  Range: ",c_block.current_channel);

	    if(c_block.range[c_block.current_channel] == BIPOLAR_5)
		   printf("Bipolar 5  ");
	    if(c_block.range[c_block.current_channel] == BIPOLAR_10)
		   printf("Bipolar 10 ");
	    if(c_block.range[c_block.current_channel] == UNIPOLAR_10)
		   printf("Unipolar 10");

	    printf("  Coefficients: Offset ");
	    if(c_block.range[c_block.current_channel] == BIPOLAR_5)
		   printf("%04X",(c_block.coef_bufb5[c_block.current_channel][0] & 0xFFFF));
	    if(c_block.range[c_block.current_channel] == BIPOLAR_10)
		   printf("%04X",(c_block.coef_bufb10[c_block.current_channel][0] & 0xFFFF));
	    if(c_block.range[c_block.current_channel] == UNIPOLAR_10)
		   printf("%04X",(c_block.coef_bufu10[c_block.current_channel][0] & 0xFFFF));

	    printf("  Gain ");
	    if(c_block.range[c_block.current_channel] == BIPOLAR_5)
		   printf("%04X",(c_block.coef_bufb5[c_block.current_channel][1] & 0xFFFF));
	    if(c_block.range[c_block.current_channel] == BIPOLAR_10)
		   printf("%04X",(c_block.coef_bufb10[c_block.current_channel][1] & 0xFFFF));
	    if(c_block.range[c_block.current_channel] == UNIPOLAR_10)
		   printf("%04X",(c_block.coef_bufu10[c_block.current_channel][1] & 0xFFFF));

	    printf("\n\nIdeal Data");
	    for( j = 0; j < 8; j++)
	    {
		printf("\n[%02X]",j*8);
		for(i = 0; i < 8; i++)
		      printf("    %04x",c_block.ideal_data[c_block.current_channel][j*8+i] & 0xFFFF);
	    }

	    printf("\n\nCorrected Data ");
	    for( j = 0; j < 8; j++)
	    {
		printf("\n[%02X]",j*8);
		for(i = 0; i < 8; i++)
		      printf("    %04x",c_block.cor_data[c_block.current_channel][j*8+i] & 0xFFFF);
	    }

	    printf("\n 1. Return to Previous Menu");
	    printf("\n 2. View Next Data Block");
	    printf("\nSelect: ");
	    scanf("%d",&temp);
	    if(temp == 1)
		break;

	    printf("\n\nChannel: %1d  Range: ",c_block.current_channel);

	    if(c_block.range[c_block.current_channel] == BIPOLAR_5)
		   printf("Bipolar 5  ");
	    if(c_block.range[c_block.current_channel] == BIPOLAR_10)
		   printf("Bipolar 10 ");
	    if(c_block.range[c_block.current_channel] == UNIPOLAR_10)
		   printf("Unipolar 10");

	    printf("  Coefficients: Offset ");
	    if(c_block.range[c_block.current_channel] == BIPOLAR_5)
		   printf("%04X",(c_block.coef_bufb5[c_block.current_channel][0] & 0xFFFF));
	    if(c_block.range[c_block.current_channel] == BIPOLAR_10)
		   printf("%04X",(c_block.coef_bufb10[c_block.current_channel][0] & 0xFFFF));
	    if(c_block.range[c_block.current_channel] == UNIPOLAR_10)
		   printf("%04X",(c_block.coef_bufu10[c_block.current_channel][0] & 0xFFFF));

	    printf("  Gain ");
	    if(c_block.range[c_block.current_channel] == BIPOLAR_5)
		   printf("%04X",(c_block.coef_bufb5[c_block.current_channel][1] & 0xFFFF));
	    if(c_block.range[c_block.current_channel] == BIPOLAR_10)
		   printf("%04X",(c_block.coef_bufb10[c_block.current_channel][1] & 0xFFFF));
	    if(c_block.range[c_block.current_channel] == UNIPOLAR_10)
		   printf("%04X",(c_block.coef_bufu10[c_block.current_channel][1] & 0xFFFF));

	    printf("\n\nIdeal Data");
	    for( j = 8; j < 16; j++)
	    {
		printf("\n[%02X]",j*8);
		for(i = 0; i < 8; i++)
		      printf("    %04x",c_block.ideal_data[c_block.current_channel][j*8+i] & 0xFFFF);
	    }

	    printf("\n\nCorrected Data ");
	    for( j = 8; j < 16; j++)
	    {
		printf("\n[%02X]",j*8);
		for(i = 0; i < 8; i++)
		      printf("    %04x",c_block.cor_data[c_block.current_channel][j*8+i] & 0xFFFF);
	    }

	    printf("\n 1. Return to Previous Menu");
	    printf("\n 2. View Previous Data Block");
	    printf("\nSelect: ");
	    scanf("%d",&temp);
	    if( temp == 2)
		goto previous;
	 break;


        case 16:        /* clear all data buffers */
	    for(i = 0; i < NUM_CHAN; i++)
	    {
	      for(j = 0; j < MAXSIZE; j++)
	      {
		c_block.ideal_data[i][j] = 0;	/* clear ideal data buffer */
		c_block.cor_data[i][j] = 0;	/* clear corrected data buffer */
	      }
	      c_block.coef_bufu10[i][0] = c_block.coef_bufu10[i][1] = 0;
	      c_block.coef_bufb10[i][0] = c_block.coef_bufb10[i][1] = 0;
	      c_block.coef_bufb5[i][0]  = c_block.coef_bufb5[i][1] = 0;
	    }
            break;

  
        case 17: /* modify gain & offset coefficients for a channel */
         if(flag == 0)
                printf("\n>>> ERROR: BOARD ADDRESS NOT SET <<<\n");
         else
	 {
	    finished1 = 0;
	    while(!finished1)
	    {
 	       printf("\n\nChannel: %x\n\n",c_block.current_channel);
	       printf(" 1. Return to Previous Menu\n");
	       printf(" 2. Change Channel Number\n");
	       printf(" 3. Change Bipolar   5 Offset & Gain\n");
	       printf(" 4. Change Bipolar  10 Offset & Gain\n");
	       printf(" 5. Change Unipolar 10 Offset & Gain\n");
	       printf(" 6. Calculate Offset & Gain from End Points\n");
	       printf(" 7. Write All Current Channel Coefficients to EEPROM\n");
	       printf("\nSelect: ");
	       scanf("%d",&temp);
	       switch(temp)
	       {
		 case 1: /* return to previous menu */
		    finished1++;
		 break;

		 case 2: /* Select channel */
		     printf("New Channel Number (0 - %d)\n",(NUM_CHAN - 1));
		     c_block.current_channel = (int)get_param();
		 break;

		 case 3: /* Select Bipolar   5 */
		     printf("New Offset Value\n");
		     c_block.coef_bufb5[c_block.current_channel][0] = (short)get_param();
		     printf("New Gain Value\n");
		     c_block.coef_bufb5[c_block.current_channel][1] = (short)get_param();
		 break;

		 case 4: /* Select Bipolar  10 */
		     printf("New Offset Value\n");
		     c_block.coef_bufb10[c_block.current_channel][0] = (short)get_param();
		     printf("New Gain Value\n");
		     c_block.coef_bufb10[c_block.current_channel][1] = (short)get_param();
		 break;

		 case 5: /* Select Unipolar  10 */
		     printf("New Offset Value\n");
		     c_block.coef_bufu10[c_block.current_channel][0] = (short)get_param();
		     printf("New Gain Value\n");
		     c_block.coef_bufu10[c_block.current_channel][1] = (short)get_param();
		 break;

		 case 6: /* calculate */
		     printf("\nSpan 10 or 20: ");
		     scanf("%d",&temp);
		     printf("\nFull Scale Value: ");
		     scanf("%f",&fs);
		     printf("\nZero Scale Value: ");
		     scanf("%f",&zs);

		     if((fs - zs) == 0.0)
			break;

		     /* do gain calculation */
		     slope = 65536.0 / (fs - zs);
		     /* gain error */
		     ge = (((float)temp * slope) / 65536.0) - 1.0;
		     printf("\nGain = %X", ((short)((ge * 65536.0 * 4) + 0.5) & 0xFFFF));
 
		     /* do offset calculation */
		     slope *= -1;
		     printf("  Offset = %X",((short)((((slope * zs) - 32768.0) * 4) + 0.5) & 0xFFFF));
		 break;


		 case 7: /* Write values to EEPROM */
		  WriteCoefficients( &c_block, c_block.current_channel, c_block.coef_bufu10[c_block.current_channel][0],
			 c_block.coef_bufu10[c_block.current_channel][1], UNIPOLAR_10 );

		  WriteCoefficients( &c_block, c_block.current_channel, c_block.coef_bufb5[c_block.current_channel][0],
			 c_block.coef_bufb5[c_block.current_channel][1], BIPOLAR_5 );

		  WriteCoefficients( &c_block, c_block.current_channel, c_block.coef_bufb10[c_block.current_channel][0],
			 c_block.coef_bufb10[c_block.current_channel][1], BIPOLAR_10 );

		 break;
	       }
	    }
         }
        break;

      
        case 18: /* detach exception handlers */
		hflag = 0;
		DisableInterrupts(c_block.nHandle);
         break;

        }   /* end of switch */
    }   /* end of while */
/*
    Reset board to disable interrupts from all counters on this IP module
*/
    if(!c_block.bInitialized)    /* module address was set */
       reset_board(&c_block);	  /* reset board */

    DisableInterrupts(c_block.nHandle);
    if(c_block.bCarrier)
	CarrierClose(c_block.nHandle);

    printf("\nEXIT PROGRAM\n");
}   /* end of main */
Exemple #11
0
int main(void)
{
	int i, spi_timeout;
	unsigned long counter;

	/* Disable JTAG port so we get our I/O pins back */
	DDPCONbits.JTAGEN = 0;
	/* Enable optimal performance */
	SYSTEMConfigPerformance(GetSystemClock());
	/* Use 1:1 CPU Core:Peripheral clocks */
	OSCSetPBDIV(OSC_PB_DIV_1);

	/* configure the core timer roll-over rate */
	OpenCoreTimer(CORE_TICK_RATE);

	/* set up the core timer interrupt */
	mConfigIntCoreTimer((CT_INT_ON | CT_INT_PRIOR_6 | CT_INT_SUB_PRIOR_0));

	/* enable multi vector interrupts */
	INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
	INTEnableInterrupts();

	map_peripherals();
	init_io_ports();
	configure_pwm();
	init_spi();
	init_dma();

	/* wait until tx buffer is filled up */
	while (!SPI2STATbits.SPITBF);

	reset_board();
	spi_data_ready = 0;
	spi_timeout = 0;
	counter = 0;

	/* enable watchdog */
	WDTCONSET = 0x8000;

	/* main loop */
	while (1) {
		if (spi_data_ready) {
			spi_data_ready = 0;

			/* the first element received is a command string */
			switch (rxBuf[0]) {
			case 0x5453523E:	/* >RST */
				reset_board();
				break;
			case 0x314D433E:	/* >CM1 */
				stepgen_update_input((const void *)&rxBuf[1]);
				stepgen_get_position((void *)&txBuf[1]);
				break;
			case 0x324D433E:	/* >CM2 */
				update_outputs(rxBuf[1]);
				update_pwm_duty((uint32_t *)&rxBuf[2]);
				txBuf[1] = read_inputs();
				break;
			case 0x4746433E:	/* >CFG */
				stepgen_update_stepwidth(rxBuf[1]);
				update_pwm_period(rxBuf[2]);
				stepgen_reset();
				break;
			case 0x5453543E:	/* >TST */
				for (i=0; i<BUFSIZE; i++)
					txBuf[i] = rxBuf[i] ^ ~0;
				break;
			}
		}

		/* if rx buffer is half-full, update the integrity check.
		   There isn't enough time if we wait for complete transfer */
		if (DCH0INTbits.CHDHIF) {
			DCH0INTCLR = 1<<4;		/* clear flag */
			txBuf[0] = rxBuf[0] ^ ~0;
		}

		/* if rx buffer is full, data from spi bus is ready */
		if (DCH0INTbits.CHBCIF) {
			DCH0INTCLR = 1<<3;		/* clear flag */
			spi_data_ready = 1;
			spi_timeout = SPI_TIMEOUT;
		}

		/* reset the board if there is no SPI activity */
		if (spi_timeout)
			spi_timeout--;

		if (spi_timeout == 1) {				
			DCH0ECONSET=BIT_6;	/* abort DMA transfers */
			DCH1ECONSET=BIT_6;
		
			init_spi();
			init_dma();
			reset_board();

			/* wait until tx buffer is filled up */
			while (!SPI2STATbits.SPITBF);
		}

		/* blink onboard led */
		if (!(counter++ % (spi_timeout ? 0x10000 : 0x40000))) {
			LED_TOGGLE;
		}

		/* keep alive */
		WDTCONSET = 0x01;
	}
	return 0;
}
Exemple #12
0
/*********************************************************//*
   Play a series of games
*/
void play_games( int num_games, int move[] )
{
  int board[10][10];
  int game_status;
  int player, first_player;
  int game;
  int m;

  first_player = 0;

  for( game=0; game < num_games; game++ ) {
    reset_board( board );

    write_agent( first_player,"start(x).\n");
    write_agent(!first_player,"start(o).\n");

    msec_left[0] = 1000*(seconds_initially - seconds_per_move);
    msec_left[1] = 1000*(seconds_initially - seconds_per_move);

    if( game > 0 || move[0] == 0 ) {// choose first move randomly
      move[0] = 1 + random()% 9;
      move[1] = 1 + random()% 9;
    }
    m = 1;
    player = first_player;
    game_status = make_move( player,m,move,board );
    while( m < MAX_MOVE && game_status == STILL_PLAYING ) {
      //print_board( stdout,board,move[m-1],move[m] );
      m++;
      player = !player;
      if( is_human[player] ) {
        game_status =  human_step( player,m,move,board );
      }
      else {
        game_status = server_step( player,m,move,board );
      }
    }
    if(!is_human[!player] &&(game_status == WIN || game_status == DRAW)){
      fprintf(agent_in[!player],"last_move(%d).\n",move[m]);
    }

    print_board( stdout,board,move[m-1],move[m] );

    if( game_status == WIN ) {
      write_agent(  player, "win(triple).\n" );
      write_agent( !player,"loss(triple).\n" );
      printf("Player %c wins (triple)\n", sb[player]);
    }
    else if( game_status == DRAW ) {
      write_all("draw(full_board).\n" );
      printf( "draw (full_board)\n" );
    }
    else if( game_status == ILLEGAL_MOVE ) {
      write_agent(  player,"loss(illegal_move).\n" );
      write_agent( !player, "win(illegal_move).\n" );
      printf("Player %c wins (illegal_move)\n",sb[!player]);
    }
    else if( game_status == TIMEOUT ) {
      write_agent(  player,"loss(timeout).\n" );
      write_agent( !player, "win(timeout).\n" );
      printf( "Player %c wins (timeout)\n", sb[!player]);
    }
  }
  printf( "\n" );
}
Exemple #13
0
static void can_reset(CO_Data* d)
{
    reset_board();
}
Exemple #14
0
int main(int argc, char *argv[])
{
    int bmid, i, j=0;
    FILE *inf, *firef;
    time4_t now=time(NULL); 
    attach_SHM();
    resolve_boards();

    if(passwd_init())
	exit(1);      

    memcpy(allbrd,bcache,numboards*sizeof(boardheader_t));

    /* write out the target file */
    inf   = fopen(OUTFILE, "w+");
    if (inf == NULL) {
	printf("open file error : %s\n", OUTFILE);
	exit(1);
    }

    firef = fopen(FIREFILE, "w+");
    if (firef == NULL) {
	printf("open file error : %s\n", FIREFILE);
	exit(1);
    }

    fprintf(inf, "警告: 板主若超過(不包含) %d天未上站,將予於免職\n",
            LAZY_BM_LIMIT_DAYS);
    fprintf(inf,
	    "看板名稱                                           "
	    "    板主        幾天沒來啦\n"
	    "---------------------------------------------------"
	    "--------------------------\n");

    fprintf(firef, "免職板主\n");
    fprintf(firef,
	    "看板名稱                                           "
	    "    板主        幾天沒來啦\n"
	    "---------------------------------------------------"
	    "--------------------------\n"); 


    j = 0;
    for (i = 0; i < numboards; i++) {
	char *p, bmbuf[IDLEN * 3 + 3];
	int   index = 0, flag = 0, k, n;
	userec_t xuser;
	p = allbrd[i].BM;

	if (*p == '[') p++;
	if (allbrd[i].brdname[0] == '\0' ||
		!isalpha(allbrd[i].brdname[0])
	   ) continue;

	p = strtok(p,"/ ]");
	for(index=0; p && index<5; index++) {
	    int diff;
	    // XXX what if bmid is invalid?
	    if(!p[0] || (bmid = passwd_load_user(p, &xuser)) < 1) {
		index--;
		p=strtok(NULL,"/ ]");
		continue;
	    }
	    strlcpy(bms[index].bmname, p, sizeof(bms[index].bmname));
	    bms[index].flag = 0;

	    diff = now - xuser.lastlogin;
	    if (diff < 0)
		diff = 0;

	    if (diff >= 45 * 86400
		    && !(xuser.userlevel & PERM_SYSOPHIDE)
		    && !(xuser.userlevel & PERM_SYSOP)) {
		strlcpy(lostbms[j].bmname, p, sizeof(bms[index].bmname));
		lostbms[j].title = allbrd[i].brdname;
		lostbms[j].ctitle = allbrd[i].title;
		lostbms[j].lostdays = diff / 86400;

		//超過 LAZY_BM_LIMIT_DAYS 天 免職
		if (lostbms[j].lostdays > LAZY_BM_LIMIT_DAYS) {
		    xuser.userlevel &= ~PERM_BM;
		    bms[index].flag = 1;
		    flag = 1;
                    // NOTE: 好像不改也無所謂,目前拔 BM 是自動的。
		    passwd_update(bmid, &xuser);
		}
		j++;
	    }
	    p = strtok(NULL,"/ ]");
	}

	if (flag == 1) {
            boardheader_t *bp = getbcache(i+1);

            // 確認我們沒搞錯 cache. 如果 cache 炸了就別用了
            if (strcmp(bp->brdname, allbrd[i].brdname) != 0) {
                printf("ERROR: unmatched cache!!! (%s - %s)\n",
                        bp->brdname, allbrd[i].brdname);
                bp = NULL;
                exit(1);
                // sync to latest
                memcpy(&allbrd[i], bp, sizeof(boardheader_t));
            }

	    bmbuf[0] = '\0';
	    for (k = 0, n = 0; k < index; k++) {
		if (!bms[k].flag) {
		    if (n++ != 0) strcat(bmbuf, "/");
		    strcat(bmbuf, bms[k].bmname);
		}
	    }
	    strcpy(allbrd[i].BM, bmbuf);
            printf("board %s: %s -> %s\n",
                    allbrd[i].brdname, bp->BM, allbrd[i].BM);
            strcpy(bp->BM, allbrd[i].BM);
	    if (substitute_record(BBSHOME"/"FN_BOARD, &allbrd[i], 
			sizeof(boardheader_t), i+1) == -1) {
		printf("Update Board Failed: %s\n", allbrd[i].brdname);
	    }
	    reset_board(i+1);
	}
    }
    qsort(lostbms, j, sizeof(lostbm), bmlostdays_cmp);

    //write to the etc/toplazyBM
    for (i = 0; i < j; i++) {
	if (lostbms[i].lostdays > LAZY_BM_LIMIT_DAYS) {
	    fprintf(firef, "%-*.*s%-*.*s%-*.*s%3d天沒上站\n",
		    IDLEN, IDLEN, lostbms[i].title, BTLEN-10,
		    BTLEN-10, lostbms[i].ctitle, IDLEN,IDLEN,
		    lostbms[i].bmname,lostbms[i].lostdays);
	} else {
	    fprintf(inf, "%-*.*s%-*.*s%-*.*s%3d天沒上站\n",
		    IDLEN, IDLEN, lostbms[i].title, BTLEN-10,
		    BTLEN-10, lostbms[i].ctitle, IDLEN,IDLEN,
		    lostbms[i].bmname,lostbms[i].lostdays);
	}
    }
    fclose(inf);
    fclose(firef);

    //printf("Total %d boards.\n", count);

    //mail to the users
    for (i=0; i<j; i++) {
	fileheader_t mymail;
	char	genbuf[200];
	int	lostdays;

	lostdays = lostbms[i].lostdays;

	if (lostdays != LAZY_BM_LIMIT_DAYS/2 &&
            lostdays != LAZY_BM_LIMIT_DAYS*2/3 &&
            lostdays != LAZY_BM_LIMIT_DAYS*5/6 &&
            lostdays <= LAZY_BM_LIMIT_DAYS)
	    continue;

	sprintf(genbuf, BBSHOME "/home/%c/%s", 
		lostbms[i].bmname[0], lostbms[i].bmname);
	stampfile(genbuf, &mymail);

	strcpy(mymail.owner, "[" BBSMNAME "警察局]");
	if (lostdays <= LAZY_BM_LIMIT_DAYS)
	    sprintf(mymail.title,
		    ANSI_COLOR(32) "版主通知" ANSI_RESET " %s版版主%s",
		    lostbms[i].title, lostbms[i].bmname);
	else
	    sprintf(mymail.title,
		    ANSI_COLOR(32) "版主自動免職通知" ANSI_RESET " %s 版主 %s",
		    lostbms[i].title, lostbms[i].bmname);

	unlink(genbuf);
	if (lostdays <= LAZY_BM_LIMIT_DAYS)
	    Link(OUTFILE, genbuf);
	else
	    Link(FIREFILE, genbuf);

	sprintf(genbuf, BBSHOME "/home/%c/%s/.DIR", 
		lostbms[i].bmname[0], lostbms[i].bmname);
	append_record(genbuf, &mymail, sizeof(mymail)); 	
    }
    return 0;
}