Fix for segfault in top_name stuff.
[monky] / text2c.sh
1 #!/bin/sh
2 #
3 # text2c.sh - convert a text file to C code
4 #
5 # Copyright (C) 2008  Phil Sutter <phil@nwl.cc>
6
7 # This program is free software: you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by the Free
9 # Software Foundation, either version 3 of the License, or (at your option)
10 # any later version.
11
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 # for more details.
16
17 # You should have received a copy of the GNU General Public License along
18 # with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21 # Invocation is as follows:
22 # $1: text file
23 # $2: output file
24 # $3: name of variable
25 #
26 # The output will be a char **, with each field containing a single line of $1.
27 # Additionally, a macro with the name print_$3 will be defined, with acts as
28 # a parameter-less function, printing the text to stdout.
29
30 [ $# -eq 3 ] || {
31         echo "Usage: `basename $0` <inputfile> <outputfile> <variablename>"
32         exit 1
33 }
34
35 outupper="`basename "$2" | tr '[a-z-.]' '[A-Z__]'`"
36
37 (
38         printf "#ifndef __%s\n" "$outupper"
39         printf "#define __%s\n" "$outupper"
40         printf "\n#define %s { \\" $3
41         printf "\n"
42         sed -e 's/"/\\"/g' -e 's/^/"/' -e 's/$/\\n", \\/' $1
43         printf "NULL }\n"
44         printf "\n#define print_%s() { \\" $3
45         printf "\n\tconst char **__sp, *__s[] = %s; \\" $3
46         printf "\n\tfor (__sp = __s; *__sp; __sp++) \\"
47         printf "\n\t\tprintf(\"%s\", *__sp); \\" "%s"
48         printf "\n}\n\n"
49         printf "#endif /* __%s */\n" "$outupper"
50 ) > $2