1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
|
#! /usr/bin/env slsh
_debug_info = 1;
if (__argc < 2)
{
() = fprintf (stderr, "Usage: %s files....\n", __argv[0]);
exit (1);
}
static variable Data;
static define init ()
{
Data = Assoc_Type[String_Type];
}
static define warning ()
{
variable args = __pop_args (_NARGS);
() = fprintf (stderr, "***WARNING: %s\n", sprintf (__push_args ()));
}
static define process_function (line, fp)
{
variable fname;
variable lines;
fname = strtrim (strtok (line, "{}")[1]);
lines = line;
#iftrue
foreach (fp)
{
line = ();
lines = strcat (lines, line);
if (0 == strncmp ("\\done", line, 5))
break;
}
#else
while (-1 != fgets (&line, fp))
{
lines += line;
if (0 == strncmp ("\\done", line, 5))
break;
}
#endif
if (assoc_key_exists (Data, fname))
{
warning ("Key %s already exists", fname);
return -1;
}
Data[fname] = lines;
return 0;
}
static define process_variable (line, fp)
{
% warning ("process_variable not implemented");
process_function (line, fp);
}
static define read_file_contents (file)
{
variable fp = fopen (file, "r");
variable n = 0;
variable line;
if (fp == NULL)
{
() = fprintf (stderr, "Unable to open %s\n", file);
return -1;
}
%while (-1 != fgets (&line, fp))
foreach (fp)
{
line = ();
if (0 == strncmp (line, "\\function{", 10))
{
if (-1 == process_function (line, fp))
return -1;
continue;
}
if (0 == strncmp (line, "\\variable{", 10))
{
if (-1 == process_variable (line, fp))
return -1;
continue;
}
}
() = fclose (fp);
return 0;
}
static define sort_and_write_file_elements (file)
{
variable fp;
variable i, keys;
variable backup_file;
backup_file = file + ".BAK";
() = remove (backup_file);
() = rename (file, backup_file);
fp = fopen (file, "w");
if (fp == NULL)
return -1;
keys = assoc_get_keys (Data);
i = array_sort (keys, &strcmp);
foreach (keys[i])
{
variable k = ();
() = fputs (Data[k], fp);
() = fputs ("\n", fp);
}
() = fclose (fp);
return 0;
}
static define process_file (file)
{
init ();
() = fprintf (stdout, "Processing %s ...", file);
() = fflush (stdout);
if (-1 == read_file_contents (file))
return -1;
if (-1 == sort_and_write_file_elements (file))
return -1;
() = fputs ("done.\n", stdout);
return 0;
}
foreach (__argv[[1:]])
process_file ();
exit (0);
|