website.c


1
#include <stdio.h>
2
#include <math.h>
3
4
5
// gcc  -Wall -Wextra -std=c99 website.c -lm 
6
7
8
// ***********************************************************************************************************
9
// Daten:
10
11
float my_data[300];
12
const size_t len_my_data = sizeof(my_data) / sizeof(my_data[0]);
13
14
void fill_data()
15
{
16
    for (size_t i = 0; i < len_my_data; ++i)
17
        my_data[i] = i / 100.0f + sin(i/20.0f);
18
}
19
20
// ***********************************************************************************************************
21
// Grafik:
22
23
#define GRAPH_HEIGHT 200.0
24
#define GRAPH_WIDTH 400.0
25
26
void svg_enter()
27
{
28
    printf("<div class=\"svg\"><svg width=\"%f\" height=\"%f\">", GRAPH_WIDTH+20, GRAPH_HEIGHT+20);
29
    printf("<rect x=\"1\" y=\"1\" width=\"%f\" height=\"%f\"fill=\"beige\" stroke=\"none\"/>", GRAPH_WIDTH+20, GRAPH_HEIGHT+20);
30
}
31
32
33
void svg_leave()
34
{
35
    printf("\"</svg></div>");
36
}
37
38
void polyline_enter()
39
{
40
    printf("<polyline fill=\"none\" stroke=\"red\" stroke-width=\"1\" points=\"");
41
}
42
43
void polyline_point(float x, float y)
44
{
45
    printf("%f,%f \n", x+10, GRAPH_HEIGHT - y + 10);
46
}
47
48
void polyline_leave()
49
{
50
    printf(" />\n");
51
}
52
53
54
// ***********************************************************************************************************
55
// HTML:
56
57
#define GRAPH_HERE "\x01"
58
#define GRAPH_HERE_CH 0x01
59
60
const char page_example[] = 
61
"<html><head><title>Testpage</title></head><body><h1>My awesome Graph</h1>This is a graph<br />" 
62
GRAPH_HERE 
63
"<br />It looks interesting.</body></html>";
64
65
66
// output the data as an svg image:
67
void plot_data_as_svg(const float* data, size_t len)
68
{
69
    if (len == 0)
70
        return;
71
    float miny = data[0];
72
    float maxy = data[0];
73
    for(size_t i = 0; i < len; ++i)
74
    {
75
        if (data[i] < miny) miny = data[i];
76
        if (data[i] > maxy) maxy = data[i];
77
    }
78
    const float x_off = 0;
79
    const float x_res = GRAPH_WIDTH / len;
80
    const float y_off = miny;
81
    const float y_res = GRAPH_HEIGHT / (maxy - miny);
82
83
    svg_enter();
84
    polyline_enter();
85
    for(size_t i = 0; i < len; ++i)
86
    {
87
        const float x = (i - x_off) * x_res;
88
        const float y = (data[i] - y_off) * y_res;
89
        polyline_point(x, y);
90
    }
91
    polyline_leave();
92
    svg_leave();   
93
}
94
95
void send_page()
96
{
97
    for(const char* c = page_example; *c; ++c)
98
    {
99
        if(*c == GRAPH_HERE_CH)
100
            plot_data_as_svg(my_data, len_my_data);
101
        else
102
            putchar(*c);           
103
    }
104
}
105
106
// ***********************************************************************************************************
107
108
int main(void)
109
{
110
111
    fill_data();
112
    send_page();
113
    return 0;
114
}