/* file stu_fun.c, 程序 stu 的处理部分源程序文件 */
#include <stdio.h>
#include <stdlib.h>
#include "stu.h"

void statistics(int n, StuRec tb[]) {
    int i;
    double s, sum, avr;

    if (n <= 1) {
        printf("Data too few. Statistics stop.\n");
        return;
    }

    for (sum = 0.0, i = 0; i < n; ++i) sum += tb[i].score;
    avr = sum/n;
    for (sum = 0.0, i = 0; i < n; ++i)
        sum += (tb[i].score - avr)*(tb[i].score - avr);
    s = sqrt(sum/(n-1));

    printf("Total students: %d\n", n);
    printf("Average score: %lf\n", avr);
    printf("Standard deviation: %lf\n\n", s);
}

void prtHH(int n) {
    int i;
    for (i = 0; i < n; ++i) putchar('H');
}

void histogram(int n, StuRec tb[], int high) {
    int i, mx;
    int segs[SEGNUM];

    for (i = 0; i < SEGNUM; ++i) segs[i] = 0; /* 初始化 */
    for (i = 0; i < n; ++i) /* 统计各分段人数 */
        segs[(int)tb[i].score / SEGLEN]++;

    for (mx = 0, i = 0; i < SEGNUM; ++i) /* 为规范化找最大个数 */
        if (segs[i] > mx) mx = segs[i];
    for (i = 0; i < SEGNUM; ++i) { /* 输出 */
        printf("<%3d: %4d|", (i+1)*SEGLEN, segs[i]);
        prtHH(segs[i]*high/mx);
        putchar('\n');
    }
    putchar('\n');
}

static int scrcmp(const void *vp1, const void *vp2) {
    StuRec *p1 = (StuRec*)vp1, *p2 = (StuRec*)vp2;
    return p1->score > p2->score ? 1 :
            p1->score == p2->score ? 0 : -1;
}

void sortoutput(int n, StuRec tb[]) {
    char fn[128];
    FILE *fp;

    do { /* 交互式获取文件名 */
        getnstr("File name for saving: ", 128, fn);
        if ((fp = fopen(fn, "w")) == NULL)
            printf("Can't open file: %s\n", fn);
        else {
            qsort(tb, n, sizeof(StuRec), scrcmp);
            printSRec(fp, n, tb);
            fclose(fp);
            break;
        }
    } while (next("Really want to save"));
}

