// File: /workspace/github_cpp_makefile_star2_O3/hzeller[P]gcode-cli/main.cc
// Function: main
int main(int argc, char *argv[]) {
    // -- Command line options.
    bool is_dry_run = false;                // Don't send anything if enabled.
    bool use_ok_flow_control = true;        // wait for 'ok' response
    int block_buffer_count = 1;             // Number of blocks sent at once.
    bool remove_semicolon_comments = true;  // Not all machines understand them
    int initial_squash_chatter_ms = 2500;   // Start after start machine prompt.

    bool print_communication = true;     // print line+block to $log_gcode
    bool print_unusual_messages = true;  // messages outside handshake

    // No cli options for the following yet. Make configurable ?
    const size_t buffer_size = (1 << 20);  // Input buffer in bytes
    FILE *const log_gcode = stderr;        // Log gcode communication here.
    FILE *log_info = stderr;               // info log, switched off with -q

    const char *EXTRA_MESSAGE_ON = "\033[7m";
    const char *EXTRA_MESSAGE_OFF = "\033[0m";
    if (!isatty(STDERR_FILENO)) {
        EXTRA_MESSAGE_ON = EXTRA_MESSAGE_OFF = "";
    }

    int opt;
    while ((opt = getopt(argc, argv, "b:cFhnqs:")) != -1) {
        switch (opt) {
        case 'n': is_dry_run = true; break;
        case 'q':
            log_info = nullptr;
            // unusual messages squashed if -q multiple times
            print_unusual_messages = print_communication;
            print_communication = false;  // Make separate option ?
            break;
        case 'F': use_ok_flow_control = false; break;
        case 'b':
            block_buffer_count = atoi(optarg);
            if (block_buffer_count < 1)
                return usage(argv[0], "Invalid block buffer\n");
            break;
        case 'c': remove_semicolon_comments = false; break;
        case 's':
            initial_squash_chatter_ms = atoi(optarg);
            if (initial_squash_chatter_ms < 0) {
                return usage(argv[0], "Invalid startup squash timeout\n");
            }
            break;
        case 'h': return usage(argv[0], "");
        default: return usage(argv[0], "Invalid option\n");
        }
    }

    if (optind >= argc) {
        return usage(argv[0], "Expected filename\n");
    }

    // Input: Open GCode file
    const char *const filename = argv[optind];
    const int input_fd = (filename == std::string("-"))
                             ? STDIN_FILENO
                             : open(filename, O_RDONLY);
    if (input_fd < 0) {
        fprintf(stderr, "Can't open input %s: %s\n", filename, strerror(errno));
        return 1;
    }

    // Output: open machine connection.
    const char *const connect_str = (optind < argc - 1)  // destination as arg
                                        ? argv[optind + 1]
                                        : "/dev/ttyACM0,b115200";
    is_dry_run |= (strcmp(connect_str, "/dev/null") == 0);

    std::unique_ptr<MachineConnection> machine;
    if (!is_dry_run) {
        machine.reset(MachineConnection::Open(connect_str));
        if (!machine) {
            fprintf(stderr, "Failed to connect to machine %s\n", connect_str);
            return 1;
        }
    }

    // In a dry-run, we also will not read anything.
    use_ok_flow_control &= !is_dry_run;

    // If there is some initial chatter, ignore it, until there is some time
    // silence on the wire.
    // That way, we only get OK responses to our requests.
    // Even without OK flow control, we need to wait as machine might
    // just reset on connect.
    if (machine) {
        machine->DiscardPendingInput(initial_squash_chatter_ms,
                                     print_communication ? log_gcode : nullptr);
    }

    if (log_info) {
        fprintf(log_info, "\n---- Sending file '%s' to '%s'%s -----\n",
                filename, connect_str, is_dry_run ? " (Dry-run)" : "");
    }

    BufferedLineReader gcode_reader(input_fd, buffer_size,
                                    remove_semicolon_comments);
    char *scratch_buffer = new char[buffer_size];
    int line_no = 0;
    const int64_t start_time = get_time_ms();
    while (!gcode_reader.is_eof()) {
        const auto lines = gcode_reader.ReadNextLines(block_buffer_count);

        // Send all block_buffer_count blocks at once.
        if (!is_dry_run && !machine->WriteBlocks(scratch_buffer, lines)) {
            fprintf(stderr, "Couldn't write!\n");
            return 1;
        }

        // We've sent all the lines above at once, now looking at the
        // expected responses for each block to confirm success.
        // Respons to a gcode-block can be multiple lines and are expected
        // to finish with either "ok" or "error".
        // If communication printing requested, print the lines together with
        // their corresponding response.
        for (const auto request : lines) {
            line_no++;
            bool request_line_already_printed = false;
            AckResponse response;
            do {
                std::string_view print_msg;
                response = ReadResponseLine(use_ok_flow_control, machine.get(),
                                            &print_msg);

                // Now we know enough if we should print the original
                // request. Whenever there is some unusual stuff going on, we
                // want to print the original message first before the response.
                const bool needs_printing =
                    (print_communication ||              // regular chatter
                     response == AckResponse::kError ||  // always print error
                     (print_unusual_messages && response != AckResponse::kOk));

                if (needs_printing) {
                    if (!request_line_already_printed) {
                        fprintf(log_gcode, "%6d\t%.*s ", line_no,
                                (int)request.size() - 1, request.data());
                        request_line_already_printed = true;
                    }
                    if (response == AckResponse::kOk) {
                        fprintf(log_gcode,
                                use_ok_flow_control ? "<< OK\n" : "\n");
                    } else {
                        while (!print_msg.empty() &&
                               isspace(*(print_msg.end() - 1))) {
                            print_msg.remove_suffix(1);
                        }
                        fprintf(log_gcode, "\n%s%.*s%s", EXTRA_MESSAGE_ON,
                                (int)print_msg.size(), print_msg.data(),
                                EXTRA_MESSAGE_OFF);
                    }
                    fflush(log_gcode);
                }

                if (response == AckResponse::kError) {
                    handle_error_or_exit();
                }
            } while (response == AckResponse::kMessage);  // more to come
        }
    }

    const int64_t duration = get_time_ms() - start_time;

    if (log_info) {
        fprintf(log_info, "---- Finished file '%s' -----\n", filename);
    }

    // We don't really expect anything coming afterwards from the machine, but
    // if there is an imbalance of sent commands vs. acknowledge flow control
    // tokens, we'd see it now.
    if (!is_dry_run) {
        if (log_info)
            fprintf(log_info, "Discarding remaining machine responses.\n");
        machine->DiscardPendingInput(
            initial_squash_chatter_ms,
            print_unusual_messages ? log_gcode : nullptr);
    }

    close(input_fd);

    if (log_info) {
        fprintf(log_info,
                "Sent total of %d non-empty lines in "
                "%" PRId64 ".%03" PRId64 "s\n",
                line_no, duration / 1000, duration % 1000);
    }
}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x108, %rsp            # imm = 0x108
movq %rsi, %r15
movl %edi, %ebp
movq 0x497f(%rip), %rax      # 0x6fd8
movq (%rax), %rbx
movl $0x2, %edi
callq 0x22d0
movq %rbx, %rcx
testl %eax, %eax
leaq 0x1a9e(%rip), %rdx      # 0x4110
leaq 0x1990(%rip), %rax      # 0x4009
cmoveq %rdx, %rax
movq %rax, 0xb0(%rsp)
leaq 0x1978(%rip), %rax      # 0x4004
cmoveq %rdx, %rax
movq %rax, 0xa8(%rsp)
movl $0x1, 0x40(%rsp)
movb $0x1, 0xf(%rsp)
movl $0x9c4, 0x20(%rsp)      # imm = 0x9C4
xorl %r13d, %r13d
leaq 0x1957(%rip), %r14      # 0x400e
movq 0x490a(%rip), %rbx      # 0x6fc8
movq %rcx, 0x58(%rsp)
movb $0x1, %al
movq %rax, 0x48(%rsp)
movb $0x1, %al
movl %eax, 0x30(%rsp)
movb $0x1, %al
movl %eax, 0x10(%rsp)
movq %rcx, 0x28(%rsp)
movl %r13d, %ecx
movl %ecx, %r13d
movl %ebp, %edi
movq %r15, %rsi
movq %r14, %rdx
callq 0x2070
movb $0x1, %cl
cmpl $0x6e, %eax
je 0x26de
cmpl $0x62, %eax
jle 0x272a
cmpl $0x70, %eax
jle 0x2752
cmpl $0x73, %eax
je 0x2768
cmpl $0x71, %eax
jne 0x2d5a
movq $0x0, 0x58(%rsp)
movq 0x48(%rsp), %rax
movb %al, 0xf(%rsp)
movq $0x0, 0x48(%rsp)
jmp 0x26db
cmpl $-0x1, %eax
je 0x278e
cmpl $0x46, %eax
je 0x2781
cmpl $0x62, %eax
jne 0x2d5a
movq (%rbx), %rdi
callq 0x22a0
movl %eax, 0x40(%rsp)
testl %eax, %eax
jg 0x26db
jmp 0x2db8
cmpl $0x63, %eax
jne 0x2d4b
movl $0x0, 0x30(%rsp)
jmp 0x26db
movq (%rbx), %rdi
callq 0x22a0
movl %eax, 0x20(%rsp)
testl %eax, %eax
jns 0x26db
jmp 0x2dae
movl $0x0, 0x10(%rsp)
jmp 0x26db
movq 0x484b(%rip), %rbx      # 0x6fe0
movslq (%rbx), %rax
cmpl %ebp, %eax
jge 0x2d64
movq (%r15,%rax,8), %r12
leaq 0xd8(%rsp), %r14
movq %r14, -0x10(%r14)
leaq 0x18ba(%rip), %rsi      # 0x4071
leaq 0x18b4(%rip), %rdx      # 0x4072
leaq 0xc8(%rsp), %rdi
callq 0x2e6e
leaq 0xc8(%rsp), %rdi
movq %r12, %rsi
callq 0x20a0
testl %eax, %eax
movq %r12, 0x50(%rsp)
je 0x27f6
movq %r12, %rdi
xorl %esi, %esi
xorl %eax, %eax
callq 0x2130
movl %eax, 0x14(%rsp)
jmp 0x27fe
movl $0x0, 0x14(%rsp)
movq 0xc8(%rsp), %rdi
cmpq %r14, %rdi
je 0x281b
movq 0xd8(%rsp), %rsi
incq %rsi
callq 0x21a0
cmpl $0x0, 0x14(%rsp)
movq 0x50(%rsp), %rdi
js 0x2d6e
movslq (%rbx), %rax
decl %ebp
cmpl %ebp, %eax
jge 0x283b
movq 0x8(%r15,%rax,8), %r14
jmp 0x2842
leaq 0x184a(%rip), %r14      # 0x408c
leaq 0x1858(%rip), %rsi      # 0x40a1
movq %r14, %rdi
callq 0x2250
testl %eax, %eax
sete %al
orb %al, %r13b
movq $0x0, 0x18(%rsp)
je 0x2869
xorl %r15d, %r15d
jmp 0x28c5
movq %r14, %rdi
callq 0x306c
movq 0x18(%rsp), %r15
movq %rax, 0x18(%rsp)
testq %r15, %r15
je 0x289a
movq %r15, %rdi
callq 0x304c
movl $0x48, %esi
movq %r15, %rdi
callq 0x21a0
movq 0x18(%rsp), %rax
testq %rax, %rax
je 0x2d8c
cmpb $0x0, 0x10(%rsp)
setne %r15b
xorl %edx, %edx
testb $0x1, 0x48(%rsp)
cmovneq 0x28(%rsp), %rdx
movq %rax, %rdi
movl 0x20(%rsp), %esi
callq 0x3446
movq 0x58(%rsp), %rdi
testq %rdi, %rdi
je 0x28fa
testb %r13b, %r13b
leaq 0x181c(%rip), %r8       # 0x40f5
leaq 0x1830(%rip), %rax      # 0x4110
cmoveq %rax, %r8
leaq 0x17e1(%rip), %rsi      # 0x40cc
movq 0x50(%rsp), %rdx
movq %r14, %rcx
xorl %eax, %eax
callq 0x2270
movzbl 0x30(%rsp), %ecx
andl $0x1, %ecx
leaq 0xc8(%rsp), %rdi
movl $0x100000, %edx         # imm = 0x100000
movl 0x14(%rsp), %esi
callq 0x38cc
movl $0x100000, %edi         # imm = 0x100000
callq 0x2030
movq %rax, 0x90(%rsp)
leaq 0x68(%rsp), %rbx
movq %rbx, %rdi
xorl %esi, %esi
callq 0x22b0
movq (%rbx), %rax
movq %rax, 0x88(%rsp)
movabsq $-0x20c49ba5e353f7cf, %rax # imm = 0xDF3B645A1CAC0831
imulq 0x8(%rbx)
movq %rdx, %rax
shrq $0x3f, %rax
sarq $0x7, %rdx
addq %rax, %rdx
movq %rdx, 0x80(%rsp)
movl 0x40(%rsp), %eax
movq %rax, 0x98(%rsp)
leaq 0x17a0(%rip), %rax      # 0x411b
leaq 0x178d(%rip), %rcx      # 0x410f
testb %r15b, %r15b
cmovneq %rax, %rcx
movq %rcx, 0xa0(%rsp)
movl $0x0, 0x10(%rsp)
movl $0x0, 0x3c(%rsp)
movl %r13d, 0x24(%rsp)
cmpb $0x0, 0xe1(%rsp)
jne 0x2c39
leaq 0x68(%rsp), %rdi
leaq 0xc8(%rsp), %rsi
movq 0x98(%rsp), %rdx
callq 0x39c2
testb %r13b, %r13b
jne 0x29f2
movq 0x18(%rsp), %rdi
movq 0x90(%rsp), %rsi
leaq 0x68(%rsp), %rdx
callq 0x35ac
testb %al, %al
je 0x2c28
movq 0x68(%rsp), %rdi
movq 0x70(%rsp), %rax
movq %rax, 0xb8(%rsp)
cmpq %rax, %rdi
je 0x2c02
movl (%rdi), %eax
movq %rdi, 0x40(%rsp)
movq 0x8(%rdi), %rcx
movq %rcx, 0xc0(%rsp)
incl 0x10(%rsp)
decl %eax
movl %eax, 0x64(%rsp)
movq $0x0, 0x30(%rsp)
movl $0x0, %ebp
movl $0x0, %r14d
movl $0x0, %ebx
testb %r15b, %r15b
je 0x2ae0
movq 0x18(%rsp), %r12
leaq 0x8(%r12), %rdi
callq 0x3c4c
movl $0x1, %ebx
movb $0x1, %r13b
cmpb $0x0, 0x21(%r12)
jne 0x2b0c
movq %rax, %rbp
movq %rdx, %r14
cmpq $0x2, %rax
jb 0x2a99
movl $0x2, %edx
movq %r14, %rdi
leaq 0x1e77(%rip), %rsi      # 0x4901
callq 0x2200
testl %eax, %eax
je 0x2aa0
cmpq $0x5, %rbp
jae 0x2aa9
movl $0x2, %ebx
jmp 0x2ae0
xorl %ebp, %ebp
xorl %r14d, %r14d
xorl %ebx, %ebx
jmp 0x2ae0
movl $0x5, %edx
movq %r14, %rdi
leaq 0x1e4c(%rip), %rsi      # 0x4904
callq 0x2200
testl %eax, %eax
je 0x2b18
movl $0x5, %edx
movq %r14, %rdi
leaq 0x1e3a(%rip), %rsi      # 0x490a
callq 0x2200
cmpl $0x1, %eax
movl $0x2, %ebx
sbbl $0x0, %ebx
cmpl $0x1, %ebx
sete %r13b
testl %ebx, %ebx
setne %al
testb %al, 0xf(%rsp)
jne 0x2b18
testb $0x1, 0x48(%rsp)
jne 0x2b18
cmpl $0x1, %ebx
je 0x2b18
cmpl $0x2, %ebx
je 0x2a33
jmp 0x2be2
movl $0x30, %ebp
leaq 0x1db8(%rip), %r14      # 0x48d0
testb $0x1, 0x30(%rsp)
jne 0x2b42
movq 0x28(%rsp), %rdi
leaq 0x15e6(%rip), %rsi      # 0x4111
movl 0x10(%rsp), %edx
movl 0x64(%rsp), %ecx
movq 0xc0(%rsp), %r8
xorl %eax, %eax
callq 0x2270
testl %ebx, %ebx
jne 0x2b5f
movq 0x28(%rsp), %r12
movq %r12, %rdi
movq 0xa0(%rsp), %rsi
xorl %eax, %eax
callq 0x2270
jmp 0x2ba7
xorl %ecx, %ecx
testq %rbp, %rbp
je 0x2b7e
movsbl -0x1(%r14,%rbp), %edi
callq 0x2060
testl %eax, %eax
je 0x2b7c
decq %rbp
jne 0x2b66
xorl %ebp, %ebp
movl %ebp, %ecx
movq 0x28(%rsp), %r12
movq %r12, %rdi
leaq 0x1595(%rip), %rsi      # 0x4122
movq 0xa8(%rsp), %rdx
movq %r14, %r8
movq 0xb0(%rsp), %r9
xorl %eax, %eax
callq 0x2270
movq %r12, %rdi
callq 0x21c0
movb $0x1, %al
movq %rax, 0x30(%rsp)
testb %r13b, %r13b
je 0x2afe
xorl %edi, %edi
callq 0x22d0
movq 0x440b(%rip), %rcx      # 0x6fd8
movq (%rcx), %rdi
testl %eax, %eax
je 0x2dc2
callq 0x247e
jmp 0x2afe
movq 0x40(%rsp), %rdi
addq $0x10, %rdi
cmpq 0xb8(%rsp), %rdi
jne 0x2a0d
movb $0x1, %bl
movq 0x68(%rsp), %rdi
jmp 0x2c04
movb $0x1, %bl
testq %rdi, %rdi
je 0x2c16
movq 0x78(%rsp), %rsi
subq %rdi, %rsi
callq 0x21a0
testb %bl, %bl
movl 0x24(%rsp), %r13d
jne 0x29a6
jmp 0x2d2e
callq 0x245c
movl $0x1, 0x3c(%rsp)
xorl %ebx, %ebx
jmp 0x2bfb
leaq 0x68(%rsp), %r12
movq %r12, %rdi
xorl %esi, %esi
callq 0x22b0
movabsq $0x20c49ba5e353f7cf, %r14 # imm = 0x20C49BA5E353F7CF
movq %r14, %rax
imulq 0x8(%r12)
movq %rdx, %r15
movq (%r12), %rbx
movq 0x58(%rsp), %r12
testq %r12, %r12
je 0x2ca3
leaq 0x14ba(%rip), %rsi      # 0x412c
movq %r12, %rdi
movq 0x50(%rsp), %rdx
xorl %eax, %eax
callq 0x2270
cmpb $0x0, 0x24(%rsp)
jne 0x2cc5
leaq 0x14bc(%rip), %rdi      # 0x414b
movl $0x28, %esi
movl $0x1, %edx
movq %r12, %rcx
callq 0x2310
jmp 0x2caa
cmpb $0x0, 0x24(%rsp)
jne 0x2cc5
movq 0x18(%rsp), %rdi
xorl %edx, %edx
testb $0x1, 0xf(%rsp)
cmovneq 0x28(%rsp), %rdx
movl 0x20(%rsp), %esi
callq 0x3446
movl 0x14(%rsp), %edi
callq 0x2320
testq %r12, %r12
je 0x2d2e
movq %r15, %rax
shrq $0x3f, %rax
sarq $0x7, %r15
addq %rax, %r15
addq 0x80(%rsp), %r15
subq 0x88(%rsp), %rbx
imulq $0x3e8, %rbx, %r8       # imm = 0x3E8
addq %r15, %r8
movq %r8, %rax
imulq %r14
movq %rdx, %rcx
shrq $0x3f, %rcx
sarq $0x7, %rdx
addq %rdx, %rcx
imulq $0x3e8, %rcx, %rax      # imm = 0x3E8
subq %rax, %r8
leaq 0x1454(%rip), %rsi      # 0x4174
movq %r12, %rdi
movl 0x10(%rsp), %edx
xorl %eax, %eax
callq 0x2270
leaq 0xc8(%rsp), %rdi
callq 0x3908
movl 0x3c(%rsp), %ebx
leaq 0x18(%rsp), %rdi
callq 0x2e3a
jmp 0x2d78
cmpl $0x68, %eax
jne 0x2d5a
movq %r15, %rdi
callq 0x2340
jmp 0x2d73
movq %r15, %rdi
callq 0x24f8
jmp 0x2d73
movq %r15, %rdi
callq 0x2415
jmp 0x2d73
callq 0x24bc
movl $0x1, %ebx
movl %ebx, %eax
addq $0x108, %rsp            # imm = 0x108
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
movq 0x4245(%rip), %rax      # 0x6fd8
movq (%rax), %rdi
leaq 0x130e(%rip), %rsi      # 0x40ab
movq %r14, %rdx
xorl %eax, %eax
callq 0x2270
movl $0x1, %ebx
jmp 0x2d3f
movq %r15, %rdi
callq 0x2387
jmp 0x2d73
movq %r15, %rdi
callq 0x23ce
jmp 0x2d73
callq 0x249e
movq %rax, %rbx
movq 0xc8(%rsp), %rdi
cmpq %r14, %rdi
je 0x2e31
movq 0xd8(%rsp), %rsi
incq %rsi
callq 0x21a0
jmp 0x2e31
jmp 0x2dfb
jmp 0x2def
jmp 0x2dfb
movq %rax, %rbx
jmp 0x2e27
movq %rax, %rbx
jmp 0x2e31
jmp 0x2e00
movq %rax, %rbx
jmp 0x2e1a
movq %rax, %rbx
movq 0x68(%rsp), %rdi
testq %rdi, %rdi
je 0x2e1a
movq 0x78(%rsp), %rsi
subq %rdi, %rsi
callq 0x21a0
leaq 0xc8(%rsp), %rdi
callq 0x3908
leaq 0x18(%rsp), %rdi
callq 0x2e3a
movq %rbx, %rdi
callq 0x22e0
nop