/* $Header: game_data.c,v 1.2 88/12/23 04:04:31 jik Exp $ */
/* $Log:	game_data.c,v $
 * Revision 1.2  88/12/23  04:04:31  jik
 * Most of these changes were done by raeburn.
 * 
 * Revision 1.1  85/01/31  14:04:47  jtkohl
 * Initial revision
 */

#include <stdio.h>
#include <strings.h>

#include "game_data.h"

char *malloc();
extern char *game_data_file;

int get_all_game_data(games, room)
struct game_data games[];
int room;
{
    FILE *fp;
    int i;
    static char buf[BUFSIZ];
    extern char *game_data_file;
    
    printf("get_all_game_data\n"); fflush(stdout);
    if ((fp = fopen(game_data_file, "r")) == NULL) {
#ifdef DEBUG
	syslog("can't open game data file %s: %m", game_data_file);
#endif
	return(-1);
    }
    for (i = 0; i < room; i++){
#ifdef DEBUG
	fprintf(stderr, "reading line\n");
#endif
	if (fgets(buf, BUFSIZ, fp) == NULL)
	    break;
	if (parse_line(&games[i], buf) < 0) {
#ifdef DEBUG
	    fprintf(stderr, "parse error reading game data file\n");
#endif
	    break;
	}
    }
    fclose(fp);
    return(i);
}

int get_game_data(game, game_name)
struct game_data *game;
char game_name[];
{
    FILE *fp;
    register int game_name_length, retval;
    static char buf[BUFSIZ];
    extern char *game_data_file;
    
    if ((fp = fopen(game_data_file, "r")) == NULL) {
	return(-1);
    }

    game_name_length = strlen(game_name);

    retval = -1;
    while (1) {
	if (fgets(buf, BUFSIZ, fp) == NULL)
	    break;

	if (!strncmp(game_name, buf, game_name_length) &&
	    buf[game_name_length] == ':') {
	    retval = parse_line(game, buf);
	    if (retval < 0)
		fprintf(stderr, "parse error in netgames file\n");
	    break;
	}
    }

    fclose(fp);
    return(retval);
}


int parse_line(game, buf)
struct game_data *game;
char *buf;
{
    char *s, *colon;
    register int size;
    
    if ((colon = index(buf, ':')) == NULL) return(-1);
    *colon = '\0';
    size = colon - buf;
    if ((s = (char *)malloc(size+1)) == NULL) return(-1);
    strncpy(s, buf, size);
    s[size] = '\0';
    game->name = s;

    buf = colon + 1;
    if ((colon = index(buf, ':')) == NULL) return(-1);
    *colon = '\0';
    game->type = atoi(buf);
	
    buf = colon + 1;
    if ((colon = index(buf, ':')) == NULL) return(-1);
    *colon = '\0';
    size = colon - buf;
    if ((s = (char *)malloc(size+1)) == NULL) return(-1);
    strncpy(s, buf, size);
    s[size] = '\0';
    game->user_path = s;

    buf = colon + 1;
    if ((colon = index(buf, ':')) == NULL) return(-1);
    *colon = '\0';
    size = colon - buf;
    if ((s = (char *)malloc(size+1)) == NULL) return(-1);
    strncpy(s, buf, size);
    s[size] = '\0';
    game->master_path = s;

    buf = colon + 1;
    if ((colon = index(buf, '\n')) == NULL) return(-1);
    *colon = '\0';
    size = colon - buf;
    if ((s = (char *)malloc(size+1)) == NULL) return(-1);
    strncpy(s, buf, size);
    s[size] = '\0';
    game->comment = s;
    return 0;
}
