+ int idx = 0;
+
+ /* parse the command
+ * format is: [addr][,addr]cmd
+ * |----||-----||-|
+ * part1 part2 part3
+ */
+
+ /* first part (if present) is an address: either a number or a /regex/ */
+ if (isdigit(cmdstr[idx]) || cmdstr[idx] == '/')
+ idx = get_address(sed_cmd, cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
+
+ /* second part (if present) will begin with a comma */
+ if (cmdstr[idx] == ',')
+ idx += get_address(sed_cmd, &cmdstr[++idx], &sed_cmd->end_line, &sed_cmd->end_match);
+
+ /* last part (mandatory) will be a command */
+ if (cmdstr[idx] == '\0')
+ error_msg_and_die("missing command");
+ sed_cmd->cmd = cmdstr[idx];
+
+ /* if it was a single-letter command that takes no arguments (such as 'p'
+ * or 'd') all we need to do is increment the index past that command */
+ if (strchr("pd", cmdstr[idx])) {
+ idx++;
+ }
+ /* handle (s)ubstitution command */
+ else if (sed_cmd->cmd == 's') {
+ idx += parse_subst_cmd(sed_cmd, &cmdstr[idx]);
+ }
+ /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
+ else if (strchr("aic", sed_cmd->cmd)) {
+ if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
+ error_msg_and_die("only a beginning address can be specified for edit commands");
+ idx += parse_edit_cmd(sed_cmd, &cmdstr[idx]);
+ }
+ /* handle file cmds: (r)ead */
+ else if (sed_cmd->cmd == 'r') {
+ if (sed_cmd->end_line || sed_cmd->end_match)
+ error_msg_and_die("Command only uses one address");
+ idx += parse_file_cmd(sed_cmd, &cmdstr[idx]);
+ }
+ else {
+ error_msg_and_die("invalid command");
+ }
+
+ /* give back whatever's left over */
+ return (char *)&cmdstr[idx];
+}
+
+static void add_cmd_str(const char *cmdstr)
+{
+ char *mystr = (char *)cmdstr;
+
+ do {
+
+ /* trim leading whitespace and semicolons */
+ memmove(mystr, &mystr[strspn(mystr, "; \n\r\t\v")], strlen(mystr));
+ /* if we ate the whole thing, that means there was just trailing
+ * whitespace or a final / no-op semicolon. either way, get out */
+ if (strlen(mystr) == 0)
+ return;
+ /* if this is a comment, jump past it and keep going */
+ if (mystr[0] == '#') {
+ mystr = strpbrk(mystr, ";\n\r");
+ continue;