#include <stdio.h>

enum {
    WDNUM = 1000, /* 最大中英文单词数 */
    WDLEN = 32,   /* 存储单词的数组的长度 */
    ROUND = 20    /* 一轮练习的次数 */
};

char wds[WDNUM*2][WDLEN];

#define ENGLISH(i) wds[2*(i)]
#define CHINESE(i) wds[2*(i)+1]

void getnstr (char prompt[], int lim, char bf[]);
int next(char s[]);
void wordgame(int terms, char wds[][WDLEN], int rd);
int readfile(FILE *fp, int lim, char wds[][WDLEN]);

int main() {
    char fn[256];
    FILE* fp;
    int terms;

    do {
        getnstr("Word file name: ", 256, fn);
        if ((fp = fopen(fn, "r")) == NULL)
            printf("Wrong file name. ");
        else {
            terms = readfile(fp, WDNUM, wds);
            fclose(fp);
            if (terms == 0) continue;
            wordgame(terms, wds, ROUND);
        }
    } while (next("word file"));

    return 0;
}

void getnstr (char prompt[], int lim, char bf[]) {
    int c, i = 0;

    printf("%s", prompt);
    while (i < lim-1 && (c = getchar()) != EOF && !isspace(c))
        bf[i++] = c;
    if (c != '\n')
        while (getchar() != '\n') ; /* 吃掉本行剩余字符 */

    bf[i] = '\0';
}

int next(char s[]) {
    int c;

    printf("Next %s? (y/n): ", s);
    while (isspace(c = getchar())) /* 读下一个非空白字符 */
        ;
    while (getchar() != '\n') ; /* 吃掉本行剩余字符 */

    return (c == 'y' || c == 'Y');
}

void wordgame(int terms, char wds[][WDLEN], int rd) {
    int n, i;
    char wd[WDLEN];

    do {
        for (i = 0; i < rd; ++i) {
            n = rand()%terms;
            printf("%s ", CHINESE(n));
            getnstr("> ", WDLEN, wd);
            if (strcmp(wd, ENGLISH(n)) == 0)
                printf("Ok!\n");
            else
                printf("Wrong! It is: %s\n", ENGLISH(n));
        }
    } while (next("Round?"));
}

char* charscopy(int lim, char t[], char s[], char delim) {
    int i;

    while (isspace(*s)) ++s;
    for (i = 0; i<lim && *s != '\0' && *s != '\n' && *s != delim;
         ++i, ++s, ++t)
        *t = *s;
    *t = '\0';

    return s + 1;
}

int readfile(FILE *fp, int lim, char wds[][WDLEN]) {
    char line[256], *p;
    int ln = 0, n = 0;

    while (n < lim && fgets(line, 256, fp) != NULL) {
        ++ln;
        p = line;
        p = charscopy(WDLEN-1, ENGLISH(n), p, ' ');
        p = charscopy(WDLEN-1, CHINESE(n), p, ' ');
        if (*ENGLISH(n) == '\0' || *CHINESE(n) == '\0')
            printf("Wrong line #%d: %s", ln, line);
        else ++n;
    }

    return n;
}

/*
int readfile(FILE *fp, int lim, char wds[][WDLEN]) {
    char line[256];
    int n = 0;

    while (n < lim && fgets(line, 256, fp) != NULL) {
        *(ENGLISH(n)) = *(CHINESE(n)) = '\0';
        sscanf(line, "%31s %31s", ENGLISH(n), CHINESE(n));
        if (*(ENGLISH(n)) == '\0' || *(CHINESE(n)) == '\0') {
            printf("Wrong line #%d: %s", n+1, line);
            continue;
        }
        ++n;
    }

    return n;
}
*/
