summaryrefslogtreecommitdiff
path: root/Build/source/texk/web2c/luatexdir/tex/texfileio.c
blob: 2c37ada75e9e5c7824756a7b94356313ab1c268a (plain)
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
/*

Copyright 2009-2010 Taco Hoekwater <taco@luatex.org>

This file is part of LuaTeX.

LuaTeX is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.

LuaTeX is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
License for more details.

You should have received a copy of the GNU General Public License along
with LuaTeX; if not, see <http://www.gnu.org/licenses/>.

*/

#include "ptexlib.h"

#include <string.h>
#include <kpathsea/absolute.h>

/*tex

The bane of portability is the fact that different operating systems treat input
and output quite differently, perhaps because computer scientists have not given
sufficient attention to this problem. People have felt somehow that input and
output are not part of ``real'' programming. Well, it is true that some kinds of
programming are more fun than others. With existing input/output conventions
being so diverse and so messy, the only sources of joy in such parts of the code
are the rare occasions when one can find a way to make the program a little less
bad than it might have been. We have two choices, either to attack I/O now and
get it over with, or to postpone I/O until near the end. Neither prospect is very
attractive, so let's get it over with.

The basic operations we need to do are (1)~inputting and outputting of text, to
or from a file or the user's terminal; (2)~inputting and outputting of eight-bit
bytes, to or from a file; (3)~instructing the operating system to initiate
(``open'') or to terminate (``close'') input or output from a specified file;
(4)~testing whether the end of an input file has been reached.

\TeX\ needs to deal with two kinds of files. We shall use the term |alpha_file|
for a file that contains textual data, and the term |byte_file| for a file that
contains eight-bit binary information. These two types turn out to be the same on
many computers, but sometimes there is a significant distinction, so we shall be
careful to distinguish between them. Standard protocols for transferring such
files from computer to computer, via high-speed networks, are now becoming
available to more and more communities of users.

The program actually makes use also of a third kind of file, called a
|word_file|, when dumping and reloading base information for its own
initialization. We shall define a word file later; but it will be possible for us
to specify simple operations on word files before they are defined.

We finally did away with |nameoffile| and |namelength|, but the variables have to
be kept otherwise there will be link errors from |openclose.c| in the web2c
library

*/

char *nameoffile;
int namelength;

/*tex

    When input files are opened via a callback, they will also be read using
    callbacks. for that purpose, the |open_read_file_callback| returns an integer
    to uniquely identify a callback table. This id replaces the file point |f| in
    this case, because the input does not have to be a file in the traditional
    sense.

    Signalling this fact is achieved by having two arrays of integers.

*/

int *input_file_callback_id;
int read_file_callback_id[17];

/*tex

    Here we handle |-output-directory|. We assume that it is OK to look here
    first. Possibly it would be better to replace lookups in "." with lookups in
    the |output_directory| followed by "." but to do this requires much more
    invasive surgery in libkpathsea.

*/

static char *find_in_output_directory(const char *s)
{
    if (output_directory && !kpse_absolute_p(s, false)) {
        FILE *f_ptr;
        char *ftemp = concat3(output_directory, DIR_SEP_STRING, s);
        /*tex This code is used for input files only. */
        f_ptr = fopen(ftemp, "rb");
        if (f_ptr) {
            fclose(f_ptr);
            return ftemp;
        } else {
            free(ftemp);

        }
    }
    return NULL;
}

/*tex

    Find an \.{\\input} or \.{\\read} file. |n| differentiates between those
    case.

*/

int kpse_available(const char *m) {
    if (!kpse_init) {
        fprintf(stdout,"missing kpse replacement callback '%s', quitting\n",m);
        exit(1);
    }
    return 1 ;
}

char *luatex_find_read_file(const char *s, int n, int callback_index)
{
    char *ftemp = NULL;
    int callback_id = callback_defined(callback_index);
    if (callback_id > 0) {
        (void) run_callback(callback_id, "dS->R", n, s, &ftemp);
    } else if (kpse_available("find_read_file")) {
        /*tex Use kpathsea here. */
        ftemp = find_in_output_directory(s);
        if (!ftemp)
            ftemp = kpse_find_file(s, kpse_tex_format, 1);
    }
    if (ftemp) {
        if (fullnameoffile)
            free(fullnameoffile);
        fullnameoffile = xstrdup(ftemp);
    }
    return ftemp;
}

/*tex Find other files types. */

char *luatex_find_file(const char *s, int callback_index)
{
    char *ftemp = NULL;
    int callback_id = callback_defined(callback_index);
    if (callback_id > 0) {
        (void) run_callback(callback_id, "S->R", s, &ftemp);
    } else if (kpse_available("find_read_file")) {
        /*tex Use kpathsea here. */
        switch (callback_index) {
            case find_enc_file_callback:
                ftemp = kpse_find_file(s, kpse_enc_format, 0);
                break;
            case find_map_file_callback:
                ftemp = kpse_find_file(s, kpse_fontmap_format, 0);
                break;
            case find_type1_file_callback:
                ftemp = kpse_find_file(s, kpse_type1_format, 0);
                break;
            case find_truetype_file_callback:
                ftemp = kpse_find_file(s, kpse_truetype_format, 0);
                break;
            case find_opentype_file_callback:
                ftemp = kpse_find_file(s, kpse_opentype_format, 0);
                if (ftemp == NULL)
                    ftemp = kpse_find_file(s, kpse_truetype_format, 0);
                break;
            case find_data_file_callback:
                ftemp = find_in_output_directory(s);
                if (!ftemp)
                    ftemp = kpse_find_file(s, kpse_tex_format, 1);
                break;
            case find_font_file_callback:
                ftemp = kpse_find_file(s, kpse_ofm_format, 1);
                if (ftemp == NULL)
                    ftemp = kpse_find_file(s, kpse_tfm_format, 1);
                break;
            case find_vf_file_callback:
                ftemp = kpse_find_file(s, kpse_ovf_format, 0);
                if (ftemp == NULL)
                    ftemp = kpse_find_file(s, kpse_vf_format, 0);
                break;
            case find_cidmap_file_callback:
                ftemp = kpse_find_file(s, kpse_cid_format, 0);
                break;
            default:
                printf("luatex_find_file(): do not know how to handle file %s of type %d\n", s, callback_index);
                break;
        }
    }
    return ftemp;
}

/*tex

    \LUATEX\ used to have private functions for these that did not use kpathsea,
    but since the file paranoia tests have to come from kpathsea anyway, that is
    no longer useful. The only downside to using luatex is that if one wants to
    disable kpathsea via the Lua startup script, it is now an absolute
    requirement that all file discovery callbacks are specified. Just using the
    find_read_file, but not setting open_read_file, for example, does not work
    any more if kpathsea is not to be used at all.

*/

#define openoutnameok(A) kpse_out_name_ok (A)
#define openinnameok(A)  kpse_in_name_ok (A)

/*tex

    Open an input file F, using the kpathsea format FILEFMT and passing
    |FOPEN_MODE| to fopen. The filename is in `fn'. We return whether or not the
    open succeeded.

*/

boolean luatex_open_input(FILE ** f_ptr, const char *fn, int filefmt, const_string fopen_mode, boolean must_exist)
{
    /*tex We haven't found anything yet. */
    string fname = NULL;
    *f_ptr = NULL;
    if (fullnameoffile)
        free(fullnameoffile);
    fullnameoffile = NULL;
    fname = kpse_find_file(fn, (kpse_file_format_type) filefmt, must_exist);
    if (fname) {
        fullnameoffile = xstrdup(fname);
        /*tex

            If we found the file in the current directory, don't leave the `./'
            at the beginning of `fn', since it looks dumb when `tex foo' says
            `(./foo.tex ... )'. On the other hand, if the user said `tex ./foo',
            and that's what we opened, then keep it -- the user specified it, so
            we shouldn't remove it.

        */
        if (fname[0] == '.' && IS_DIR_SEP(fname[1]) && (fn[0] != '.' || !IS_DIR_SEP(fn[1]))) {
            unsigned i = 0;
            while (fname[i + 2] != 0) {
                fname[i] = fname[i + 2];
                i++;
            }
            fname[i] = 0;
        }
        /*tex This fopen is not allowed to fail. */
        *f_ptr = xfopen(fname, fopen_mode);
    }
    if (*f_ptr) {
        recorder_record_input(fname);
    }
    return *f_ptr != NULL;
}

boolean luatex_open_output(FILE ** f_ptr, const char *fn, const_string fopen_mode)
{
    char *fname;
    boolean absolute = kpse_absolute_p(fn, false);
    /*tex If we have an explicit output directory, use it. */
    if (output_directory && !absolute) {
        fname = concat3(output_directory, DIR_SEP_STRING, fn);
    } else {
        fname = xstrdup(fn);
    }
    /*tex Is the filename openable as given?  */
    *f_ptr = fopen(fname, fopen_mode);
    if (!*f_ptr) {
        /*tex Can't open as given. Try the envvar.  */
        string texmfoutput = kpse_var_value("TEXMFOUTPUT");
        if (texmfoutput && *texmfoutput && !absolute) {
            fname = concat3(texmfoutput, DIR_SEP_STRING, fn);
            *f_ptr = fopen(fname, fopen_mode);
        }
    }
    if (*f_ptr) {
        recorder_record_output(fname);
    }
    free(fname);
    return *f_ptr != NULL;
}

boolean lua_a_open_in(alpha_file * f, char *fn, int n)
{
    int k;
    char *fnam;
    int callback_id;
    boolean ret = true;
    boolean file_ok = true;
    if (n == 0) {
        input_file_callback_id[iindex] = 0;
    } else {
        read_file_callback_id[n] = 0;
    }
    if (*fn == '|')
        fnam = fn;
    else
        fnam = luatex_find_read_file(fn, n, find_read_file_callback);
    if (!fnam)
        return false;
    callback_id = callback_defined(open_read_file_callback);
    if (callback_id > 0) {
        k = run_and_save_callback(callback_id, "S->", fnam);
        if (k > 0) {
            ret = true;
            if (n == 0)
                input_file_callback_id[iindex] = k;
            else
                read_file_callback_id[n] = k;
        } else {
            /*tex read failed */
            file_ok = false;
        }
    } else {
        /*tex no read callback */
        if (openinnameok(fnam)) {
            ret = open_in_or_pipe(f, fnam, kpse_tex_format, FOPEN_RBIN_MODE, (n == 0 ? true : false));
        } else {
            /*tex open failed */
            file_ok = false;
        }
    }
    if (!file_ok) {
        ret = false;
    }
    return ret;
}

boolean lua_a_open_out(alpha_file * f, char *fn, int n)
{
    boolean test;
    char *fnam = NULL;
    int callback_id;
    boolean ret = false;
    callback_id = callback_defined(find_write_file_callback);
    if (callback_id > 0) {
        test = run_callback(callback_id, "dS->R", n, fn, &fnam);
        if ((test) && (fnam != NULL) && (strlen(fnam) > 0)) {
            /*tex

                There is no message here because if that is needed the macro
                package should do that in the callback code. As elsewhere,
                messaging is left to \LUA\ then.

            */
            ret = open_outfile(f, fnam, FOPEN_W_MODE);
            free(fnam);
        }
    } else {
        if (openoutnameok(fn)) {
            if (n > 0 && selector != term_only) {
                /*tex

                    This message to the log is for downward compatibility with
                    other tex's as there are scripts out there that act on this
                    message. An alternative is to let a macro package write an
                    explicit message.

                */
                fprintf(log_file,"\n\\openout%i = %s\n",n-1,fn);
             }
             ret = open_out_or_pipe(f, fn, FOPEN_W_MODE);
        }
    }
    return ret;
}

boolean lua_b_open_out(alpha_file * f, char *fn)
{
    boolean test;
    char *fnam = NULL;
    int callback_id;
    boolean ret = false;
    callback_id = callback_defined(find_output_file_callback);
    if (callback_id > 0) {
        test = run_callback(callback_id, "S->R", fn, &fnam);
        if ((test) && (fnam != NULL) && (strlen(fnam) > 0)) {
            ret = open_outfile(f, fnam, FOPEN_WBIN_MODE);
            free(fnam);
        }
    } else {
        if (openoutnameok(fn)) {
            ret = luatex_open_output(f, fn, FOPEN_WBIN_MODE);
        }
    }
    return ret;
}

void lua_a_close_in(alpha_file f, int n)
{
    int callback_id;
    if (n == 0)
        callback_id = input_file_callback_id[iindex];
    else
        callback_id = read_file_callback_id[n];
    if (callback_id > 0) {
        run_saved_callback(callback_id, "close", "->");
        destroy_saved_callback(callback_id);
        if (n == 0)
            input_file_callback_id[iindex] = 0;
        else
            read_file_callback_id[n] = 0;
    } else {
        close_file_or_pipe(f);
    }
}

void lua_a_close_out(alpha_file f)
{
    close_file_or_pipe(f);
}

/*tex

    Binary input and output are done with C's ordinary procedures, so we don't
    have to make any other special arrangements for binary~I/O. Text output is
    also easy to do with standard routines. The treatment of text input is more
    difficult, however, because of the necessary translation to |ASCII_code|
    values. \TeX's conventions should be efficient, and they should blend nicely
    with the user's operating environment.

    Input from text files is read one line at a time, using a routine called
    |lua_input_ln|. This function is defined in terms of global variables called
    |buffer|, |first|, and |last| that will be described in detail later; for
    now, it suffices for us to know that |buffer| is an array of |ASCII_code|
    values, and that |first| and |last| are indices into this array representing
    the beginning and ending of a line of text.

*/

/*tex lines of characters being read */

packed_ASCII_code *buffer;

/*tex the first unused position in |buffer| */

int first;

/*tex end of the line just input to |buffer| */

int last;

/*tex largest index used in |buffer| */

int max_buf_stack;

/*tex

    The |lua_input_ln| function brings the next line of input from the specified
    file into available positions of the buffer array and returns the value
    |true|, unless the file has already been entirely read, in which case it
    returns |false| and sets |last:=first|. In general, the |ASCII_code| numbers
    that represent the next line of the file are input into |buffer[first]|,
    |buffer[first+1]|, \dots, |buffer[last-1]|; and the global variable |last| is
    set equal to |first| plus the length of the line. Trailing blanks are removed
    from the line; thus, either |last=first| (in which case the line was entirely
    blank) or |buffer[last-1]<>" "|.

    An overflow error is given, however, if the normal actions of |lua_input_ln|
    would make |last>=buf_size|; this is done so that other parts of \TeX\ can
    safely look at the contents of |buffer[last+1]| without overstepping the
    bounds of the |buffer| array. Upon entry to |lua_input_ln|, the condition
    |first<buf_size| will always hold, so that there is always room for an
    ``empty'' line.

    The variable |max_buf_stack|, which is used to keep track of how large the
    |buf_size| parameter must be to accommodate the present job, is also kept up
    to date by |lua_input_ln|.

    If the |bypass_eoln| parameter is |true|, |lua_input_ln| will do a |get|
    before looking at the first character of the line; this skips over an |eoln|
    that was in |f^|. The procedure does not do a |get| when it reaches the end
    of the line; therefore it can be used to acquire input from the user's
    terminal as well as from ordinary text files.

    Since the inner loop of |lua_input_ln| is part of \TeX's ``inner
    loop''---each character of input comes in at this place---it is wise to
    reduce system overhead by making use of special routines that read in an
    entire array of characters at once, if such routines are available.

*/

boolean lua_input_ln(alpha_file f, int n, boolean bypass_eoln)
{
    boolean lua_result;
    int last_ptr;
    int callback_id;
    /*tex Todo: variable can be removed: */
    (void) bypass_eoln;
    if (n == 0)
        callback_id = input_file_callback_id[iindex];
    else
        callback_id = read_file_callback_id[n];
    if (callback_id > 0) {
        last = first;
        last_ptr = first;
        lua_result =
            run_saved_callback(callback_id, "reader", "->l", &last_ptr);
        if ((lua_result == true) && (last_ptr != 0)) {
            last = last_ptr;
            if (last > max_buf_stack)
                max_buf_stack = last;
        } else {
            lua_result = false;
        }
    } else {
        lua_result = input_ln(f, bypass_eoln);
    }
    if (lua_result == true) {
        /*tex Fix up the input buffer using callbacks */
        if (last >= first) {
            callback_id = callback_defined(process_input_buffer_callback);
            if (callback_id > 0) {
                last_ptr = first;
                lua_result =
                    run_callback(callback_id, "l->l", (last - first),
                                 &last_ptr);
                if ((lua_result == true) && (last_ptr != 0)) {
                    last = last_ptr;
                    if (last > max_buf_stack)
                        max_buf_stack = last;
                }
            }
        }
        return true;
    }
    return false;
}

/*tex

    We need a special routine to read the first line of \TeX\ input from the
    user's terminal. This line is different because it is read before we have
    opened the transcript file; there is sort of a ``chicken and egg'' problem
    here. If the user types `\.{\\input paper}' on the first line, or if some
    macro invoked by that line does such an \.{\\input}, the transcript file will
    be named `\.{paper.log}'; but if no \.{\\input} commands are performed during
    the first line of terminal input, the transcript file will acquire its
    default name `\.{texput.log}'. (The transcript file will not contain error
    messages generated by the first line before the first \.{\\input} command.)

    The first line is special also because it may be read before \TeX\ has input
    a format file. In such cases, normal error messages cannot yet be given. The
    following code uses concepts that will be explained later.

    Different systems have different ways to get started. But regardless of what
    conventions are adopted, the routine that initializes the terminal should
    satisfy the following specifications:

    \startitemize[n]

        \startitem
            It should open file |term_in| for input from the terminal. (The file
            |term_out| will already be open for output to the terminal.)
        \stopitem

        \startitem
            If the user has given a command line, this line should be considered
            the first line of terminal input. Otherwise the user should be
            prompted with `\.{**}', and the first line of input should be
            whatever is typed in response.
        \stopitem

        \startitem
            The first line of input, which might or might not be a command line,
            should appear in locations |first| to |last-1| of the |buffer| array.
        \stopitem

        \startitem
            The global variable |loc| should be set so that the character to be
            read next by \TeX\ is in |buffer[loc]|. This character should not be
            blank, and we should have |loc<last|.
        \stopitem

    \stopitemize

    It may be necessary to prompt the user several times before a non-blank line
    comes in. The prompt is `\.{**}' instead of the later `\.*' because the
    meaning is slightly different: `\.{\\input}' need not be typed immediately
    after~`\.{**}'.)

    The following program does the required initialization. Iff anything has been
    specified on the command line, then |t_open_in| will return with |last >
    first|.

*/

boolean init_terminal(void)
{
    /*tex This gets the terminal input started. */
    t_open_in();
    if (last > first) {
        iloc = first;
        while ((iloc < last) && (buffer[iloc] == ' '))
            incr(iloc);
        if (iloc < last) {
            return true;
        }
    }
    while (1) {
        wake_up_terminal();
        fputs("**", term_out);
        update_terminal();
        if (!input_ln(term_in, true)) {
            /*tex This shouldn't happen. */
            fputs("\n! End of file on the terminal... why?\n", term_out);
            return false;
        }
        iloc = first;
        while ((iloc < last) && (buffer[iloc] == ' ')) {
            incr(iloc);
        }
        /*tex Return unless the line was all blank. */
        if (iloc < last) {
            return true;
        }
        fputs("Please type the name of your input file.\n", term_out);
    }
}


/*tex

    Here is a procedure that asks the user to type a line of input, assuming that
    the |selector| setting is either |term_only| or |term_and_log|. The input is
    placed into locations |first| through |last-1| of the |buffer| array, and
    echoed on the transcript file if appropriate.

*/

void term_input(void)
{
    /*tex Index into |buffer|: */
    int k;
    /*tex Now the user sees the prompt for sure: */
    update_terminal();
    if (!input_ln(term_in, true))
        fatal_error("End of file on the terminal!");
    /*tex The user's line ended with \.{<return>}: */
    term_offset = 0;
    /*tex Prepare to echo the input. */
    decr(selector);
    if (last != first) {
        for (k = first; k <= last - 1; k++)
            print_char(buffer[k]);
    }
    print_ln();
    /*tex Restore previous status. */
    incr(selector);
}

/*tex

    It's time now to fret about file names. Besides the fact that different
    operating systems treat files in different ways, we must cope with the fact
    that completely different naming conventions are used by different groups of
    people. The following programs show what is required for one particular
    operating system; similar routines for other systems are not difficult to
    devise.

    \TeX\ assumes that a file name has three parts: the name proper; its
    ``extension''; and a ``file area'' where it is found in an external file
    system. The extension of an input file or a write file is assumed to be
    `\.{.tex}' unless otherwise specified; it is `\.{.log}' on the transcript
    file that records each run of \TeX; it is `\.{.tfm}' on the font metric files
    that describe characters in the fonts \TeX\ uses; it is `\.{.dvi}' on the
    output files that specify typesetting information; and it is `\.{.fmt}' on
    the format files written by \.{INITEX} to initialize \TeX. The file area can
    be arbitrary on input files, but files are usually output to the user's
    current area. If an input file cannot be found on the specified area, \TeX\
    will look for it on a special system area; this special area is intended for
    commonly used input files like \.{webmac.tex}.

    Simple uses of \TeX\ refer only to file names that have no explicit extension
    or area. For example, a person usually says `\.{\\input} \.{paper}' or
    `\.{\\font\\tenrm} \.= \.{helvetica}' instead of `\.{\\input} \.{paper.new}'
    or `\.{\\font\\tenrm} \.= \.{<csd.knuth>test}'. Simple file names are best,
    because they make the \TeX\ source files portable; whenever a file name
    consists entirely of letters and digits, it should be treated in the same way
    by all implementations of \TeX. However, users need the ability to refer to
    other files in their environment, especially when responding to error
    messages concerning unopenable files; therefore we want to let them use the
    syntax that appears in their favorite operating system.

    The following procedures don't allow spaces to be part of file names; but
    some users seem to like names that are spaced-out. System-dependent changes
    to allow such things should probably be made with reluctance, and only when
    an entire file name that includes spaces is ``quoted'' somehow.

    Here are the global values that file names will be scanned into.

*/

/*tex name of file just scanned */

str_number cur_name;

/*tex file area just scanned, or \.{""} */

str_number cur_area;

/*tex file extension just scanned, or \.{""} */

str_number cur_ext;

/*tex

    The file names we shall deal with have the following structure: If the name
    contains `\./' or `\.:' (for Amiga only), the file area consists of all
    characters up to and including the final such character; otherwise the file
    area is null. If the remaining file name contains `\..', the file extension
    consists of all such characters from the last `\..' to the end, otherwise the
    file extension is null.

    We can scan such file names easily by using two global variables that keep
    track of the occurrences of area and extension delimiters:

*/

/*tex the most recent `\./', if any */

pool_pointer area_delimiter;

/*tex the relevant `\..', if any */

pool_pointer ext_delimiter;

/*tex

    Input files that can't be found in the user's area may appear in a standard
    system area called |TEX_area|. Font metric files whose areas are not given
    explicitly are assumed to appear in a standard system area called
    |TEX_font_area|. $\Omega$'s compiled translation process files whose areas
    are not given explicitly are assumed to appear in a standard system area.
    These system area names will, of course, vary from place to place.

*/

#define append_to_fn(A) do {                                    \
        c=(A);                                                  \
        if (c!='"') {                                           \
            if (k<file_name_size) fn[k++]=(unsigned char)(c);   \
        }                                                       \
    } while (0)


char *pack_file_name(str_number n, str_number a, str_number e)
{
    /*tex character being packed */
    ASCII_code c;
    /*tex index into |str_pool| */
    unsigned char *j;
    /*tex number of positions filled in |fn| */
    int k = 0;
    unsigned char *fn = xmallocarray(packed_ASCII_code, str_length(a) + str_length(n) + str_length(e) + 1);
    for (j = str_string(a); j < str_string(a) + str_length(a); j++)
        append_to_fn(*j);
    for (j = str_string(n); j < str_string(n) + str_length(n); j++)
        append_to_fn(*j);
    for (j = str_string(e); j < str_string(e) + str_length(e); j++)
        append_to_fn(*j);
    fn[k] = 0;
    return (char *) fn;
}

/*tex

    A messier routine is also needed, since format file names must be scanned
    before \TeX's string mechanism has been initialized. We shall use the global
    variable |TEX_format_default| to supply the text for default system areas and
    extensions related to format files.

    Under \UNIX\ we don't give the area part, instead depending on the path
    searching that will happen during file opening. Also, the length will be set
    in the main program.

*/

char *TEX_format_default;


/*tex

    This part of the program becomes active when a ``virgin'' \TeX\ is trying to
    get going, just after the preliminary initialization, or when the user is
    substituting another format file by typing `\.\&' after the initial `\.{**}'
    prompt. The buffer contains the first line of input in
    |buffer[loc..(last-1)]|, where |loc<last| and |buffer[loc]<>" "|.

*/

char *open_fmt_file(void)
{
    /*tex The first space after the format file name: */
    int j;
    char *fmt = NULL;
    int dist;
    j = iloc;
    if (buffer[iloc] == '&') {
        incr(iloc);
        j = iloc;
        buffer[last] = ' ';
        while (buffer[j] != ' ')
            incr(j);
        fmt = xmalloc((unsigned) (j - iloc + 1));
        strncpy(fmt, (char *) (buffer + iloc), (size_t) (j - iloc));
        fmt[j - iloc] = 0;
        dist = (int) (strlen(fmt) - strlen(DUMP_EXT));
        if (!(strstr(fmt, DUMP_EXT) == fmt + dist))
            fmt = concat(fmt, DUMP_EXT);
        if (zopen_w_input(&fmt_file, fmt, DUMP_FORMAT, FOPEN_RBIN_MODE))
            goto FOUND;
        wake_up_terminal();
        fprintf(stdout, "Sorry, I can't find the format `%s'; will try `%s'.\n",
                fmt, TEX_format_default);
        update_terminal();
    }
    /*tex Now pull out all the stops: try for the system \.{plain} file. */
    fmt = TEX_format_default;
    if (!zopen_w_input(&fmt_file, fmt, DUMP_FORMAT, FOPEN_RBIN_MODE)) {
        wake_up_terminal();
        fprintf(stdout, "I can't find the format file `%s'!\n",
                TEX_format_default);
        return NULL;
    }
  FOUND:
    iloc = j;
    return fmt;
}

/*tex

    The global variable |name_in_progress| is used to prevent recursive use of
    |scan_file_name|, since the |begin_name| and other procedures communicate via
    global variables. Recursion would arise only by devious tricks like
    `\.{\\input\\input f}'; such attempts at sabotage must be thwarted.
    Furthermore, |name_in_progress| prevents \.{\\input} from being initiated
    when a font size specification is being scanned.

    Another global variable, |job_name|, contains the file name that was first
    \.{\\input} by the user. This name is extended by `\.{.log}' and `\.{.dvi}'
    and `\.{.fmt}' in the names of \TeX's output files.

*/

/*tex is a file name being scanned? */

boolean name_in_progress;

/*tex principal file name */

str_number job_name;

/*tex has the transcript file been opened? */

boolean log_opened_global;

/*tex

    Initially |job_name=0|; it becomes nonzero as soon as the true name is known.
    We have |job_name=0| if and only if the `\.{log}' file has not been opened,
    except of course for a short time just after |job_name| has become nonzero.

*/

/*tex full name of the log file */

unsigned char *texmf_log_name;

/*tex

    The |open_log_file| routine is used to open the transcript file and to help
    it catch up to what has previously been printed on the terminal.

*/

void open_log_file(void)
{
    /*tex previous |selector| setting */
    int old_setting;
    /*tex index into |buffer| */
    int k;
    /*tex end of first input line */
    int l;
    char *fn;
    old_setting = selector;
    if (job_name == 0)
        job_name = getjobname(maketexstring("texput"));
    fn = pack_job_name(".fls");
    recorder_change_filename(fn);
    fn = pack_job_name(".log");
    while (!lua_a_open_out(&log_file, fn, 0)) {
        /*tex

            Try to get a different log file name. Sometimes |open_log_file| is
            called at awkward moments when \TeX\ is unable to print error
            messages or even to |show_context|. The |prompt_file_name| routine
            can result in a |fatal_error|, but the |error| routine will not be
            invoked because |log_opened| will be false.

            The normal idea of |batch_mode| is that nothing at all should be
            written on the terminal. However, in the unusual case that no log
            file could be opened, we make an exception and allow an explanatory
            message to be seen.

            Incidentally, the program always refers to the log file as a
            `\.{transcript file}', because some systems cannot use the extension
            `\.{.log}' for this file.
        */
        selector = term_only;
        fn = prompt_file_name("transcript file name", ".log");
    }
    texmf_log_name = (unsigned char *) xstrdup(fn);
    selector = log_only;
    log_opened_global = true;
    if (callback_defined(start_run_callback) == 0) {
        /*tex Print the banner line, including current date and time. */
        log_banner(luatex_version_string);
        /*tex Make sure bottom level is in memory. */
        input_stack[input_ptr] = cur_input;
        tprint_nl("**");
        /*tex The last position of first line. */
        l = input_stack[0].limit_field;
        if (buffer[l] == end_line_char_par) {
            /*tex maybe also handle multichar endlinechar */
            decr(l);
        }
        for (k = 1; k <= l; k++) {
            print_char(buffer[k]);
        }
        /*tex now the transcript file contains the first line of input */
        print_ln();
    }
    /*tex should be done always */
    flush_loggable_info();
    /*tex should be done always */
    selector = old_setting + 2;
}

/*tex

    This function is needed by synctex to make its log appear in the right spot
    when |output_directory| is set.

*/

char *get_full_log_name (void)
{
   if (output_directory) {
       char *ret  = xmalloc(strlen((char *)texmf_log_name)+2+strlen(output_directory));
       ret = strcpy(ret, output_directory);
       strcat(ret, "/");
       strcat(ret, (char *)texmf_log_name);
       return ret;
   } else {
       return xstrdup((const char*)texmf_log_name);
   }
}

/*tex Synctex uses this to get the anchored path of an input file. */

char *luatex_synctex_get_current_name (void)
{
  char *pwdbuf = NULL, *ret;
  if (kpse_absolute_p(fullnameoffile, false)) {
     return xstrdup(fullnameoffile);
  }
  pwdbuf = xgetcwd();
  ret = concat3(pwdbuf, DIR_SEP_STRING, fullnameoffile);
  free(pwdbuf) ;
  return ret;
}

/*tex

    Let's turn now to the procedure that is used to initiate file reading when an
    `\.{\\input}' command is being processed.

*/

void start_input(void)
{
    str_number temp_str;
    char *fn;
    do {
        get_x_token();
    } while ((cur_cmd == spacer_cmd) || (cur_cmd == relax_cmd));

    back_input();
    if (cur_cmd != left_brace_cmd) {
        /*tex Set |cur_name| to desired file name. */
        scan_file_name();
    } else {
        scan_file_name_toks();
    }
    fn = pack_file_name(cur_name, cur_area, cur_ext);
    while (1) {
        /*tex Set up |cur_file| and new level of input. */
        begin_file_reading();
        if (lua_a_open_in(&cur_file, fn, 0)) {
            break;
        }
        /*tex Remove the level that didn't work. */
        end_file_reading();
        fn = prompt_file_name("input file name", "");
    }
    iname = maketexstring(fullnameoffile);
    /*tex

        Now that we have |fullnameoffile|, it is time to post-adjust |cur_name|
        and |cur_ext| for trailing |.tex|.

    */
    {
        char *n, *p;
        n = p = fullnameoffile + strlen(fullnameoffile);
        while (p>fullnameoffile) {
            p--;
            if (IS_DIR_SEP(*p)) {
                break;
            }
        }
        if (IS_DIR_SEP(*p)) {
            p++;
        }
        while (n>fullnameoffile) {
            n--;
            if (*n == '.') {
                break;
            }
        }
        if (n>p) {
            int q = *n;
            cur_ext = maketexstring(n);
            *n = 0;
            cur_name = maketexstring(p);
            *n = q;
        }
    }
    source_filename_stack[in_open] = iname;
    full_source_filename_stack[in_open] = xstrdup(fullnameoffile);
    /*tex We can try to conserve string pool space now. */
    temp_str = search_string(iname);
    if (temp_str > 0) {
        flush_str(iname);
        iname = temp_str;
    }
    if (job_name == 0) {
        job_name = getjobname(cur_name);
        open_log_file();
    }
    /*tex

        |open_log_file| doesn't |show_context|, so |limit| and |loc| needn't be
        set to meaningful values yet.

    */
    report_start_file(filetype_tex,fullnameoffile);
    incr(open_parens);
    update_terminal();
    istate = new_line;
    /*tex Prepare new file {\sl Sync\TeX} information. */
    if (! synctex_get_no_files()) {
        /*tex Give control to the {\sl Sync\TeX} controller. */
        synctexstartinput();
    }
    /*tex

        Read the first line of the new file. Here we have to remember to tell the
        |lua_input_ln| routine not to start with a |get|. If the file is empty,
        it is considered to contain a single blank line.

    */
    line = 1;
    if (lua_input_ln(cur_file, 0, false)) {
        ;
    }
    firm_up_the_line();
    if (end_line_char_inactive)
        decr(ilimit);
    else
        buffer[ilimit] = (packed_ASCII_code) end_line_char_par;
    first = ilimit + 1;
    iloc = istart;
}

/*tex

    Because the format is zipped we read and write dump files through zlib.
    Earlier versions recast |*f| from |FILE *| to |gzFile|, but there is no
    guarantee that these have the same size, so a static variable is needed.

*/

static gzFile gz_fmtfile = NULL;

/*tex

    As distributed, the dump files are architecture dependent; specifically,
    BigEndian and LittleEndian architectures produce different files. These
    routines always output BigEndian files. This still does not guarantee them to
    be architecture-independent, because it is possible to make a format that
    dumps a glue ratio, i.e., a floating-point number. Fortunately, none of the
    standard formats do that.

*/

#if !defined (WORDS_BIGENDIAN) && !defined (NO_DUMP_SHARE)

/*tex

    This macro is always invoked as a statement. It assumes a variable `temp'.

*/

#  define SWAP(x, y) do { temp = x; x = y; y = temp; } while (0)

/*tex

    Make the NITEMS items pointed at by P, each of size SIZE, be the
    opposite-endianness of whatever they are now.

*/

static void swap_items(char *pp, int nitems, int size)
{
    char temp;
    unsigned total = (unsigned) (nitems * size);
    char *q = xmalloc(total);
    char *p = q;
    memcpy(p,pp,total);
    /*tex

        Since `size' does not change, we can write a while loop for each case,
        and avoid testing `size' for each time.

    */
    switch (size) {
        case 16:
            /*tex

                16-byte items happen on the DEC Alpha machine when we are not doing
                sharable memory dumps.

            */
            while (nitems--) {
                SWAP(p[0], p[15]);
                SWAP(p[1], p[14]);
                SWAP(p[2], p[13]);
                SWAP(p[3], p[12]);
                SWAP(p[4], p[11]);
                SWAP(p[5], p[10]);
                SWAP(p[6], p[9]);
                SWAP(p[7], p[8]);
                p += size;
            }
            break;

        case 12:
            while (nitems--) {
                SWAP(p[0], p[11]);
                SWAP(p[1], p[10]);
                SWAP(p[2], p[9]);
                SWAP(p[3], p[8]);
                SWAP(p[4], p[7]);
                SWAP(p[5], p[6]);
                p += size;
            }
            break;

        case 8:
            while (nitems--) {
                SWAP(p[0], p[7]);
                SWAP(p[1], p[6]);
                SWAP(p[2], p[5]);
                SWAP(p[3], p[4]);
                p += size;
            }
            break;

        case 4:
            while (nitems--) {
                SWAP(p[0], p[3]);
                SWAP(p[1], p[2]);
                p += size;
            }
            break;

        case 2:
            while (nitems--) {
                SWAP(p[0], p[1]);
                p += size;
            }
            break;
        case 1:
            /*tex Nothing to do. */
            break;
        default:
            FATAL1("Can't swap a %d-byte item for (un)dumping", size);
    }
    memcpy(pp,q,total);
    xfree(q);
}
#endif

/*tex

    That second swap is to make sure following calls don't get confused in the
    case of |dump_things|.

*/

void do_zdump(char *p, int item_size, int nitems, FILE * out_file)
{
    int err;
    (void) out_file;
    if (nitems == 0)
        return;
#if !defined (WORDS_BIGENDIAN) && !defined (NO_DUMP_SHARE)
    swap_items(p, nitems, item_size);
#endif
    if (gzwrite(gz_fmtfile, (void *) p, (unsigned) (item_size * nitems)) !=
        item_size * nitems) {
        fprintf(stderr, "! Could not write %d %d-byte item(s): %s.\n", nitems, item_size, gzerror(gz_fmtfile, &err));
        uexit(1);
    }
#if !defined (WORDS_BIGENDIAN) && !defined (NO_DUMP_SHARE)
    swap_items(p, nitems, item_size);
#endif
}

void do_zundump(char *p, int item_size, int nitems, FILE * in_file)
{
    int err;
    (void) in_file;
    if (nitems == 0)
        return;
    if (gzread(gz_fmtfile, (void *) p, (unsigned) (item_size * nitems)) <= 0) {
        fprintf(stderr, "Could not undump %d %d-byte item(s): %s.\n", nitems, item_size, gzerror(gz_fmtfile, &err));
        uexit(1);
    }
#if !defined (WORDS_BIGENDIAN) && !defined (NO_DUMP_SHARE)
    swap_items(p, nitems, item_size);
#endif
}

/*tex

    Tests has shown that a level 3 compression is the most optimal tradeoff
    between file size and load time.

*/

#define COMPRESSION "R3"

boolean zopen_w_input(FILE ** f, const char *fname, int format, const_string fopen_mode)
{
    int callbackid;
    int res;
    char *fnam;
    callbackid = callback_defined(find_format_file_callback);
    if (callbackid > 0) {
        res = run_callback(callbackid, "S->R", fname, &fnam);
        if (res && fnam && strlen(fnam) > 0) {
            *f = fopen(fnam, fopen_mode);
            if (*f == NULL) {
                return 0;
            }
        } else {
            return 0;
        }
    } else {
        res = luatex_open_input(f, fname, format, fopen_mode, true);
    }
    if (res) {
        gz_fmtfile = gzdopen(fileno(*f), "rb" COMPRESSION);
    }
    return res;
}

boolean zopen_w_output(FILE ** f, const char *s, const_string fopen_mode)
{
    int res = 1;
    if (luainit) {
        *f = fopen(s, fopen_mode);
        if (*f == NULL) {
            return 0;
        }
    } else {
        res = luatex_open_output(f, s, fopen_mode);
    }
    if (res) {
        gz_fmtfile = gzdopen(fileno(*f), "wb" COMPRESSION);
    }
    return res;
}

void zwclose(FILE * f)
{
    (void) f;
    gzclose(gz_fmtfile);
}

/*tex Create the \DVI\ or \PDF\ file. */

int open_outfile(FILE ** f, const char *name, const char *mode)
{
    FILE *res;
    res = fopen(name, mode);
    if (res != NULL) {
        *f = res;
        return 1;
    }
    return 0;
}

/*tex The caller should set |tfm_buffer=NULL| and |tfm_size=0|. */

int readbinfile(FILE * f, unsigned char **tfm_buffer, int *tfm_size)
{
    void *buf;
    int size;
    if (fseek(f, 0, SEEK_END) == 0) {
        size = (int) ftell(f);
        if (size > 0) {
            buf = xmalloc((unsigned) size);
            if (fseek(f, 0, SEEK_SET) == 0) {
                if (fread((void *) buf, (size_t) size, 1, f) == 1) {
                    *tfm_buffer = (unsigned char *) buf;
                    *tfm_size = size;
                    return 1;
                }
            }
        } else {
            *tfm_buffer = NULL;
            *tfm_size = 0;
            return 1;
        }
    }
    /*tex Either seek failed or we have a zero-sized file. */
    return 0;
}

/*tex

    Like |os.execute()|, the |runpopen()| function is called only when
    |shellenabledp == 1|. Unlike |os.execute()| we write errors to stderr, since
    we have nowhere better to use; and of course we return a file handle (or
    NULL) instead of a status indicator.

*/

static FILE *runpopen(char *cmd, const char *mode)
{
    FILE *f = NULL;
    char *safecmd = NULL;
    char *cmdname = NULL;
    int allow;
#ifdef WIN32
    char *pp;

    for (pp = cmd; *pp; pp++) {
      if (*pp == '\'') *pp = '"';
    }
#endif
    /*tex If |restrictedshell| is zero, any command is allowed. */
    if (restrictedshell == 0) {
        allow = 1;
    } else {
        const char *thecmd = cmd;
        allow = shell_cmd_is_allowed(thecmd, &safecmd, &cmdname);
    }
    if (allow == 1)
        f = popen(cmd, mode);
    else if (allow == 2)
        f = popen(safecmd, mode);
    else if (allow == -1)
        fprintf(stderr, "\nrunpopen quotation error in command line: %s\n", cmd);
    else
        fprintf(stderr, "\nrunpopen command not allowed: %s\n", cmdname);
    if (safecmd)
        free(safecmd);
    if (cmdname)
        free(cmdname);
    return f;
}

/*tex

    The code that implements |popen()| needs an array for tracking possible pipe
    file pointers, because these need to be closed using |pclose()|.

*/

#define NUM_PIPES 16
static FILE *pipes[NUM_PIPES];

#ifdef WIN32
FILE *Poptr;
#endif

boolean open_in_or_pipe(FILE ** f_ptr, char *fn, int filefmt, const_string fopen_mode, boolean must_exist)
{
    string fname = NULL;
    int i;
    /*tex

        Opening a read pipe is straightforward, only have to skip past the pipe
        symbol in the file name. filename quoting is assumed to happen elsewhere
        (it does :-))

    */
    if (shellenabledp && *fn == '|') {
        /*tex The user requested a pipe. */
        *f_ptr = NULL;
        fname = (string) xmalloc((unsigned) (strlen(fn) + 1));
        strcpy(fname, fn);
        if (fullnameoffile)
            free(fullnameoffile);
        fullnameoffile = xstrdup(fname);
        recorder_record_input(fname + 1);
        *f_ptr = runpopen(fname + 1, "r");
        free(fname);
        for (i = 0; i < NUM_PIPES; i++) {
            if (pipes[i] == NULL) {
                pipes[i] = *f_ptr;
                break;
            }
        }
        if (*f_ptr)
            setvbuf(*f_ptr, (char *) NULL, _IONBF, 0);
#ifdef WIN32
        Poptr = *f_ptr;
#endif
        return *f_ptr != NULL;
    }
    return luatex_open_input(f_ptr, fn, filefmt, fopen_mode, must_exist);
}


boolean open_out_or_pipe(FILE ** f_ptr, char *fn, const_string fopen_mode)
{
    string fname;
    int i;
    /*tex

        Opening a write pipe takes a little bit more work, because TeX will
        perhaps have appended ".tex". To avoid user confusion as much as
        possible, this extension is stripped only when the command is a bare
        word. Some small string trickery is needed to make sure the correct
        number of bytes is free()-d afterwards.
    */
    if (shellenabledp && *fn == '|') {
        /*tex The user requested a pipe. */
        fname = (string) xmalloc((unsigned) (strlen(fn) + 1));
        strcpy(fname, fn);
        if (strchr(fname, ' ') == NULL && strchr(fname, '>') == NULL) {
            /*tex

                \METAPOST\ and \METAFIONT\ currently do not use this code, but it
                is better to be prepared. Hm, what has this todo with \LUATEX ?

            */
            if (STREQ((fname + strlen(fname) - 3), "tex"))
                *(fname + strlen(fname) - 4) = 0;
            *f_ptr = runpopen(fname + 1, "w");
            *(fname + strlen(fname)) = '.';
        } else {
            *f_ptr = runpopen(fname + 1, "w");
        }
        recorder_record_output(fname + 1);
        free(fname);
        for (i = 0; i < NUM_PIPES; i++) {
            if (pipes[i] == NULL) {
                pipes[i] = *f_ptr;
                break;
            }
        }
        if (*f_ptr)
            setvbuf(*f_ptr, (char *) NULL, _IONBF, 0);
        return *f_ptr != NULL;
    }
    return luatex_open_output(f_ptr, fn, fopen_mode);
}


void close_file_or_pipe(FILE * f)
{
    int i;
    if (shellenabledp) {
        for (i = 0; i <= 15; i++) {
            /*tex If this file was a pipe, |pclose()| it and return. */
            if (pipes[i] == f) {
                if (f) {
                    pclose(f);
#ifdef WIN32
                    Poptr = NULL;
#endif
                }
                pipes[i] = NULL;
                return;
            }
        }
    }
    close_file(f);
}