File: lua.trm

package info (click to toggle)
gnuplot 6.0.2%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 14,936 kB
  • sloc: ansic: 95,319; cpp: 7,590; makefile: 2,470; javascript: 2,328; sh: 1,531; lisp: 664; perl: 304; pascal: 191; tcl: 88; python: 46
file content (1525 lines) | stat: -rw-r--r-- 40,578 bytes parent folder | download | duplicates (2)
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
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
/*
 *  GNUPLOT - lua.trm
 */

/*[
 *
 * Copyright 2008   Peter Hedwig <peter@affenbande.org>
 *
 *
 * Permission to use, copy, and distribute this software and its
 * documentation for any purpose with or without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.
 *
 * Permission to modify the software is granted, but not the right to
 * distribute the complete modified source code.  Modifications are to
 * be distributed as patches to the released version.  Permission to
 * distribute binaries produced by compiling modified sources is granted,
 * provided you
 *   1. distribute the corresponding source modifications from the
 *    released version in the form of a patch file along with the binaries,
 *   2. add special version identification to distinguish your version
 *    in addition to the base release version number,
 *   3. provide your name and address as the primary contact for the
 *    support of your modified version, and
 *   4. retain our contact information in regard to use of the base
 *    software.
 * Permission to distribute the released version of the source code along
 * with corresponding source modifications in the form of a patch file is
 * granted with same provisions 2 through 4 for binary distributions.
 *
 * This software is provided "as is" without express or implied warranty
 * to the extent permitted by applicable law.
]*/


#include "driver.h"

#define LUA_TERM_REVISION "$Rev: Jun 2020$"

#ifdef TERM_REGISTER
register_term(lua)
#endif

#ifdef TERM_PROTO
TERM_PUBLIC void LUA_options(void);
TERM_PUBLIC void LUA_init(void);
TERM_PUBLIC void LUA_reset(void);
TERM_PUBLIC void LUA_text(void);
/* scale */
TERM_PUBLIC void LUA_graphics(void);
TERM_PUBLIC void LUA_move(unsigned int x, unsigned int y);
TERM_PUBLIC void LUA_vector(unsigned int ux, unsigned int uy);
TERM_PUBLIC void LUA_linetype(int linetype);
TERM_PUBLIC void LUA_dashtype(int type, t_dashtype *custom_dash_type);
TERM_PUBLIC void LUA_put_text(unsigned int x, unsigned int y, const char str[]);
TERM_PUBLIC int  LUA_text_angle(float ang);
TERM_PUBLIC int  LUA_justify_text(enum JUSTIFY mode);
TERM_PUBLIC void LUA_point(unsigned int x, unsigned int y, int number);
TERM_PUBLIC void LUA_arrow(unsigned int sx, unsigned int sy, unsigned int ex, unsigned int ey, int head);
TERM_PUBLIC int  LUA_set_font(const char *font);
TERM_PUBLIC void LUA_pointsize(double ptsize);
TERM_PUBLIC void LUA_boxfill(int style, unsigned int x1,
                             unsigned int y1, unsigned int width,
                             unsigned int height);
TERM_PUBLIC void LUA_linewidth(double width);
TERM_PUBLIC int  LUA_make_palette(t_sm_palette *);
TERM_PUBLIC void LUA_previous_palette(void);
TERM_PUBLIC void LUA_set_color(t_colorspec *);
TERM_PUBLIC void LUA_filled_polygon(int, gpiPoint *);
TERM_PUBLIC void LUA_image(unsigned, unsigned, coordval *, gpiPoint *, t_imagecolor);
TERM_PUBLIC void LUA_path(int p);
TERM_PUBLIC void LUA_boxed_text(unsigned int, unsigned int, int);

/* defaults */
#define LUA_XMAX 10000.0
#define LUA_YMAX 10000.0

#define LUA_HTIC	100
#define LUA_VTIC	100
#define LUA_HCHAR	160
#define LUA_VCHAR	420
#define LUA_TERM_DESCRIPTION "Lua generic terminal driver"

/* gnuplot 4.3, term->tscale */
#define LUA_TSCALE   1.0

#endif /* TERM_PROTO */


#ifndef TERM_PROTO_ONLY
#ifdef TERM_BODY


#ifdef HAVE_CAIROPDF
# include "wxterminal/gp_cairo.h"
# include "wxterminal/gp_cairo_helpers.h"
# define LUA_EXTERNAL_IMAGES 1
#elif defined(HAVE_GD_PNG) && (GD2_VERS >= 2)
# include "gd.h"
# define LUA_EXTERNAL_IMAGES 1
#endif

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

static lua_State *L = NULL;

static char *LUA_script = NULL;

static int lua_term_status, lua_term_result;
static int tb, luaterm, image_cnt, image_extern;

#if LUA_VERSION_NUM > 501
/*
 * two helper functions to ease transitioning to lua 5.2
 */

/*
 * same as lua_getfield(L, LUA_GLOBALINDEXS, f) in lua 5.1
 */
static void LUA_getfield_global(lua_State *L, const char *f)
{
  lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
  lua_getfield(L, -1, f);
  lua_replace(L, -2);
}
/*
 * approximately the same as luaL_register(L, libname, l) in lua 5.1
 */
static void LUA_register(lua_State *L, const char *libname, const luaL_Reg *l)
{
  if (!libname)
    luaL_setfuncs(L, l, 0);
  else {
    LUA_getfield_global(L, "package");
    lua_getfield(L, -1, "loaded");
    lua_newtable(L);
    luaL_setfuncs(L, l, 0);
    lua_pushvalue(L, -1);
    lua_setglobal(L, libname);
    lua_setfield(L, -2, libname);
    lua_pop(L, 2);
    lua_getglobal(L, libname);
  }
}
#endif /* LUA_VERSION_NUM > 501 */

/*
 * static buffer, because we cannot free memory after
 * calling int_error that never returns
 */
static char last_error_msg[MAX_LINE_LEN+1] = "";

/*
 * Handle Lua functions
 */
#define LUA_GP_FNC "gp"

/*
 *  returns a table with the coords of
 *  the plot's bounding box
 */
static int
LUA_GP_get_boundingbox(lua_State *L) {
  lua_newtable (L);
  lua_pushstring (L, "xleft");
  lua_pushinteger(L, plot_bounds.xleft);
  lua_rawset (L, -3);
  lua_pushstring (L, "xright");
  lua_pushinteger(L, plot_bounds.xright);
  lua_rawset (L, -3);
  lua_pushstring (L, "ybot");
  lua_pushinteger(L, plot_bounds.ybot);
  lua_rawset (L, -3);
  lua_pushstring (L, "ytop");
  lua_pushinteger(L, plot_bounds.ytop);
  lua_rawset (L, -3);
  return(1);
}

/* gp.term_options(char *str) */
static int
LUA_GP_term_options(lua_State *L) {
  int n = lua_gettop(L);  /* Number of arguments */
  const char *opt_str;
  if (n != 1)
    return luaL_error(L, "Got %d arguments expected 1", n);

  opt_str = luaL_checkstring(L, 1);
  n = strlen(opt_str);
  if (n > MAX_LINE_LEN)
    return luaL_error(L, "Option string consists of %d characters but only %d are allowed", n, MAX_LINE_LEN);

  strncpy(term_options, opt_str, MAX_LINE_LEN);
  term_options[MAX_LINE_LEN] = '\0';
  return(0);
}


/* close Lua context and clean up */
static void
LUA_close(void) {
  if (L) {
    lua_close(L);
    L = NULL;
  }
  if (LUA_script) {
    free(LUA_script);
    LUA_script = NULL;
  }
}

/* gp.write(char *str) */
static int
LUA_GP_write(lua_State *L) {
  int n = lua_gettop(L);  /* Number of arguments */
  const char *out_str;
  if (n != 1)
      return luaL_error(L, "Got %d arguments expected 1", n);

  out_str = luaL_checkstring(L, 1);
  fputs(out_str, gpoutfile);

  return(0);
}

/*
  gp.int_error(int t_num, char *msg)
  gp.int_error(char *msg)

 */
static int
LUA_GP_int_error(lua_State *L) {
  int t_num = NO_CARET;
  const char *msg = "";

  int n = lua_gettop(L);  /* Number of arguments */
  switch (n) {
    case 1:
      msg = luaL_checkstring(L, 1);
      break;
    case 2:
      t_num = luaL_checkinteger(L, 1);
      msg  = luaL_checkstring(L, 2);
      break;
    default:
      return luaL_error(L, "Got %d arguments expected 1 or 2", n);
      break;
  }

  snprintf(last_error_msg, MAX_LINE_LEN, "%s Lua context closed.", msg);

  /* close Lua context on fatal errors */
  LUA_close();

  int_error(t_num, last_error_msg);

  return(0);
}

/*
  gp.int_warn(int t_num, char *errmsg)
  gp.int_warn(char *errmsg)

*/
static int
LUA_GP_int_warn(lua_State *L) {
  int t_num = NO_CARET;
  const char *msg = "";

  int n = lua_gettop(L);  /* Number of arguments */
  switch (n) {
    case 1:
      msg = luaL_checkstring(L, 1);
      break;
    case 2:
      t_num = luaL_checkinteger(L, 1);
      msg = luaL_checkstring(L, 2);
      break;
    default:
      return luaL_error(L, "Got %d arguments expected 1 or 2", n);
      break;
  }
  int_warn(t_num, msg);

  return(0);
}

/*
  gp.term_out(char *terminal_msg)

  Print user messages, e.g. help messages
*/
static int
LUA_GP_term_out(lua_State *L) {
  char c;             /* dummy input char */
  char *line, *last;
  int pagelines = 0;
  const char *msg = "";

  int n = lua_gettop(L);  /* Number of arguments */
  switch (n) {
    case 1:
      msg = luaL_checkstring(L, 1);
      break;
    default:
      return luaL_error(L, "Got %d arguments expected 1", n);
      break;
  }

  last = (char *)msg;
  while ((line = strchr(last, '\n'))) {
    *line = '\0';
    if (pagelines >= 22) {
      fputs("Press return for more: ", stderr);
#if defined(ATARI) || defined(MTOS)
      do
        c = tos_getch();
      while (c != '\x04' && c != '\r' && c != '\n');
#elif defined(_WIN32) || defined(MSDOS) || defined(OS2)
      do
        c = getchar();
      while (c != EOF && c != '\n' && c != '\r');
#else
      do
        c = getchar();
      while (c != EOF && c != '\n');
#endif
      pagelines = 0;
    }
    fputs(last, stderr);
    fputs("\n", stderr);
    pagelines++;
    last = line+1;
  }
  if (*last)
    fputs(last, stderr);

  return(0);
}

/*
  gp.is_multiplot()

*/
static int
LUA_GP_is_multiplot(lua_State *L) {
  lua_pushboolean(L, multiplot);
  return(1);
}

/*
  returns all internal and userdefined variables
  [name] = {type, val1 [, val2]},
  [name] = {type, val1 [, val2]},
  ...
*/
static int
LUA_GP_get_all_variables(lua_State *L) {
  struct udvt_entry *udv = first_udv;
  struct value *val;

  lua_newtable(L);
  while (udv) {
    /* ignore mouse related variables */
    if(!strncmp(udv->udv_name, "MOUSE_", 6)) {
      udv = udv->next_udv;
      continue;
    }
    lua_newtable(L);
    if (udv->udv_value.type == NOTDEFINED) {
      lua_pushnil(L);
      lua_rawseti(L, -2, 2);
    } else {
      val = &(udv->udv_value);
      switch (val->type) {
      case INTGR:
        lua_pushstring(L, "int");
        lua_rawseti(L, -2, 2);
        lua_pushinteger(L, val->v.int_val);
        lua_rawseti(L, -2, 3);
        break;
      case CMPLX:
        if (val->v.cmplx_val.imag  != 0.0) {
          lua_pushstring(L, "cmplx");
          lua_rawseti(L, -2, 2);
          lua_pushnumber(L, val->v.cmplx_val.imag);
          lua_rawseti(L, -2, 4);
        } else {
          lua_pushstring(L, "real");
          lua_rawseti(L, -2, 2);
        }
#ifdef HAVE_ISNAN
        if (isnan(val->v.cmplx_val.real)) {
          lua_pushnil(L);
          lua_rawseti(L, -2, 3);
        } else
#endif
        {
          lua_pushnumber(L, val->v.cmplx_val.real);
          lua_rawseti(L, -2, 3);
        }
        break;
#ifdef GP_STRING_VARS
      case STRING:
        lua_pushstring(L, "string");
        lua_rawseti(L, -2, 2);
        if (val->v.string_val) {
          lua_pushstring(L, val->v.string_val);
          lua_rawseti(L, -2, 3);
        }
        break;
#endif
        default:
          lua_pushstring(L, "unknown");
          lua_rawseti(L, -2, 2);
      }
    }
    lua_setfield(L, -2, udv->udv_name);
    udv = udv->next_udv;
  }
  return(1);
}

/*
 * based on the parse_color_name() function in misc.c
 * returns rgb triplet based on color name or hex values
 */
static int
LUA_GP_parse_color_name(lua_State *L)
{
  int color = -1, token_cnt;
  int n = lua_gettop(L);  /* Number of arguments */
  const char *opt_str;
  if (n != 2)
    return luaL_error(L, "Got %d arguments expected 2", n);
  token_cnt = luaL_checkinteger(L, 1);
  opt_str = luaL_checkstring(L, 2);

  color = lookup_table_nth(pm3d_color_names_tbl, opt_str);
  if (color >= 0)
    color = pm3d_color_names_tbl[color].value;
  else
    sscanf(opt_str, "#%x", &color);
  if ((color & 0xff000000) != 0)
    int_error(token_cnt, "not recognized as a color name or a string of form \"#RRGGBB\"");

  lua_createtable(L, 3, 0);
  n = lua_gettop(L);
  lua_pushnumber(L, (double)((color >> 16 ) & 255) / 255.); lua_rawseti(L, n, 1);
  lua_pushnumber(L, (double)((color >> 8 ) & 255) / 255.); lua_rawseti(L, n, 2);
  lua_pushnumber(L, (double)(color & 255) / 255.); lua_rawseti(L, n, 3);

  return (1);
}

#if LUA_VERSION_NUM > 500
static const luaL_Reg gp_methods[] = {
#else
static const luaL_reg gp_methods[] = {
#endif
  {"write", LUA_GP_write},
  {"int_error", LUA_GP_int_error},
  {"int_warn", LUA_GP_int_warn},
  {"term_out", LUA_GP_term_out},
  {"get_boundingbox", LUA_GP_get_boundingbox},
  {"is_multiplot", LUA_GP_is_multiplot},
  {"get_all_variables", LUA_GP_get_all_variables},
  {"term_options", LUA_GP_term_options},
  {"parse_color_name", LUA_GP_parse_color_name},
  {NULL, NULL}
};


static void
LUA_register_gp_fnc (void)
{
#if LUA_VERSION_NUM > 501
  LUA_register(L, LUA_GP_FNC, gp_methods);
#else
  luaL_register(L, LUA_GP_FNC, gp_methods);
#endif
}


/*
  read variables from script
*/
static void
LUA_get_term_vars(void) {
  lua_getfield(L, luaterm, "description");
  term->description = (lua_isstring(L, -1)) ? lua_tostring(L, -1) : LUA_TERM_DESCRIPTION;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "xmax");
  term->xmax = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : LUA_XMAX;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "ymax");
  term->ymax = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : LUA_YMAX;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "v_char");
  term->v_char = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : LUA_VCHAR;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "h_char");
  term->h_char = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : LUA_HCHAR;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "v_tic");
  term->v_tic = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : LUA_VTIC;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "h_tic");
  term->h_tic = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : LUA_HTIC;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "flags");
  term->flags = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : TERM_BINARY;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "tscale");
  term->tscale = (lua_isnumber(L, -1)) ? (double)lua_tonumber(L, -1) : LUA_TSCALE;
  lua_pop(L, 1);

  lua_getfield(L, luaterm, "external_images");
  image_extern = lua_toboolean(L ,-1);
  lua_pop(L, 1);
}

static void
LUA_set_term_vars(void) {
  /* set term.version */
  lua_pushstring(L, gnuplot_version);
  lua_setfield(L, luaterm, "gp_version");
  /* set term.patchlevel */
  lua_pushstring(L, gnuplot_patchlevel);
  lua_setfield(L, luaterm, "gp_patchlevel");
  /* set term.patchlevel */
  lua_pushstring(L, LUA_TERM_REVISION);
  lua_setfield(L, luaterm, "lua_term_revision");
  /* set term.lua_ident */
  lua_pushstring(L, LUA_RELEASE);
  lua_setfield(L, luaterm, "lua_ident");
  /* set flag if terminal supports external images */
#ifdef LUA_EXTERNAL_IMAGES
  image_extern = 0;
  lua_pushboolean(L, image_extern);
  lua_setfield(L, luaterm, "external_images");
#endif
  /* some static definitions from term_api.h */
  lua_pushinteger(L, TERM_CAN_MULTIPLOT);     /* tested if stdout not redirected */
  lua_setfield(L, luaterm, "TERM_CAN_MULTIPLOT");
  lua_pushinteger(L, TERM_CANNOT_MULTIPLOT);  /* tested if stdout is redirected  */
  lua_setfield(L, luaterm, "TERM_CANNOT_MULTIPLOT");
  lua_pushinteger(L, TERM_BINARY);            /* open output file with "b"       */
  lua_setfield(L, luaterm, "TERM_BINARY");
  lua_pushinteger(L, TERM_INIT_ON_REPLOT);    /* call term->init() on replot     */
  lua_setfield(L, luaterm, "TERM_INIT_ON_REPLOT");
  lua_pushinteger(L, TERM_IS_POSTSCRIPT);     /* post, next, pslatex, etc        */
  lua_setfield(L, luaterm, "TERM_IS_POSTSCRIPT");
  lua_pushinteger(L, TERM_IS_LATEX);
  lua_setfield(L, luaterm, "TERM_IS_LATEX");
  lua_pushinteger(L, TERM_ENHANCED_TEXT);     /* enhanced text mode is enabled   */
  lua_setfield(L, luaterm, "TERM_ENHANCED_TEXT");
  lua_pushinteger(L, TERM_NO_OUTPUTFILE);     /* terminal doesn't write to a file */
  lua_setfield(L, luaterm, "TERM_NO_OUTPUTFILE");
  lua_pushinteger(L, TERM_CAN_CLIP);          /* terminal does its own clipping  */
  lua_setfield(L, luaterm, "TERM_CAN_CLIP");
  lua_pushinteger(L, TERM_CAN_DASH);          /* terminal knows dashed lines */
  lua_setfield(L, luaterm, "TERM_CAN_DASH");
  lua_pushinteger(L, TERM_ALPHA_CHANNEL);     /* alpha channel transparency      */
  lua_setfield(L, luaterm, "TERM_ALPHA_CHANNEL");
  lua_pushinteger(L, TERM_MONOCHROME);        /* term is running in mono mode    */
  lua_setfield(L, luaterm, "TERM_MONOCHROME");
  lua_pushinteger(L, TERM_LINEWIDTH);         /* support for set term linewidth  */
  lua_setfield(L, luaterm, "TERM_LINEWIDTH");
#ifdef TERM_FONTSCALE
  lua_pushinteger(L, TERM_FONTSCALE);         /* terminal supports fontscale     */
  lua_setfield(L, luaterm, "TERM_FONTSCALE");
#endif
}

static int
LUA_init_luaterm_function(const char *fnc) {
  if (!L)
    int_error(NO_CARET, "Missing Lua context! No script?");

  lua_getfield(L, luaterm, fnc);
  if(lua_isfunction(L, -1)) {
    return(1);
  } else {
    int_warn(NO_CARET, "Script lacks function `%s'!", fnc);
    lua_pop(L, 1); /* clean stack */
  }
  return(0);
}


static int
LUA_call_report (int status)
{
  if (status) {
    const char *msg = lua_tostring(L, -1);
    if (msg == NULL) msg = "(error with no message)";
    snprintf(last_error_msg, MAX_LINE_LEN, "%s. Lua context closed.", msg);
    LUA_close();
    int_error(NO_CARET, last_error_msg);
  }
  return status;
}


static int
LUA_init_lua(void)
{
  int sf; /* Lua script "function" */
  struct stat stat_buf;
  char *script_fqn;
  char *gp_lua_dir;
#if defined(_WIN32) || defined(MSDOS) || defined(OS2)
  char *free_lua_dir = NULL;
#endif

  /*
   * Close old Lua context and open a new one.
    */
  if (L)
    lua_close(L);
#if LUA_VERSION_NUM > 500
  L = luaL_newstate();
#else
  L = lua_open();
#endif

  luaL_openlibs(L); /* Load Lua libraries */
  luaopen_debug(L);

  gp_lua_dir = getenv("GNUPLOT_LUA_DIR");

# if defined(_WIN32) || defined(MSDOS) || defined(OS2)
  if (!gp_lua_dir)
    gp_lua_dir = free_lua_dir = RelativePathToGnuplot(GNUPLOT_LUA_DIR);
#else /* not _WIN32 */
  if (!gp_lua_dir)
    gp_lua_dir = GNUPLOT_LUA_DIR;
#endif

  if (stat(LUA_script, &stat_buf) || !S_ISREG(stat_buf.st_mode)) {
    script_fqn = gp_alloc(strlen(gp_lua_dir) + strlen(LUA_script) + 2, "LUA_script path");
    sprintf(script_fqn, "%s%c%s", gp_lua_dir, DIRSEP1, LUA_script);
  } else {
    script_fqn = gp_strdup(LUA_script);
  }
#if defined(_WIN32) || defined(MSDOS) || defined(OS2)
  free(free_lua_dir);
#endif

  /* Load the file containing the script we are going to run */
  lua_term_status = luaL_loadfile(L, script_fqn);
  if (lua_term_status) {
    fprintf(stderr, "error: %s. Lua context closed.\n", lua_tostring(L, -1));
    LUA_close();
    free(script_fqn);
    return(0);
  }
  free(script_fqn);

  /* remember script "function" */
  sf = lua_gettop(L);

  /*  lua_settop(L, 0);*/ /* clear stack */
#if LUA_VERSION_NUM > 501
  LUA_getfield_global(L, "debug");
#else
  lua_getfield(L, LUA_GLOBALSINDEX, "debug");
#endif
  lua_getfield(L, -1, "traceback");
  lua_remove(L, -2); /* rm debug */
  tb = lua_gettop(L); /* store "traceback" */
  /* create table `term' */
  lua_newtable(L);
  lua_setglobal(L, "term");
#if LUA_VERSION_NUM > 501
  LUA_getfield_global(L, "term");
#else
  lua_getfield(L, LUA_GLOBALSINDEX, "term");
#endif
  luaterm = lua_gettop(L); /* store `term' */

  /* register gp functions */
  LUA_register_gp_fnc();

  /* set terminal variables */
  LUA_set_term_vars();

  /* put script "function" on top and call */
  lua_pushvalue(L, sf);
  LUA_call_report(lua_pcall(L, 0, LUA_MULTRET, tb));

  return(1);
}

/* see color.h */
static const char*
LUA_get_colorstyle(int style) {
  const char *style_str = "unknown";

  switch(style) {
    case TC_LT:       /* Use the color of linetype <n> */
      style_str = "LT";
      break;
    case TC_LINESTYLE:/* Use the color of line style <n> (only for "internal" use or unused?) */
      style_str = "LINESTYLE";
      break;
    case TC_RGB:      /* Explicit RGBA values provided by user */
      style_str = "RGBA";
      break;
    case TC_CB:       /* "palette cb <value>" (only for "internal" use or unused?) */
      style_str = "CB";
      break;
    case TC_FRAC:     /* "palette frac <value>" */
      style_str = "FRAC";
      break;
    case TC_Z:        /* "palette z" (only for "internal" use or unused?) */
      style_str = "Z";
      break;
    case TC_DEFAULT:  /* Use default color, set separately (only for "internal" use or unused?) */
      style_str = "DEFAULT";
      break;
  }
  return(style_str);
}

/* see term_api.h */
static const char*
LUA_get_fillstyle(int style) {
  const char *style_str = "unknown";

  if (style == FS_OPAQUE) {
    /* FIXME: not quite sure how to handle this, since it is only used by the
      postscript terminal */
    style_str = "OPAQUE";
  } else {
    switch (style & 0xf) {
      case FS_EMPTY:
        style_str = "EMPTY";
        break;
      case FS_SOLID:
        style_str = "SOLID";
        break;
      case FS_PATTERN:
        style_str = "PATTERN";
        break;
      case FS_TRANSPARENT_SOLID:
        style_str = "TRANSPARENT_SOLID";
        break;
      case FS_TRANSPARENT_PATTERN:
        style_str = "TRANSPARENT_PATTERN";
        break;
      case FS_DEFAULT:
        style_str = "DEFAULT";
        break;
    }
  }
  return(style_str);
}




/*
 * Handle options
 */

TERM_PUBLIC void
LUA_options()
{

  char *opt_str = NULL;
  char *s;

  int tc_off = c_token+1; /* token counter offset */
  int need_init = 1;


  /* 'set term tikz' is short for 'set term lua tikz' */
  c_token--; /* see how we got here */
  if (!equals(c_token, "tikz")) {
    if (almost_equals(c_token, "termop$tions")) {
      if (!LUA_script) {
        int_error(NO_CARET, "No Lua context for setting terminal options!");
        return;
      }
      need_init = 0;
  }
    /*  else should always be lua, so just count up ... */
    c_token++;
  }

    opt_str = gp_input_line + token[c_token].start_index;

  if (need_init) {
    if (!END_OF_COMMAND) {
    if (*opt_str == '"' || *opt_str == '\'') {
      s = try_to_get_string();
        gp_expand_tilde(&s);
    } else {
      s = gp_alloc(token_len(c_token)+strlen("gnuplot-.lua")+1, "LUA_script");
      memcpy(s, "gnuplot-", 8);
      memcpy(s+8, opt_str , token_len(c_token));
      memcpy(s+8+token_len(c_token), ".lua\0", 5);
      c_token++;
    }
    if (LUA_script) {
      if (strcmp(LUA_script, s)) {
        free(LUA_script);
        LUA_script = s;
        need_init = 1;
      } else {
        free(s);
        need_init = 0;
      }
    } else {
      LUA_script = s;
    }
    opt_str = gp_input_line + token[c_token].start_index;
  } else {
    LUA_close();
    int_error(NO_CARET, "No Lua driver name or file name given!");
  }

  /* init lua when opening the terminal or on script change */
    if(!LUA_init_lua()) {
      return;
    }
  }

  /* since options are tokenized again in the script we always "finish" this here */
  while (!END_OF_COMMAND)
    c_token++;

  if(LUA_init_luaterm_function("options")) {
    /* isolate the "set term ...;" part of the command line */
    opt_str = gp_strdup(opt_str);
    opt_str[ strcspn(opt_str,";") ] = '\0';
    lua_pushstring(L, opt_str);
    lua_pushinteger(L, need_init);
    lua_pushinteger(L, tc_off);
    LUA_call_report(lua_pcall(L, 3, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
    free(opt_str);
  }

  LUA_get_term_vars();

  /* Treat "set term tikz mono" as "set term tikz; set mono" */
  if (strstr(term_options, "monochrome")) {
    monochrome = TRUE;
    init_monochrome();
 }

}


TERM_PUBLIC void
LUA_init()
{
  if (gpoutfile != stdout) {
    fseek(gpoutfile, 0, SEEK_SET);
    /* ignore compiler warnings here, because `gpoutfile' is already open */
    if (fflush(gpoutfile) || ftruncate(fileno(gpoutfile), 0))
	int_warn(NO_CARET, "Error re-writing output file: %s", strerror(errno));
  }

  /* reset image counter */
  image_cnt = 0;

  LUA_linetype(-1);
  if(LUA_init_luaterm_function("init")) {
    LUA_call_report(lua_pcall(L, 0, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}

TERM_PUBLIC void
LUA_graphics()
{
  if(LUA_init_luaterm_function("graphics")) {
    LUA_call_report(lua_pcall(L, 0, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}


TERM_PUBLIC void
LUA_text()
{
  if(LUA_init_luaterm_function("text")) {
    LUA_call_report(lua_pcall(L, 0, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}


TERM_PUBLIC void
LUA_linetype(int linetype)
{
  if(LUA_init_luaterm_function("linetype")) {
    lua_pushinteger(L, linetype);
    LUA_call_report(lua_pcall(L, 1, 1, tb));
	lua_term_result = (int)lua_tonumber(L, -1);
	lua_pop(L, 1);
  }
}


TERM_PUBLIC void
LUA_dashtype(int type, t_dashtype *custom_dash_type)
{
    int i = 0;

    if(LUA_init_luaterm_function("dashtype")) {
	lua_pushinteger(L, type);
	lua_newtable(L);
	if (type == DASHTYPE_CUSTOM) {
	    while (custom_dash_type->pattern[i] > 0) {
		lua_pushnumber(L, custom_dash_type->pattern[i]);
		i++;
		lua_rawseti(L, -2, i);
	    }
	} else {
	    lua_pushinteger(L, 0);
	    lua_rawseti(L, -2, 1);
	}
	LUA_call_report(lua_pcall(L, 2, 1, tb));
	lua_term_result = (int)lua_tonumber(L, -1);
	lua_pop(L, 1);
    }
}


TERM_PUBLIC void
LUA_move(unsigned int x, unsigned int y)
{
  if(LUA_init_luaterm_function("move")) {
    lua_pushinteger(L, (int)x);
    lua_pushinteger(L, (int)y);
    LUA_call_report(lua_pcall(L, 2, 1, tb));
	lua_term_result = (int)lua_tonumber(L, -1);
	lua_pop(L, 1);
  }
}


TERM_PUBLIC void
LUA_point(unsigned int x, unsigned int y, int number)
{

  lua_term_result = 0;

  if(LUA_init_luaterm_function("point")) {
    lua_pushinteger(L, (int)x);
    lua_pushinteger(L, (int)y);
    lua_pushinteger(L, number);
    LUA_call_report(lua_pcall(L, 3, 1, tb));
	lua_term_result = (int)lua_tonumber(L, -1);
	lua_pop(L, 1);
  }

  if (!lua_term_result) do_point(x, y, number);

}

TERM_PUBLIC void
LUA_pointsize(double ptsize)
{
  if(LUA_init_luaterm_function("pointsize")) {
    lua_pushnumber(L, ptsize);
    LUA_call_report(lua_pcall(L, 1, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}

TERM_PUBLIC void
LUA_vector(unsigned int ux, unsigned int uy)
{
  if(LUA_init_luaterm_function("vector")) {
    lua_pushinteger(L, (int)ux);
    lua_pushinteger(L, (int)uy);
    LUA_call_report(lua_pcall(L, 2, 1, tb));
	lua_term_result = (int)lua_tonumber(L, -1);
	lua_pop(L, 1);
  }
}

TERM_PUBLIC void
LUA_arrow(
    unsigned int sx, unsigned int sy,
    unsigned int ex, unsigned int ey,
    int head)
{

  /*
    if the script does not provide an `arrow' functions
    or if it returns `0' we fall back to `do_arrow'
  */
  lua_term_result = 0;

  if(LUA_init_luaterm_function("arrow")) {
    lua_pushinteger(L, (int)sx);
    lua_pushinteger(L, (int)sy);
    lua_pushinteger(L, (int)ex);
    lua_pushinteger(L, (int)ey);

    /* hidden3d uses a non-standard method of indicating NOHEAD */
    if (curr_arrow_headangle == 0 && curr_arrow_headlength > 0)
	head = NOHEAD;

    lua_pushinteger(L, head);

    /*   additional vars  */
    lua_pushinteger(L, curr_arrow_headlength);    /* access head length + angle (int) */
    lua_pushnumber(L, curr_arrow_headangle);      /* angle in degrees (double)        */
    lua_pushnumber(L, curr_arrow_headbackangle);  /* angle in degrees (double)        */
    lua_pushinteger(L, curr_arrow_headfilled);    /* arrow head filled or not         */
    LUA_call_report(lua_pcall(L, 9, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }

  if (!lua_term_result) do_arrow(sx, sy, ex, ey, head);

}


TERM_PUBLIC void
LUA_put_text(unsigned int x, unsigned int y, const char str[])
{
  if(LUA_init_luaterm_function("put_text")) {
    lua_pushinteger(L, (int)x);
    lua_pushinteger(L, (int)y);
    lua_pushstring(L, str);
    LUA_call_report(lua_pcall(L, 3, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}


TERM_PUBLIC int
LUA_justify_text(enum JUSTIFY mode)
{
  if(LUA_init_luaterm_function("justify_text")) {
    const char *m;
    switch (mode) {
      case LEFT:
        m = "left";
        break;
      default:
      case CENTRE:
        m = "center";
        break;
      case RIGHT:
        m = "right";
        break;
    }
    lua_pushstring(L, m);
    LUA_call_report(lua_pcall(L, 1, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
    return((lua_term_result ? TRUE : FALSE));
  }
  return(FALSE);
}

TERM_PUBLIC int
LUA_text_angle(float ang)
{
  if(LUA_init_luaterm_function("text_angle")) {
    lua_pushnumber(L, ang);
    LUA_call_report(lua_pcall(L, 1, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
    return(((lua_term_result || !ang ) ? TRUE : FALSE));
  }
  return((ang ? FALSE : TRUE)); /* return TRUE if called with ang==0 */
}

TERM_PUBLIC int
LUA_set_font(const char *font)
{
  if(LUA_init_luaterm_function("set_font")) {
    lua_pushstring(L, font);
    LUA_call_report(lua_pcall(L, 1, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
    if (lua_term_result) {
	lua_getfield(L, luaterm, "v_char");
	term->v_char = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : LUA_VCHAR;
	lua_pop(L, 1);
	lua_getfield(L, luaterm, "h_char");
	term->h_char = (lua_isnumber(L, -1)) ? (unsigned int)lua_tonumber(L, -1) : LUA_HCHAR;
	lua_pop(L, 1);
	return TRUE;
    }
  }
  return(FALSE);
}

TERM_PUBLIC void
LUA_boxfill (int style, unsigned int x1,
    unsigned int y1, unsigned int width,
    unsigned int height)
{

  if(LUA_init_luaterm_function("boxfill")) {
    lua_pushstring(L, LUA_get_fillstyle(style));
    lua_pushinteger(L, style >> 4);
    lua_pushinteger(L, (int)x1);
    lua_pushinteger(L, (int)y1);
    lua_pushinteger(L, (int)width);
    lua_pushinteger(L, (int)height);
    LUA_call_report(lua_pcall(L, 6, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}

TERM_PUBLIC void
LUA_linewidth(double width)
{
  if(LUA_init_luaterm_function("linewidth")) {
    lua_pushnumber(L, width);
    LUA_call_report(lua_pcall(L, 1, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}

TERM_PUBLIC void
LUA_previous_palette(void)
{
  if(LUA_init_luaterm_function("previous_palette")) {
    LUA_call_report(lua_pcall(L, 0, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}


TERM_PUBLIC void
LUA_reset(void)
{
  if(LUA_init_luaterm_function("reset")) {
    LUA_call_report(lua_pcall(L, 0, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}

TERM_PUBLIC int
LUA_make_palette (t_sm_palette *palette)
{
  if(LUA_init_luaterm_function("make_palette")) {
    LUA_call_report(lua_pcall(L, 0, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
    return(lua_term_result);
  }
  return(0); /* continuous number of colours */
}


TERM_PUBLIC void
LUA_set_color (t_colorspec *colorspec)
{

  double gray = colorspec->value;
  rgb_color color = {0.,0.,0.};
  double opacity = 1.0;

  if(LUA_init_luaterm_function("set_color")) {
    if (colorspec->type == TC_FRAC) {
      rgb1maxcolors_from_gray(gray, &color);
    } else if (colorspec->type == TC_RGB) {
      opacity = 1.0 - (double)(colorspec->lt >> 24 & 255) / 255.;
      color.r = (double)((colorspec->lt >> 16 ) & 255) / 255.;
      color.g = (double)((colorspec->lt >> 8 ) & 255) / 255.;
      color.b = (double)(colorspec->lt & 255) / 255.;
    }

    if (color.r < 1e-4) color.r = 0;
    if (color.g < 1e-4) color.g = 0;
    if (color.b < 1e-4) color.b = 0;

    lua_pushstring(L, LUA_get_colorstyle(colorspec->type));
    lua_pushinteger(L, colorspec->lt);
    lua_pushnumber(L, colorspec->value);
    lua_pushnumber(L, opacity);
    lua_pushnumber(L, color.r);
    lua_pushnumber(L, color.g);
    lua_pushnumber(L, color.b);
    LUA_call_report(lua_pcall(L, 7, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}


TERM_PUBLIC void
LUA_filled_polygon (int points, gpiPoint *corners)
{

  if(LUA_init_luaterm_function("filled_polygon")) {
    int i;
    lua_pushstring(L, LUA_get_fillstyle(corners->style));
    lua_pushinteger(L, corners->style >> 4);
    /* put all coords into a simple table */
    lua_newtable(L);
    for (i = 0; i < points; i++) {
      lua_newtable(L);
      lua_pushinteger(L, corners[i].x);
      lua_rawseti(L, -2, 1);
      lua_pushinteger(L, corners[i].y);
      lua_rawseti(L, -2, 2);
      lua_rawseti(L, -2 , i+1); /* add "subtable" */
    }
    LUA_call_report(lua_pcall(L, 3, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}

TERM_PUBLIC void
LUA_layer (t_termlayer syncpoint)
{
  if(LUA_init_luaterm_function("layer")) {
    const char *m;
    switch (syncpoint) {
      case TERM_LAYER_RESET:      /* Start of plot; reset flag */
        m = "reset";
        break;
      case TERM_LAYER_BACKTEXT:   /* Start of "back" text layer */
        m = "backtext";
        break;
      case TERM_LAYER_FRONTTEXT:  /* Start of "front" text layer */
        m = "fronttext";
        break;
      case TERM_LAYER_END_TEXT:   /* Close off front or back macro before leaving */
        m = "end_text";
        break;
      case TERM_LAYER_BEFORE_PLOT:  /* Close off front or back macro before leaving */
        m = "before_plot";
        break;
      case TERM_LAYER_AFTER_PLOT:   /* Close off front or back macro before leaving */
        m = "after_plot";
        break;
      case TERM_LAYER_BEGIN_GRID:
        m = "begin_grid";
        break;
      case TERM_LAYER_END_GRID:
        m = "end_grid";
        break;
      default:
        m = "";
        break;
    }
    lua_pushstring(L, m);
    LUA_call_report(lua_pcall(L, 1, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}

TERM_PUBLIC void
LUA_path (int path)
{
  if(LUA_init_luaterm_function("path")) {
    lua_pushinteger(L, path);
    LUA_call_report(lua_pcall(L, 1, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}

/*
  Lua table structure for the image pixel:
  pixel = {{r, g, b, [, a]}, {r, g, b [, a]}, ... , {r, g, b [, a]}}

*/
TERM_PUBLIC void
LUA_image (unsigned m, unsigned n, coordval *image, gpiPoint *corner, t_imagecolor color_mode) {
  if(LUA_init_luaterm_function("image")) {
    int i;
    rgb_color rgb1;
    coordval alpha = 0;
    char *image_file = NULL;

#ifdef LUA_EXTERNAL_IMAGES
    /* "externalize" if transparent images are used or on user request */
    if (outstr && ((color_mode == IC_RGBA) || image_extern)) {
      char *idx;
      /* cairo based png images with alpha channel */
      if ((idx = strrchr(outstr, '.')) == NULL)
        idx = strchr(outstr, '\0');
      image_file = (char*)gp_alloc((idx-outstr)+10, "LUA_image");
      strncpy(image_file, outstr, (idx-outstr) + 1);
      snprintf(image_file+(idx-outstr), 9, ".%03d.png", (unsigned char)(++image_cnt));

      write_png_image (m, n, image, color_mode, image_file);
    }
#endif

    lua_pushinteger(L, m);
    lua_pushinteger(L, n);

    lua_newtable(L); /* pixel table */
    for (i = 0; i < m*n; i++) {
      if (color_mode == IC_PALETTE) {
        /* FIXME: Is this correct? Needs a testcase. Would be nice to map it correctly to RGB. */
        rgb1maxcolors_from_gray(*image++, &rgb1);
      } else { /* IC_RGB and IC_RGBA*/
        rgb1.r = *image++;
        rgb1.g = *image++;
        rgb1.b = *image++;
        if (color_mode == IC_RGBA) alpha = (*image++)/255.;
      }
      lua_newtable(L); /* pixel color */
      lua_pushnumber(L, rgb1.r);
      lua_rawseti(L, -2, 1);
      lua_pushnumber(L, rgb1.g);
      lua_rawseti(L, -2, 2);
      lua_pushnumber(L, rgb1.b);
      lua_rawseti(L, -2, 3);
      if (color_mode == IC_RGBA) {
        lua_pushnumber(L, alpha);
        lua_rawseti(L, -2, 4);
      }
      lua_rawseti(L, -2, i+1); /* add "pixel" */
    }

    lua_newtable(L); /* "corner" table */
    for (i = 0; i < 4; i++) {
      lua_newtable(L);
      lua_pushinteger(L, (int)corner[i].x);
      lua_rawseti(L, -2, 1);
      lua_pushinteger(L, (int)corner[i].y);
      lua_rawseti(L, -2, 2);
      lua_rawseti(L, -2 , i+1); /* add "subtable" */
    }
    switch (color_mode) {
      case IC_PALETTE:
      case IC_RGB:
      lua_pushstring(L, "RGB");
        break;
      case IC_RGBA:
        lua_pushstring(L, "RGBA");
        break;
    }
    if (image_file) {
      lua_pushstring(L, image_file);
      free(image_file);
    } else {
      lua_pushnil(L);
    }
    LUA_call_report(lua_pcall(L, 6, 1, tb));
    lua_term_result = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }
}


TERM_PUBLIC void
LUA_boxed_text(unsigned int x, unsigned int y, int option)
{
    const char *option_str = "UNKNOWN";
    switch (option) {
    case TEXTBOX_INIT:
	option_str = "INIT";
	break;
    case TEXTBOX_OUTLINE:
	option_str = "OUTLINE";
	break;
    case TEXTBOX_BACKGROUNDFILL:
	option_str = "BACKGROUNDFILL";
	break;
    case TEXTBOX_MARGINS:
	option_str = "MARGINS";
	break;
    default:
	break;
    }

    if(LUA_init_luaterm_function("boxed_text")) {
	lua_pushinteger(L, x);
	lua_pushinteger(L, y);
	lua_pushstring(L, option_str);
	LUA_call_report(lua_pcall(L, 3, 1, tb));
	lua_term_result = (int)lua_tonumber(L, -1);
	lua_pop(L, 1);
    }
}

#endif /* TERM_BODY */


#ifdef TERM_TABLE

TERM_TABLE_START(lua_driver)
    "lua", LUA_TERM_DESCRIPTION,
    LUA_XMAX, LUA_YMAX, LUA_VCHAR, LUA_HCHAR,
    LUA_VTIC, LUA_HTIC, LUA_options, LUA_init, LUA_reset,
    LUA_text, null_scale, LUA_graphics, LUA_move, LUA_vector,
    LUA_linetype, LUA_put_text, LUA_text_angle,
    LUA_justify_text, LUA_point, LUA_arrow, LUA_set_font, LUA_pointsize,
    TERM_BINARY /*flags*/, 0 /*suspend*/, 0 /*resume*/,
    LUA_boxfill, LUA_linewidth
#ifdef USE_MOUSE
    , 0, 0, 0, 0, 0
#endif
    , LUA_make_palette, LUA_previous_palette,  LUA_set_color
    , LUA_filled_polygon
    , LUA_image
   , 0, 0, 0
   , LUA_layer
   , LUA_path
   , LUA_TSCALE
    , NULL /* hypertext */
    , LUA_boxed_text
    , NULL /* modify plots */
    , LUA_dashtype
TERM_TABLE_END(lua_driver)

#undef LAST_TERM
#define LAST_TERM lua_driver

TERM_TABLE_START(tikz_driver)
    "tikz", "TeX TikZ graphics macros via the lua script driver",
    LUA_XMAX, LUA_YMAX, LUA_VCHAR, LUA_HCHAR,
    LUA_VTIC, LUA_HTIC, LUA_options, LUA_init, LUA_reset,
    LUA_text, null_scale, LUA_graphics, LUA_move, LUA_vector,
    LUA_linetype, LUA_put_text, LUA_text_angle,
    LUA_justify_text, LUA_point, LUA_arrow, LUA_set_font, LUA_pointsize,
    TERM_BINARY /*flags*/, 0 /*suspend*/, 0 /*resume*/,
    LUA_boxfill, LUA_linewidth
#ifdef USE_MOUSE
    , 0, 0, 0, 0, 0
#endif
    , LUA_make_palette, LUA_previous_palette,  LUA_set_color
    , LUA_filled_polygon
    , LUA_image
   , 0, 0, 0
   , LUA_layer
   , LUA_path
   , LUA_TSCALE
    , NULL /* hypertext */
    , LUA_boxed_text
    , NULL /* modify plots */
    , LUA_dashtype
TERM_TABLE_END(tikz_driver)

#undef LAST_TERM
#define LAST_TERM tikz_driver

#endif /* TERM_TABLE */
#endif /* TERM_PROTO_ONLY */

#ifdef TERM_HELP
START_HELP(lua)
"1 lua",
"?commands set terminal lua",
"?set terminal lua",
"?set term lua",
"?terminal lua",
"?term lua",
"?lua",
" The `lua` generic terminal driver works in conjunction with an",
" external Lua script to create a target-specific plot file.",
" Currently the only supported target is TikZ -> pdflatex.",
"",
" Information about Lua is available at http://www.lua.org .",
"",
" Syntax:",
"    set terminal lua <target name> | \"<file name>\"",
"                        {<script_args> ...}",
"                        {help}",
"",
" A 'target name' or 'file name' (in quotes) for a script is mandatory.",
" If a 'target name' for the script is given, the terminal will look for",
" \"gnuplot-<target name>.lua\" in the local directory and on failure in",
" the environmental variable GNUPLOT_LUA_DIR.",
"",
" All arguments will be provided to the selected script for further",
" evaluation. E.g. 'set term lua tikz help' will cause the script itself",
" to print additional help on options and choices for the script.",
#ifdef HAVE_LUA
#include "gnuplot-tikz.help"
#endif
""
END_HELP(lua)
START_HELP(tikz)
"1 tikz",
"?commands set terminal tikz",
"?set terminal tikz",
"?set term tikz",
"?terminal tikz",
"?term tikz",
"?tikz",
" This driver creates output for use with the TikZ package of graphics macros",
" in TeX.  It is currently implemented via an external lua script, and ",
" `set term tikz` is a short form of the command `set term lua tikz`.",
" See `term lua tikz` for a complete description.",
" Use the command `set term tikz help` to print terminal options."
END_HELP(tikz)
#endif /* TERM_HELP */