Source

sed / sed.c

Full commit
   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
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
#define _POSIX_C_SOURCE 200809L
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <regex.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAX_WFILES  ((size_t)  10) // minimum required by POSIX
#define LABEL_BYTES ((size_t)   9) // minimum required by POSIX + '\0'
#define SPACE_BYTES ((size_t)8192) // minimum required by POSIX

#define LENGTH(a) (sizeof(a) / sizeof(*a))
#define USE(a)    ((void)(a)) // to escape unused warnings
#define serror()  ((void)fprintf(stderr, "%s: %zu%s,%s,%d: %s\n", prog_name, line_number, __FILE__, __func__, __LINE__, strerror(errno)))
#define warn(...) do{ fprintf(stderr, "%s: %zu: ", prog_name, line_number); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); }while(0)

// Types
typedef struct {
    union {
        size_t  line_number;
        regex_t *regex;
    };
    enum {
        IGNORE, // empty address, ignore
        EVERY , // every line
        LINE  , // line number
        LAST  , // last line ($)
        REGEX , // use included regex
        LASTRE, // use most recently used regex
    } type;
} Address;

// naddr == 0 iff beg.type == EVERY  && end.type == IGNORE
// naddr == 1 iff beg.type != IGNORE && end.type == IGNORE
// naddr == 2 iff beg.type != IGNORE && end.type != IGNORE
typedef struct {
    Address       beg;
    Address       end;
    unsigned char naddr; // not necessary, but helpful
} Range;

typedef struct _command Command; // forward declaration for function pointer types

typedef int    (*Action )(void           ); // Action taken after current command executes
typedef Action (*Sedfunc)(Command*       ); // Sed function, takes current command
typedef int    (*Print  )(char*   , FILE*); // Print function for a,c,i,r
typedef char  *(*Getarg )(Command*, char*); // Read arguments for given command from line
typedef void   (*Freearg)(Command*       ); // Free anything that was malloced in Getarg

typedef struct {    // used to build the lookup table of functions
    Sedfunc  runcmd;
    Getarg   getarg;
    Freearg  freearg;
    unsigned naddr; // max addresses function takes
} Sedfunc_info;

// TODO: worth switching back to mallocing explicit types and just having a
//       void *extra instead of builtin types in the union?
struct _command {
    Range         range;
    Sedfunc_info *func;
    union {
        Command  *jump;                  // used for   b,t during execution
        char      label[LABEL_BYTES];    // used for :,b,t during building
        ptrdiff_t offset;                // used for { (instead of jump because pointers break when we realloc)
        struct {                         // used for a,c,i,r,s,y
            union {
                regex_t   *regex;        // for s regex to find
                Print      print;        // for a,c,i check_puts for r write_file
            };
            char          *text;         // y sets, s replace text, a,c,i,r text
            size_t         size;         // size of malloced char *text string
            FILE          *file;         // for w, and for s: if non NULL, file for w flag
            unsigned short occurrence;   // which match to replace, 0 for all (g flag)
            char           delim;        // s/// delimiter
            unsigned char  flag_p    :1; // print flag
            unsigned char  last_regex:1; // use last regex, not included regex
        };
    };
    unsigned char in_match:1;            // are we currently inside of a match
    unsigned char negate  :1;            // is the range negated for this command
};

typedef struct {    // used with push/pop as a dynamicly sized array
    Command **data; // was void *, any reason to keep void *?
    size_t    size;
    size_t    capacity;
} Vector;

// Globals
struct { // files for w commands and s///w flag
    char *name;
    FILE *file;
} wfiles[MAX_WFILES];

struct { // global flags
    unsigned char n       :1; // -n (no print)
    unsigned char s       :1; // s/// happened
    unsigned char aci_cont:1; // a,c,i text continuation
    unsigned char s_cont  :1; // s replacement text continuation
    unsigned char running :1; // 0 while building, 1 while running
} gflags;

// store addresses of { in braces, : in labels, bt in branches during building
// store addresses of scheduled writes during execution
// store (cmd - prog) for braces, labels, and branches so we don't screw up
// pointers when we realloc
Vector braces, labels, branches, writes;

// pattern and hold spaces
char  space1[SPACE_BYTES],  space2[SPACE_BYTES];
char *patt_space = space1, *hold_space = space2;

regex_t *last_regex;     // last used regex for use with empty regex searches
char   **files;          // list of file names from argv
FILE    *file;           // current file we are reading
char    *prog_name;      // argv[0]
Command *prog, *pc, *ni; // program memory, program counter, next instruction
size_t   prog_size;      // number of Commands in prog
size_t   line_number;    // of script when building, of input when running

// Forward Delcarations
// Sedfuncs
Action cmd_a     (Command *cmd);
Action cmd_b     (Command *cmd);
Action cmd_c     (Command *cmd);
Action cmd_d     (Command *cmd);
Action cmd_D     (Command *cmd);
Action cmd_g     (Command *cmd);
Action cmd_G     (Command *cmd);
Action cmd_h     (Command *cmd);
Action cmd_H     (Command *cmd);
Action cmd_i     (Command *cmd);
Action cmd_l     (Command *cmd);
Action cmd_n     (Command *cmd);
Action cmd_N     (Command *cmd);
Action cmd_p     (Command *cmd);
Action cmd_P     (Command *cmd);
Action cmd_q     (Command *cmd);
Action cmd_r     (Command *cmd);
Action cmd_s     (Command *cmd);
Action cmd_t     (Command *cmd);
Action cmd_w     (Command *cmd);
Action cmd_x     (Command *cmd);
Action cmd_y     (Command *cmd);
Action cmd_colon (Command *cmd);
Action cmd_equal (Command *cmd);
Action cmd_lbrace(Command *cmd);
Action cmd_rbrace(Command *cmd);
Action cmd_last  (Command *cmd);

// Getargs / Freeargs
void  free_acir_arg (Command *cmd);
void  free_s_arg    (Command *cmd);
void  free_y_arg    (Command *cmd);
char *get_aci_arg   (Command *cmd, char *str);
char *get_bt_arg    (Command *cmd, char *str);
char *get_colon_arg (Command *cmd, char *str);
char *get_lbrace_arg(Command *cmd, char *str);
char *get_r_arg     (Command *cmd, char *str);
char *get_rbrace_arg(Command *cmd, char *str);
char *get_s_arg     (Command *cmd, char *str);
char *get_w_arg     (Command *cmd, char *str);
char *get_y_arg     (Command *cmd, char *str);

// Actions
int noop     (void); // continue execution
int new_line (void); // read   new line, continue current cycle
int app_line (void); // append new line, continue current cycle
int new_next (void); // move to new cycle, read new line
int app_next (void); // move to new cycle, append new line
int old_next (void); // move to new cycle, reuse pattern space
int quit     (void); // do not start a new cycle
int error    (void); // he's dead Jim

// Utilities
int      check_puts    (char *str, FILE *stream);
char    *chomp         (char *str);
int      resize        (void **ptr, size_t *nmemb, size_t size, size_t new_nmemb, void **next, int clear);
char    *find_delim    (char *str, char delim, int do_brackets);
size_t   handle_escapes(char *beg, char *end, char delim);
int      is_eof        (FILE *stream);
int      next_file     (void);
Command *pop           (Vector *vec);
size_t   push          (Vector *vec, Command *cmd);
int      read_line     (char *buf, size_t size, FILE* file);
int      sized_memcpy  (char *dest, char *src, size_t n, char *buf, size_t buf_size);
void     strlcpy       (char *dest, char *src, size_t size);
void     strlcat       (char *dest, char *src, size_t size);
int      write_file    (char *in_path, FILE *out_stream);

// Build and run
int      aci_append   (Command *cmd, char *str);
int      build        (char *line);
void     cleanup      (void);
int      do_writes    (void);
Command *find_label   (Vector *vec, char *label);
int      in_range     (Command *cmd);
int      insert_labels(void);
char    *make_address (Address *addr, char *str);
char    *make_range   (Range *range, char *str);
int      match_addr   (Address *addr);
int      run          (void);
int      script_file  (char *path);
int      script_string(char *script);
void     update_ranges(Command *beg, Command *end);

// Lookup table of functions
#define info(letter, sedfunc, getargs, freeargs, max_addr) \
    [letter] = { sedfunc, getargs, freeargs, max_addr }
Sedfunc_info funcs[] = {
    info('a', cmd_a     , get_aci_arg   , free_acir_arg , 1), // schedule write of text for later
    info('b', cmd_b     , get_bt_arg    , NULL          , 2), // branch to label (extra holds char *label while building, Command *label while running)
    info('c', cmd_c     , get_aci_arg   , free_acir_arg , 2), // delete pattern space, at 0 or 1 addr or end of 2 addr, write text
    info('d', cmd_d     , NULL          , NULL          , 2), // delete pattern space
    info('D', cmd_D     , NULL          , NULL          , 2), // delete to first newline and start new cycle without reading (if no newline, d)
    info('g', cmd_g     , NULL          , NULL          , 2), // replace pattern space with hold space
    info('G', cmd_G     , NULL          , NULL          , 2), // append newline and hold space to pattern space
    info('h', cmd_h     , NULL          , NULL          , 2), // replace hold space with pattern space
    info('H', cmd_H     , NULL          , NULL          , 2), // append newline and pattern space to hold space
    info('i', cmd_i     , get_aci_arg   , free_acir_arg , 1), // write text
    info('l', cmd_l     , NULL          , NULL          , 2), // write pattern space in 'visually unambiguous form'
    info('n', cmd_n     , NULL          , NULL          , 2), // write pattern space (unless -n) read to replace pattern space (if no input, quit)
    info('N', cmd_N     , NULL          , NULL          , 2), // append to pattern space separated by newline, line number changes (if no input, quit)
    info('p', cmd_p     , NULL          , NULL          , 2), // write pattern space
    info('P', cmd_P     , NULL          , NULL          , 2), // write pattern space up to first newline
    info('q', cmd_q     , NULL          , NULL          , 1), // quit
    info('r', cmd_r     , get_r_arg     , free_acir_arg , 1), // write contents of file (unable to open/read treated as empty file)
    info('s', cmd_s     , get_s_arg     , free_s_arg    , 2), // find/replace/all that crazy s stuff
    info('t', cmd_t     , get_bt_arg    , NULL          , 2), // if s/// succeeded (since input or last t) brance to label (end if no label)
    info('w', cmd_w     , get_w_arg     , NULL          , 2), // append pattern space to file
    info('x', cmd_x     , NULL          , NULL          , 2), // exchange pattern and hold spaces
    info('y', cmd_y     , get_y_arg     , free_y_arg    , 2), // replace characters in set1 with characters in set2 (sets is two adjacent strings)
    info(':', cmd_colon , get_colon_arg , NULL          , 0), // defines label for later b and t commands
    info('=', cmd_equal , NULL          , NULL          , 1), // printf("%d\n", line_number);
    info('{', cmd_lbrace, get_lbrace_arg, NULL          , 2), // if we match, run commands, otherwise jump to close
    info('}', cmd_rbrace, get_rbrace_arg, NULL          , 0), // noop, hold onto open for ease of building scripts

    [CHAR_MAX    ] = { NULL    , NULL, NULL, 0 }, // fill out the rest of the array
    [CHAR_MAX + 1] = { cmd_last, NULL, NULL, 0 }
};

/*
 * Sedfuncs
 * Check if cmd is applicable, perform function if it is, return Action to run
 * after command
 */
Action cmd_a(Command *cmd)
{
    if (in_range(cmd))
        if (!push(&writes, cmd))
            return error;
    return noop;
}

Action cmd_b(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    // if we jump backwards update to end, if we jump forwards update to there
    update_ranges(cmd + 1, cmd->jump > cmd ? cmd->jump : ni);
    pc = cmd->jump;
    return noop;
}

Action cmd_c(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    if (!cmd->in_match && check_puts(cmd->text, stdout))
        return error;
    return new_next;
}

Action cmd_d(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    *patt_space = '\0';
    return new_next;
}

Action cmd_D(Command *cmd)
{
    char *p;

    if (!in_range(cmd))
        return noop;

    if (!(p = strchr(patt_space, '\n')))
        return cmd_d(cmd);
    p++;
    memmove(patt_space, p, strlen(p) + 1);
    return old_next;
}

Action cmd_g(Command *cmd)
{
    if (in_range(cmd))
        strlcpy(patt_space, hold_space, SPACE_BYTES);
    return noop;
}

Action cmd_G(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    if (strlen(patt_space) + strlen(hold_space) + 1 > SPACE_BYTES)
        warn("truncating pattern space to %zu bytes", SPACE_BYTES);

    strlcat(patt_space, "\n"      , SPACE_BYTES);
    strlcat(patt_space, hold_space, SPACE_BYTES);
    return noop;
}

Action cmd_h(Command *cmd)
{
    if (in_range(cmd))
        strlcpy(hold_space, patt_space, SPACE_BYTES);
    return noop;
}

Action cmd_H(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    if (strlen(patt_space) + strlen(hold_space) + 1 > SPACE_BYTES)
        warn("truncating hold space to %zu bytes", SPACE_BYTES);

    strlcat(hold_space, "\n"      , SPACE_BYTES);
    strlcat(hold_space, patt_space, SPACE_BYTES);
    return noop;
}

Action cmd_i(Command *cmd)
{
    if (in_range(cmd) && check_puts(cmd->text, stdout))
        return error;
    return noop;
}

Action cmd_l(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    char *escapes[] = {
        ['\\'] = "\\\\", ['\a'] = "\\a", ['\b'] = "\\b",
        ['\f'] = "\\f" , ['\r'] = "\\r", ['\t'] = "\\t",
        ['\v'] = "\\v" , [CHAR_MAX] = '\0', // fill out the table
    };

    for (char *p = patt_space; *p; p++) {
        // wrap lines to keep a POSIX compliant text file
        // (save room for '\\' and '\n')
        if (p != patt_space && (p - patt_space) % (LINE_MAX - 2) == 0)
            if (check_puts("\\", stdout))
                return error;
        if (escapes[(int)*p]) {
            if (printf("%s", escapes[(int)*p]) < 0) {
                serror();
                return error;
            }
        } else if (!isprint(*p)) {
            if (printf("\\%03o", *p) < 0) {
                serror();
                return error;
            }
        } else if (putchar(*p) == EOF) {
            serror();
            return error;
        }
    }
    if (check_puts("$", stdout))
        return error;
    return noop;
}

Action cmd_n(Command *cmd)
{
    if (!in_range(cmd))
        return noop;
    if (cmd_last(cmd) == error)
        return error;
    return new_line;
}

Action cmd_N(Command *cmd)
{
    if (!in_range(cmd))
        return noop;
    if (do_writes())
        return error;
    return app_line;
}

Action cmd_p(Command *cmd)
{
    if (in_range(cmd) && check_puts(patt_space, stdout))
        return error;
    return noop;
}

Action cmd_P(Command *cmd)
{
    char *p;
    if (!in_range(cmd))
        return noop;

    if ((p = strchr(patt_space, '\n')))
        *p = '\0';
    if (check_puts(patt_space, stdout))
        return error;
    if (p)
        *p = '\n';
    return noop;
}

Action cmd_q(Command *cmd)
{
    if (!in_range(cmd))
        return noop;
    if (cmd_last(cmd) == error)
        return error;
    return quit;
}

Action cmd_r(Command *cmd)
{
    if (in_range(cmd))
        if (!push(&writes, cmd))
            return error;
    return noop;
}

// FIXME: check overflow on all the *(new++) =
Action cmd_s(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    if (cmd->last_regex && !last_regex) {
        warn("no previous regex");
        return error;
    }

    regex_t   *re = cmd->last_regex ? last_regex : cmd->regex;
    regmatch_t pmatch[re->re_nsub + 1];
    char       buf[SPACE_BYTES], *new = buf, *str = patt_space;
    unsigned   matches = 0, last_empty = 1, qflag = 0;
    int        cflags  = 0;

    last_regex = re;

    while (!qflag && !regexec(re, str, LENGTH(pmatch), pmatch, cflags)) {
        cflags = REG_NOTBOL; // want to match against beg of line  first time, but not again
        if (!*str)           // want to match against empty string first time, but not again
            qflag = 1;
        if ((last_empty || pmatch[0].rm_eo) &&  // don't subst if last match was not empty and this one is
            (++matches == cmd->occurrence || !cmd->occurrence)) {  // correct match or global
            unsigned escape = 0;

            // copy over everything before the match
            if (sized_memcpy(new, str, pmatch[0].rm_so, buf, sizeof(buf)))
                break;
            new += pmatch[0].rm_so;
            for (char *p = cmd->text; *p; p++) {
                if (escape) {
                    escape = 0;
                    if (isdigit(*p)) { // backreference
                        regmatch_t *rm  = &pmatch[*p - '0'];
                        if (rm->rm_so != -1) {
                            size_t len = rm->rm_eo - rm->rm_so;
                            if (sized_memcpy(new, str + rm->rm_so, len, buf, sizeof(buf)))
                                break;
                            new += len;
                        }
                    } else
                        *(new++) = *p; // now non special character
                } else switch (*p) {
                    default  : *(new++) = *p; break;
                    case '\\': escape = 1;    break;
                    case '&' :
                    { // insert matched text
                        regmatch_t *rm  = pmatch;
                        size_t      len = rm->rm_eo - rm->rm_so;
                        if (sized_memcpy(new, str + rm->rm_so, len, buf, sizeof(buf)))
                            break;
                        new += len;
                        break;
                    }
                }
            }
        } else {
            // copy over everything including the match
            if (sized_memcpy(new, str, pmatch[0].rm_eo, buf, sizeof(buf)))
                break;
            new += pmatch[0].rm_eo;
        }
        if (!pmatch[0].rm_eo)    // both this and last match were empty
            *(new++) = *(str++); // advance one character, add it to output
        last_empty = !pmatch[0].rm_eo;
        str       +=  pmatch[0].rm_eo;
    }
    gflags.s = matches && matches >= cmd->occurrence;
    if (!matches)
        return noop;

    sized_memcpy(new, str, strlen(str) + 1, buf, sizeof(buf));
    strlcpy(patt_space, buf, SPACE_BYTES);
    if (cmd->flag_p && check_puts(patt_space, stdout))
        return error;
    if (cmd->file && check_puts(patt_space, cmd->file))
        return error;
    return noop;
}

Action cmd_t(Command *cmd)
{
    if (!in_range(cmd) || !gflags.s)
        return noop;

    // if we jump backwards update to end, if we jump forwards update to there
    update_ranges(cmd + 1, cmd->jump > cmd ? cmd->jump : ni);
    pc = cmd->jump;
    gflags.s = 0;
    return noop;
}

Action cmd_w(Command *cmd)
{
    if (in_range(cmd) && check_puts(patt_space, cmd->file))
        return error;
    return noop;
}

Action cmd_x(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    char *tmp  = patt_space;
    patt_space = hold_space;
    hold_space = tmp;
    return noop;
}

Action cmd_y(Command *cmd)
{
    if (!in_range(cmd))
        return noop;

    char *find = cmd->text;
    char *repl = find + strlen(find) + 1;

    for (char *p = patt_space; (p = strpbrk(p, find)); p++)
        *p = repl[strchr(find, *p) - find];

    return noop;
}

Action cmd_colon(Command *cmd)
{
    USE(cmd);
    return noop;
}

Action cmd_equal(Command *cmd)
{
    if (!in_range(cmd))
        return noop;
    if (printf("%zu\n", line_number) < 0) {
        serror();
        return error;
    }
    return noop;
}

Action cmd_lbrace(Command *cmd)
{
    if (in_range(cmd))
        return noop;

    // update ranges on all commands we're skipping
    Command *jump = prog + cmd->offset;
    update_ranges(cmd + 1, jump);
    pc = jump;
    return noop;
}

Action cmd_rbrace(Command *cmd)
{
    USE(cmd);
    return noop;
}

// not actually a Sedfunc/cmd_ but acts like one
// command at end of script, print if not -n, perform scheduled a,r writes,
// start new cycle
Action cmd_last(Command *cmd)
{
    USE(cmd);
    if (!gflags.n && check_puts(patt_space, stdout))
        return error;
    if (do_writes())
        return error;
    return new_next;
}

/*
 * Getargs / Freeargs
 * Read the first argument from str into cmd->extra and return pointer to one
 * past last character of argument or NULL on error
 */
// prepare for text for a,c,i functions, set aci_cont flag so build() will read
// text instead of parsing a command
char *get_aci_arg(Command *cmd, char *str)
{
    cmd->print = check_puts;
    if (!(cmd->text = calloc((cmd->size = 1), 1))) { // start with empty string (1 nul byte)
        serror();
        return NULL;
    }
    if (*str != '\\' || *(str + 1) != '\0') {
        warn("trailing characters: %s", str);
        return NULL;
    }
    gflags.aci_cont = 1;
    return str + 1;
}

void free_acir_arg(Command *cmd)
{
    free(cmd->text);
}

// read label for b,t commands. for strict POSIX compliance read rest of line
// (including spaces and semicolons) and truncate to 8 bytes
char *get_bt_arg(Command *cmd, char *str)
{
    size_t len = strlen(str = chomp(str));

    if (*str)
        strlcpy(cmd->label, str, LABEL_BYTES);

    if (*str && len > LABEL_BYTES - 1)
        warn("truncating label '%s' to '%s' (%zu bytes)", str, cmd->label, LABEL_BYTES);
    if (!push(&branches, (Command *)(cmd - prog)))
        return NULL;
    return str + len;
}

// read label for : command. for strict POSIX compliance read rest of line
// (including spaces and semicolons) and truncate to 8 bytes
char *get_colon_arg(Command *cmd, char *str)
{
    size_t len = strlen(str = chomp(str));

    if (!*str) {
        warn("no label name");
        return NULL;
    }
    strlcpy(cmd->label, str, LABEL_BYTES);
    if (len > LABEL_BYTES - 1)
        warn("truncating label '%s' to '%s' (%zu bytes)", str, cmd->label, LABEL_BYTES);
    if (!push(&labels, (Command *)(cmd - prog)))
        return NULL;
    return str + len;
}

// push address of { so we can pop for }. not really getarg, but called at the
// same place. (use cmd - prog offset instead of address so we don't screw up
// pointers when we realloc)
// On commands that don't take arguments, lbrace and rbace, return str - 1
// (will be incremented to point to next command)
char *get_lbrace_arg(Command *cmd, char *str)
{
    if (!push(&braces, (Command *)(cmd - prog)))
        return NULL;
    return str;
}

// pop { and set offset to cmd so we can jump from { to }
char *get_rbrace_arg(Command *cmd, char *str)
{
    Command *lbrace = prog + (ptrdiff_t)pop(&braces);

    if (!lbrace) {
        warn("extra }");
        return NULL;
    }
    str = chomp(str);
    if (*str) {
        warn("trailing characters, } must be on its own line");
        return NULL;
    }
    lbrace->offset = cmd - prog;
    return str;
}

// read file for r command. for strict POSIX compliance read rest of line
// (including spaces and semicolons)
char *get_r_arg(Command *cmd, char *str)
{
    if (!isblank(*str)) {
        warn("no space before file name");
        return NULL;
    }
    cmd->print = write_file;
    str        = chomp(str);
    if (!*str) {
        warn("no file name");
        return NULL;
    }
    if (!(cmd->text = strdup(str))) {
        serror();
        return NULL;
    }
    return str + strlen(str);
}

// read arguments for s function, replace "\\n" with literal newline "\n" in
// regex. if w flag read rest of line as file name for strict POSIX compliance
// (including spaces and semicolons)
char *get_s_arg(Command *cmd, char *str)
{
    char  *p, *q, *beg = str, delim = *str;
    int    err;
    size_t len;

    // s_Find_Replace_Flags

    // Find
    // we are NOT continuing from a literal newline in a replacement text
    if (!gflags.s_cont) {
        cmd->occurrence = 1;
        if (!delim || delim == '\\') {
            warn("bad delimiter '%c' in s argument: %s", delim, beg);
            return NULL;
        }
        if (*++str == delim) // empty regex, use last_regex
            cmd->last_regex = 1;
        if (!(p = find_delim(str, delim, 1))) {
            warn("missing second delimiter '%c' in s argument: %s", delim, beg);
            return NULL;
        }
        p -= handle_escapes(str, p, delim);
        *p = '\0';
        if (!cmd->last_regex) {
            if (!(cmd->regex = malloc(sizeof(*cmd->regex)))) {
                serror();
                return NULL;
            }
            if ((err = regcomp(cmd->regex, str, 0))) {
                char msg[128]; // TODO: size? own regcomp() function so no repeats
                regerror(err, cmd->regex, msg, sizeof(msg));
                warn("bad regex: %s: %s", str, msg);
                return NULL;
            }
        }
        *(p++) = cmd->delim = delim; // replace delim for error messages
    } else { // continuing after a literal newline in the replacment text
        p     = str;
        delim = cmd->delim;
    }

    // Replace
    // if we are continuing from a literal newline in a replacement text p
    // points to the beginning of the current line
    // if we are not continuing p points one character past to the second
    // delimiter
    q  = find_delim(p, delim, 0);
    if (!q) { // no third delimiter, either backslash newline or error
        len = strlen(p);
        q   = p + len - 1;
        if (*q != '\\') {
            warn("missing third delimiter '%c' in s argument: %s", delim, beg);
            return NULL;
        }
        gflags.s_cont = 1;
        *(q++) = '\n';
        --ni; // decrement next inst pointer so when it's incremented it points to cmd again
    } else {
        gflags.s_cont = 0;
        len = q - p;
    }
    if (!cmd->size)
        ++len; // need space for nul byte first time
    *q = '\0';
    if (resize((void **)&cmd->text, &cmd->size, sizeof(*cmd->text), cmd->size + len, NULL, 1)) {
        serror();
        return NULL;
    }
    strlcat(cmd->text, p, cmd->size);
    if (gflags.s_cont) // literal newline in replacement text
        return q;
    else
        *q = delim; // replace delim for better error messages

    // Flags
    // q now points to the third delimiter
    for (p = q + 1; *p; p++) {
        if (isdigit(*p)) {
            long num = strtol(p, &p, 10);
            if (num == LONG_MAX)
                serror();
            if (num == 0) {
                warn("invalid match number: 0");
                return NULL;
            }
            cmd->occurrence = num;
            p--;
        } else switch (*p) {
            default : return p;
            case 'p': cmd->flag_p     = 1; break;
            case 'g': cmd->occurrence = 0; break;
            case 'w':
            {
                Command buf;
                if (!(p = get_w_arg(&buf, p + 1)))
                    return NULL;
                cmd->file = buf.file;
                break;
            }
        }
        if (!*p) // w flag ate rest of line
            break;
    }

    // p now points to 1 past last argument
    return p;
}

void free_s_arg(Command *cmd)
{
    free(cmd->text);
    if (!cmd->last_regex && cmd->regex) {
        regfree(cmd->regex);
        free(cmd->regex);
    }
}

// read file name for w function for strict POSIX compliance read rest of line
// (including spaces and semicolons) and limit to MAX_WFILES wfiles
char *get_w_arg(Command *cmd, char *str)
{
    unsigned i;

    if (!isblank(*str)) {
        warn("no space before file name");
        return NULL;
    }
    str = chomp(str);
    if (!*str) {
        warn("no file name");
        return NULL;
    }
    for (i = 0; i < MAX_WFILES && wfiles[i].file; i++)
        if (!strcmp(str, wfiles[i].name))
            break;
    if (i == MAX_WFILES) {
        warn("too many wfiles");
        return NULL;
    }
    if (!wfiles[i].file) { // no match
        wfiles[i].name = strdup(str);
        if (!(wfiles[i].file = fopen(str, "w"))) {
            serror();
            return NULL;
        }
    }
    cmd->file = wfiles[i].file;
    return str + strlen(str);
}

// read find and replace sets for y function, put in cmd->text as two adjacent
// nul terminated strings (i.e. char *set2 = cmd->text + strlen(cmd->text) + 1)
char *get_y_arg(Command *cmd, char *str)
{
    char *p, *q, *beg = str, delim = *str;

    if (delim == '\\')
        delim = *++str;
    if (delim == '\\') {
        warn("bad delimiter '%c' for y command", delim);
        return NULL;
    }
    if (!(p = find_delim(str + 1, delim, 0))) {
        warn("missing second delimiter '%c' for y command: %s", delim, beg);
        return NULL;
    }
    if (!(q = find_delim(p + 1, delim, 0))) {
        warn("missing second delimiter '%c' for y command: %s", delim, beg);
        return NULL;
    }
    q -= handle_escapes(str, q, delim);
    p  = find_delim(str + 1, delim, 0);
    if (q - p != p - str) {
        warn("bad y argument, different length sets: %s", beg);
        return NULL;
    }
    *q = '\0';
    if (!(cmd->text = strdup(str + 1))) {
        serror();
        return NULL;
    }
    *find_delim(cmd->text, delim, 0) = '\0';
    return q + 1;
}

void free_y_arg(Command *cmd)
{
    free(cmd->text);
}

/*
 * Actions
 * Read, append, print, reset pc, etc.
 * Return -1 on error, 0 to continue execution, 1 to halt
 */
// append new line, continue current cycle
int app_line(void)
{
    int  ret;
    char line[SPACE_BYTES];

    while (read_line(line, SPACE_BYTES, file) == EOF)
        if ((ret = next_file()))
            return ret;

    if (strlen(patt_space) + strlen(line) + 1 > SPACE_BYTES)
        warn("truncating pattern space to %zu bytes", SPACE_BYTES);

    strlcat(patt_space, "\n", SPACE_BYTES);
    strlcat(patt_space, line, SPACE_BYTES);
    gflags.s = 0;
    line_number++;
    return 0;
}

// move to new cycle, append new line
int app_next(void)
{
    int ret;

    // update ranges on all commands we're skipping
    update_ranges(pc + 1, ni);
    ret = app_line();
    pc  = prog - 1;
    return ret;
}

// he's dead Jim
int error(void)
{
    return -1;
}

// read new line, continue current cycle
int new_line(void)
{
    int ret;

    while (read_line(patt_space, SPACE_BYTES, file) == EOF)
        if ((ret = next_file()))
            return ret;
    gflags.s = 0;
    line_number++;
    return 0;
}

// move to new cycle, read new line
int new_next(void)
{
    int ret;

    // update ranges on all commands we're skipping
    update_ranges(pc + 1, ni);
    ret = new_line();
    pc  = prog - 1;
    return ret;
}

// continue execution
int noop(void)
{
    return 0;
}

// move to new cycle, reuse pattern space
int old_next(void)
{
    // update ranges on all commands we're skipping
    update_ranges(pc + 1, ni);
    pc = prog - 1;
    return 0;
}

// do not start a new cycle
int quit(void)
{
    return 1;
}

/*
 * Utilities
 */
// write str to stream followed by newline and check for errors
int check_puts(char *str, FILE *stream)
{
    if (fputs(str, stream) == EOF) {
        serror();
        return -1;
    }
    if (fputs("\n", stream) == EOF) {
        serror();
        return -1;
    }
    return 0;
}

// return pointer to first non blank character in str
char *chomp(char *str)
{
    for (; *str && isblank(*str); str++)
        ;
    return str;
}

// given memory pointed to by *ptr that currently holds *nmemb members of size
// size, realloc to hold new_nmemb members, return new_nmemb in *memb and one
// past old end in *next. if clear is nonzero clear new memory. if realloc fails
// change nothing. (should work to shrink, too...)
int resize(void **ptr, size_t *nmemb, size_t size, size_t new_nmemb, void **next, int clear)
{
    void *n, *tmp;

    if (new_nmemb) {
        if (!(tmp = realloc(*ptr, new_nmemb * size)))
            return -1;
    } else { // turns out realloc(*ptr, 0) != free(*ptr)
        free(*ptr);
        tmp = NULL;
    }
    n = (char *)tmp + *nmemb * size;
    if (clear && new_nmemb > *nmemb)
        memset(n, 0, (new_nmemb - *nmemb) * size);
    *nmemb = new_nmemb;
    *ptr   = tmp;
    if (next)
        *next = n;
    return 0;
}

// Find first delim in str that is not escaped or in []
// or in [::] inside [] or in [..] inside []
char *find_delim(char *str, char delim, int do_brackets)
{
    enum {
        OUTSIDE         , // not in brackets
        BRACKETS_OPENING, // last char was first [ or last two were first [^
        BRACKETS_INSIDE , // inside []
        INSIDE_OPENING  , // inside [] and last char was [
        CLASS_INSIDE    , // inside class [::], or colating element [..] or [==], inside []
        CLASS_CLOSING   , // inside class [::], or colating element [..] or [==], and last character was the respective : . or =
    }        brackets = OUTSIDE;
    unsigned escape   = 0;
    char     c        = 0; // : inside class, . or = inside colating element

    // TODO: is there a better way? this is a big unwieldy state machine
    for (char *p = str; *p; p++) {
        if      (brackets == BRACKETS_OPENING       &&  *p == '^'  ) {                             continue; }
        else if (brackets == BRACKETS_OPENING       &&  *p == ']'  ) { brackets = BRACKETS_INSIDE; continue; }
        else if (brackets == BRACKETS_OPENING                      ) { brackets = BRACKETS_INSIDE;           }

        if      (brackets == CLASS_CLOSING          &&  *p == ']'  ) { brackets = BRACKETS_INSIDE ;          }
        else if (brackets == CLASS_CLOSING                         ) { brackets = CLASS_INSIDE    ;          }
        else if (brackets == CLASS_INSIDE           &&  *p ==  c   ) { brackets = CLASS_CLOSING   ;          }
        else if (brackets == INSIDE_OPENING         && (*p == ':'  ||
                                                        *p == '.'  ||
                                                        *p == '=') ) { brackets = CLASS_INSIDE    ; c = *p;  }
        else if (brackets == INSIDE_OPENING         &&  *p == ']'  ) { brackets = OUTSIDE         ;          }
        else if (brackets == BRACKETS_INSIDE        &&  *p == '['  ) { brackets = INSIDE_OPENING  ;          }
        else if (brackets == BRACKETS_INSIDE        &&  *p == ']'  ) { brackets = OUTSIDE         ;          }
        else if (brackets == OUTSIDE                &&  escape     ) { escape   = 0               ;          }
        else if (brackets == OUTSIDE                &&  *p == '\\' ) { escape   = 1               ;          }
        else if (brackets == OUTSIDE && do_brackets &&  *p == '['  ) { brackets = BRACKETS_OPENING;          }
        else if (brackets == OUTSIDE                &&  *p == delim) return p;
    }
    return NULL;
}

// scan from beg to end, replacing "\\d" with "d" and "\\n" with "\n" (where d
// is delim) then memmove rest of string into place
// special behavior if d is '\0' then remove all backslashes
// NOTE: d takes precedence so a delimiter of 'n' means "\\n" is replaced with
//       "n" not "\n"
size_t handle_escapes(char *beg, char *end, char d)
{
    size_t num_newlines = 0;
    char *src = beg, *dst = beg;

    while (src < end && (*(dst++) = *(src++))) {
        if (*(src - 1) == '\\' && (*src == 'n' || *src == d || d == '\0')) {
            *(dst - 1) = (*src == d || !d) ? *src : '\n';
            ++src;
            ++num_newlines;
        }
    }
    memmove(dst, src, strlen(src) + 1);
    return num_newlines;
}

// test of stream is at EOF
int is_eof(FILE *stream)
{
    int c = fgetc(stream);

    if (c == EOF && ferror(stream))
        serror();
    if (c != EOF && ungetc(c, stream) == EOF)
        serror();

    return c == EOF;
}

// move to next file on command line or stdin if this is the first call and
// there are no files on the command line
// return 0 for success, 1 for no more files
int next_file(void)
{
    if (file == stdin)
        clearerr(file);
    else if (file && fclose(file))
        serror();
    file = NULL;

    do {
        if (!*files) {
            if (!gflags.running) // first call, no file arguments, use stdin
                file = stdin;
        } else if (!strcmp(*files, "-")) {
            file = stdin;
            files++;
        } else if (!(file = fopen(*(files++), "r")))
            serror();
    } while (!file && *files);
    return !file;
}

// pop cmd from vec, shrinking if we're using < 1/4 of capcity
Command *pop(Vector *vec)
{
    Command *tmp;

    if (!vec->size)
        return NULL;
    tmp = vec->data[--vec->size];

    if (vec->size <= vec->capacity / 4)
        if (resize((void **)&vec->data, &vec->capacity, sizeof(*vec->data), vec->capacity / 2, NULL, 0))
            return NULL;
    return tmp;
}

// push cmd onto vec, growing (doubling) if needed
size_t push(Vector *vec, Command *cmd)
{
    if (vec->size == vec->capacity)
        if (resize((void **)&vec->data, &vec->capacity, sizeof(*vec->data), vec->capacity * 2 + 1, NULL, 0))
            return 0;
    vec->data[vec->size++] = cmd;
    return vec->size;
}

// read one line (max size bytes including '\0') from file into buf. warn if
// line is truncated
int read_line(char *buf, size_t size, FILE* file)
{
    size_t len;
    if (!file)
        return EOF;
    if (fgets(buf, size, file) == NULL) {
        if (ferror(file))
            serror();
        return EOF;
    }
    len = strlen(buf) - 1;
    if (buf[len] == '\n') {
        buf[len] =  '\0';
    } else if (feof(file)) {
        warn("no final newline, not POSIX text file");
    } else {
        warn("truncating line to %zu bytes", size - 1);
        do {
            if (fgets(buf, size, file) == NULL) {
                if (ferror(file))
                    serror();
                return EOF;
            }
        } while (buf[strlen(buf)] != '\n');
    }
    return 0;
}

// memcpy from src to dest min(n, buf_size - (dest - buf)), warn if truncating
// dest is a pointer to a location inside buf (i.e. dest - buf <= buf_size)
int sized_memcpy(char *dest, char *src, size_t n, char *buf, size_t buf_size)
{
    int ret = 0;

    if (dest - buf + n > buf_size) {
        warn("truncating pattern space to %zu bytes", buf_size);
        n   = buf_size - (dest - buf);
        ret = -1;
    }
    memcpy(dest, src, n);
    return ret;
}

void strlcpy(char *dest, char *src, size_t size)
{
    if (!size || !dest || !src)
        return;

    while (--size && (*(dest++) = (*src++)))
        ;
    if (!size)
        *dest = '\0';
}

void strlcat(char *dest, char *src, size_t size)
{
    size_t len;

    if (!size || !dest || !src)
        return;
    if ((len = strlen(dest)) >= size)
        return;
    dest += len;
    size -= len;
    strlcpy(dest, src, size);
}

// read file at in_path a line at a time (truncating if long lines) and write
// to out_stream
int write_file(char *in_path, FILE *out_stream)
{
    char line[LINE_MAX + 1];
    FILE *in_stream = fopen(in_path, "r");

    if (!in_stream) // no file is treated as empty file
        return 0;
    while (read_line(line, sizeof(line), in_stream) != EOF)
        if (check_puts(line, out_stream))
            return -1;
    if (fclose(in_stream))
        serror(); // TODO: return error? or just keep going?
    return 0;
}

/*
 * Build and run
 */
// append line to the text for the given a,c,i command
int aci_append(Command *cmd, char *line)
{
    char  **text = &cmd->text;
    size_t *size = &cmd->size;
    size_t  len  = strlen(line);

    if (!len) {// empty line
        gflags.aci_cont = 0;
        return 0;
    }
    if (line[len - 1] == '\\')
        line[len - 1] =  '\n';
    else
        gflags.aci_cont = 0;

    // get rid of all backslashes
    len -= handle_escapes(line, line + len, 0);

    // already have 1 null byte
    if (resize((void **)text, size, sizeof(**text), *size + len, NULL, 0)) {
        serror();
        return -1;
    }
    strlcat(*text, line, *size);
    return 0;
}

// read given line building the program. return 0 on success -1 on error
int build(char *line)
{
    char orig[strlen(line) + 1]; // for better error messages
    strlcpy(orig, line, sizeof(orig));

    // if the script starts with #n it shall be equivalent to specifying -n
    if (++line_number == 1 && line[0] == '#' && line[1] == 'n')
        gflags.n = 1;
    if (gflags.aci_cont) {
        if (aci_append(ni - 1, line))
            return -1;
    } else for (char *p = line; *p;) {
        if (!gflags.s_cont) { // if we have an s replacement continuation, skip to the getarg()
            if (ni == prog + prog_size)
                if (resize((void **)&prog, &prog_size, sizeof(*prog), prog_size * 2 + 1, (void **)&ni, 1))
                    return -1;

            for (; isblank(*p) || *p == ';'; p++)
                // inside {} only one command per line optionally preceded by blanks
                if (braces.size && *p == ';')
                    warn("leading semicolon inside {}: %s", p);
            if (!*p || *p == '#')
                break;
            if (!(p = make_range(&ni->range, p)))
                return -1;
            p = chomp(p);
            if (*p == '!')
                ni->negate = 1;
            for (; *p == '!'; p++)
                ;
            if (!(ni->func = &funcs[(int)*p])->runcmd) { // stupid -Wchar-subcripts
                warn("%s", orig);
                warn("%*s^ bad sed function: %c", (int)(p - line), "", *p);
                return -1;
            }
            if (ni->range.naddr > ni->func->naddr) {
                warn("%s", orig);
                warn("%*s^ function %c only takes %d addr", (int)(p - line), "", *p, ni->func->naddr);
                return -1;
            }
            p++;
        }
        if (ni->func->getarg && !(p = ni->func->getarg(ni, p)))
            return -1;

        if (braces.size && (ptrdiff_t)braces.data[braces.size - 1] == ni - prog) {
            // we just opened a brace, we can have blanks and then another command,
            // skip the following checks
        } else if (braces.size && *p) {
            // inside {} only one command per line immediately followed by a newline
            // except for the same line as the {
            warn("%s", orig);
            warn("%*s^ trailing characters (%c) while inside {}", (int)(p - line), "", *p);
            return -1;
        } else if (*p && *p != ';') {
            // commands may be followed immediately by a semicolon, then blanks
            // commands that cannot be followed by a semicolon will cause *p == '\0'
            warn("%s", orig);
            warn("%*s^ trailing non semiclon characers (%c)", (int)(p - line), "", *p);
            return -1;
        }
        ni++;
    }
    return 0;
}

void cleanup(void)
{
    free(braces  .data);
    free(labels  .data);
    free(branches.data);

    for (unsigned i = 0; i < MAX_WFILES && wfiles[i].file; i++) {
        free(wfiles[i].name);
        if (fclose(wfiles[i].file))
            serror();
    }

    for (pc = prog; pc < ni; pc++) {
        if (pc->range.beg.type == REGEX && pc->range.beg.regex) {
            regfree(pc->range.beg.regex);
            free   (pc->range.beg.regex);
        }
        if (pc->range.end.type == REGEX && pc->range.end.regex) {
            regfree(pc->range.end.regex);
            free   (pc->range.end.regex);
        }
        if (pc->func->freearg)
            pc->func->freearg(pc);
    }

    free(prog);
}

// perform writes scheduled by a and r commands
int do_writes(void)
{
    Command *cmd;

    for (unsigned i = 0; i < writes.size; i++) {
        cmd = writes.data[i];
        if(cmd->print(cmd->text, stdout))
            return -1;
    }
    // sure I could while(pop()); but... eh
    if (resize((void **)&writes.data, &writes.capacity, sizeof(*writes.data), 0, NULL, 0))
        return -1;
    writes.size = 0;
    return 0;
}

Command *find_label(Vector *vec, char *label)
{
    for (unsigned i = 0; i < vec->size; i++)
        if (!strcmp(label, (prog + (ptrdiff_t)vec->data[i])->label))
            return prog + (ptrdiff_t)vec->data[i];
    return NULL;
}

// test if current line is within cmd->range taking into account cmd->negate
int in_range(Command *cmd)
{
    if (match_addr(&cmd->range.beg)) {
        if (cmd->range.naddr == 2) {
            if (cmd->range.end.type == LINE && cmd->range.end.line_number <= line_number)
                cmd->in_match = 0;
            else
                cmd->in_match = 1;
        }
        return !cmd->negate;
    }
    if (match_addr(&cmd->range.end)) {
        unsigned tmp  = cmd->in_match;
        cmd->in_match = 0;
        return tmp ^ cmd->negate;
    }
    return cmd->in_match ^ cmd->negate;
}

// make jump for b,t point to corresponding label
int insert_labels(void)
{
    Command *cmd, *label;

    // side effect of stuffing ptrdiff_t into Command*, NULL (0) is a valid
    // value, so check size explicitly
    while (branches.size) {
        cmd = prog + (ptrdiff_t)pop(&branches);
        if (!*cmd->label) // no label, branch to end of script
            label = ni - 2;
        else
            label = find_label(&labels, cmd->label);

        if (!label) {
            warn("no such label: %s", cmd->label);
            return -1;
        }
        cmd->jump = label;
    }
    return 0;
}

// Read the first address from str into addr and return pointer to character 1
// past end of address or NULL on error
char *make_address(Address *addr, char *str)
{
    char *end = NULL, *orig = str;

    if (*str == '$') {
        addr->type = LAST;
        end = str + 1;
    } else if (isdigit(*str)) { // line number
        // TODO: strtol func so I don't repeat it
        long num = strtol(str, &end, 10);
        if (num == LONG_MAX)
            serror();
        if (num == 0) {
            warn("unsupported address: 0");
            return NULL;
        }
        *addr = (Address){ .type = LINE, .line_number = num };
    } else if (*str == '/' || *str == '\\') {
        char delim;
        if (*str == '\\' && *++str == '\\') {
            warn("bad delimiter: %s", orig);
            return NULL;
        }
        delim = *str;
        if (*++str == delim) {
            addr->type = LASTRE;
            end = str + 1;
        } else if (!(end = find_delim(str, delim, 1))) {
            warn("unclosed regex: %s", orig);
        } else {
            int err;
            end -= handle_escapes(str, end, delim);
            *(end++) = '\0';
            addr->type = REGEX;
            if (!(addr->regex = malloc(sizeof(*addr->regex)))) {
                serror();
                return NULL;
            }
            if ((err = regcomp(addr->regex, str, 0))) {
                char msg[128]; // TODO: size?
                regerror(err, addr->regex, msg, sizeof(msg));
                warn("bad regex: %s: %s", str, msg);
                end = NULL;
            }
        }
    } else {
        addr->type = EVERY;
        end = str;
    }
    return end;
}

// Read the first range from str in range and return pointer to character 1
// past end of range or NULL on error
char *make_range(Range *range, char *str)
{
    char *p = str;

    if (!(p = make_address(&range->beg, p)))
        return NULL;

    if (*p != ',')
        range->end.type = IGNORE;
    else if (!(p = make_address(&range->end, p + 1)))
        return NULL;

    if      (range->beg.type == EVERY  && range->end.type == IGNORE)
        range->naddr = 0;
    else if (range->beg.type != IGNORE && range->end.type == IGNORE)
        range->naddr = 1;
    else if (range->beg.type != IGNORE && range->end.type != IGNORE)
        range->naddr = 2;
    else { // This should never happen right?
        warn("bad range: %s", str);
        return NULL;
    }

    return p;
}

// test if addr matches current pattern space
int match_addr(Address *addr)
{
    int m = 0;
    switch(addr->type) {
    default    :
    case IGNORE: return 0;                                              // empty address, ignore
    case EVERY : return 1;                                              // every line
    case LINE  : return line_number == addr->line_number;               // line number
    case LAST  : while (!m && is_eof(file))                             // last line ($)
                     if ((m = next_file()))
                         break;
                 return m;
    case REGEX : last_regex = addr->regex;
                 return !regexec(addr->regex, patt_space, 0, NULL, 0); // use included regex
    case LASTRE: if (!last_regex) {
                     warn("no previous regex");
                     exit(EXIT_FAILURE); // TODO: is there a better way?
                 }
                 return !regexec(last_regex , patt_space, 0, NULL, 0); // use most recently used regex
    }
}
// finishing touches, initial setup, run the program
// quit when a command returns a function that returns non zero
int run(void)
{
    int ret;

    line_number = 0;
    if (braces.size) {
        warn("extra {");
        return -1;
    }
    if (insert_labels()) return -1;
    if (next_file    ()) return -1;
    if (new_line     ()) return -1;

    gflags.running = 1;
    for (pc = prog; !(ret = pc->func->runcmd(pc)()); pc++)
        ;

    return ret;
}

// read lines from file at path and build() each line
int script_file(char *path)
{
    char  line[LINE_MAX + 1];
    FILE *file = fopen(path, "r");
    int   err  = 0;

    if (!file) {
        serror();
        return -1;
    }
    while (read_line(line, sizeof(line), file) != EOF)
        if ((err = build(line)))
            break;
    if (fclose(file))
        serror();
    return err;
}

// read lines from script and build() each line
int script_string(char *script)
{
    char line[LINE_MAX + 1];
    int  err = 0;

    // copy becase build() does funky stuff and strtok's saveptr may be wrong
    for (char *p = strtok(script, "\n"); p; p = strtok(NULL, "\n")) {
        if (strlen(p) > sizeof(line))
            warn("truncating line to %zu bytes", sizeof(line));
        strlcpy(line, p, sizeof(line));
        if ((err = build(line)))
            break;
    }
    return err;
}

// iterate from Command beg to end updating ranges so we don't miss any
// e.g. sed -n '1d;1,3p' should still print lines 2 and 3
void update_ranges(Command *beg, Command *end)
{
    while (beg < end)
        in_range(beg++);
}

int main(int argc, char **argv)
{
    int c, err = 0, script = 0;

    prog_name = argv[0];

    if (argc == 1) {
        warn("USAGE:... at some point");
        return EXIT_FAILURE;
    }

    if (atexit(cleanup)) {
        serror();
        return EXIT_FAILURE;
    }

    // -e script, -f file, -n
    while (!err && (c = getopt(argc, argv, ":e:f:n")) != -1) {
        switch (c) {
            case 'n': gflags.n = 1;                                                       break;
            case 'e': err = script_string(optarg); script++;                              break;
            case 'f': err = script_file  (optarg); script++;                              break;
            case ':': err++; fprintf(stderr, "Option -%c requires an operand\n", optopt); break;
            case '?': err++; fprintf(stderr, "Unrecognized option: -%c\n"      , optopt); break;
        }
    }

    if (!script) // no script yet, first argument is script
        err = script_string(argv[optind++]);

    if (err)
        cleanup();

    // add our last instruction
    if (ni == prog + prog_size)
        if (resize((void **)&prog, &prog_size, sizeof(*prog), prog_size + 1, (void **)&ni, 1))
            return EXIT_FAILURE;

    ni->range.beg.type = EVERY;
    ni->range.end.type = IGNORE;
    ni->func           = &funcs[LENGTH(funcs) - 1];
    ++ni;

    files = &argv[optind];

    return run() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}