// File: /workspace/github_cpp_makefile_star2_O2/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 $0xf8, %rsp
movq %rsi, %rbx
movl %edi, %r15d
movq 0x4b6e(%rip), %rax      # 0x6fd8
movq (%rax), %r14
pushq $0x2
popq %rdi
callq 0x22f0
testl %eax, %eax
movq %r14, %rax
leaq 0x1c8f(%rip), %rdx      # 0x4110
leaq 0x1b81(%rip), %rcx      # 0x4009
cmoveq %rdx, %rcx
movq %rcx, 0xa0(%rsp)
leaq 0x1b69(%rip), %rcx      # 0x4004
cmoveq %rdx, %rcx
movq %rcx, 0x98(%rsp)
pushq $0x1
popq %rcx
movl %ecx, 0x30(%rsp)
movb $0x1, 0xb(%rsp)
movl $0x9c4, 0x14(%rsp)      # imm = 0x9C4
xorl %r14d, %r14d
leaq 0x1b49(%rip), %rbp      # 0x400e
movq 0x4afc(%rip), %r12      # 0x6fc8
movq %rax, %r13
movb $0x1, %cl
movq %rcx, 0x40(%rsp)
movb $0x1, %cl
movl %ecx, 0xc(%rsp)
movb $0x1, %cl
movl %ecx, 0x1c(%rsp)
movq %rax, 0x28(%rsp)
movl %r14d, %ecx
movl %ecx, %r14d
movl %r15d, %edi
movq %rbx, %rsi
movq %rbp, %rdx
callq 0x2070
movb $0x1, %cl
cmpl $0x6e, %eax
je 0x24ea
cmpl $-0x1, %eax
je 0x258f
cmpl $0x46, %eax
je 0x2582
cmpl $0x62, %eax
je 0x2568
cmpl $0x63, %eax
je 0x2548
cmpl $0x68, %eax
je 0x261b
cmpl $0x73, %eax
je 0x2552
cmpl $0x71, %eax
jne 0x2627
xorl %r13d, %r13d
movq 0x40(%rsp), %rax
movb %al, 0xb(%rsp)
movq $0x0, 0x40(%rsp)
jmp 0x24e7
movl $0x0, 0xc(%rsp)
jmp 0x24e7
movq (%r12), %rdi
callq 0x22c0
movl %eax, 0x14(%rsp)
testl %eax, %eax
jns 0x24e7
jmp 0x2ae3
movq (%r12), %rdi
callq 0x22c0
movl %eax, 0x30(%rsp)
testl %eax, %eax
jg 0x24e7
jmp 0x2ad4
movl $0x0, 0x1c(%rsp)
jmp 0x24e7
movl %r14d, %ebp
movq 0x4a47(%rip), %r14      # 0x6fe0
movslq (%r14), %rax
cmpl %r15d, %eax
jge 0x2633
movq (%rbx,%rax,8), %r12
leaq 0x1ac1(%rip), %rsi      # 0x4071
leaq 0xb8(%rsp), %rdi
leaq 0x60(%rsp), %rdx
callq 0x2c60
leaq 0xb8(%rsp), %rsi
movq %r12, 0x48(%rsp)
movq %r12, %rdi
callq 0x2c49
xorl %ecx, %ecx
testb %al, %al
jne 0x25ed
movq 0x48(%rsp), %rdi
xorl %esi, %esi
xorl %eax, %eax
callq 0x2150
movl %eax, %ecx
movl %ecx, 0x10(%rsp)
leaq 0xb8(%rsp), %rdi
callq 0x2120
cmpl $0x0, 0x10(%rsp)
js 0x2af2
movslq (%r14), %rax
decl %r15d
cmpl %r15d, %eax
jge 0x2659
movq 0x8(%rbx,%rax,8), %rbx
jmp 0x2660
movq (%rbx), %rdi
leaq 0x1aeb(%rip), %rsi      # 0x4110
jmp 0x263d
movq (%rbx), %rdi
leaq 0x1a1d(%rip), %rsi      # 0x404e
jmp 0x263d
movq (%rbx), %rdi
leaq 0x1a21(%rip), %rsi      # 0x405e
callq 0x2bb8
pushq $0x1
popq %rbx
movl %ebx, %eax
addq $0xf8, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
leaq 0x1a2c(%rip), %rbx      # 0x408c
leaq 0x1a3a(%rip), %rsi      # 0x40a1
movq %rbx, %rdi
callq 0x2270
testl %eax, %eax
sete %al
andq $0x0, 0x20(%rsp)
orb %al, %bpl
movq 0x48(%rsp), %r14
je 0x2688
xorl %edi, %edi
jmp 0x26ac
movq %rbx, %rdi
callq 0x2f20
leaq 0x20(%rsp), %r15
movq %r15, %rdi
movq %rax, %rsi
callq 0x2d76
movq (%r15), %rdi
testq %rdi, %rdi
je 0x2b26
testq %rdi, %rdi
je 0x26c7
xorl %edx, %edx
testb $0x1, 0x40(%rsp)
cmovneq 0x28(%rsp), %rdx
movl 0x14(%rsp), %esi
callq 0x32ca
testq %r13, %r13
je 0x26f8
testb %bpl, %bpl
leaq 0x1a1f(%rip), %r8       # 0x40f5
leaq 0x1a33(%rip), %rax      # 0x4110
cmoveq %rax, %r8
leaq 0x19e4(%rip), %rsi      # 0x40cc
movq %r13, %rdi
movq %r14, %rdx
movq %rbx, %rcx
xorl %eax, %eax
callq 0x2290
movzbl 0xc(%rsp), %ecx
andl $0x1, %ecx
leaq 0xb8(%rsp), %rdi
movl $0x100000, %edx         # imm = 0x100000
movl 0x10(%rsp), %esi
callq 0x3848
movl $0x100000, %edi         # imm = 0x100000
callq 0x2030
movq %rax, 0x80(%rsp)
movl %ebp, %ebx
notb %bl
callq 0x2bfb
movq %rax, 0x78(%rsp)
movb %bl, 0xc(%rsp)
testb %bl, 0x1c(%rsp)
leaq 0x19ca(%rip), %rax      # 0x410f
leaq 0x19cf(%rip), %rcx      # 0x411b
cmoveq %rax, %rcx
movq %rcx, 0x90(%rsp)
movl 0x30(%rsp), %eax
movq %rax, 0x88(%rsp)
movl $0x0, 0x18(%rsp)
movl $0x0, 0x3c(%rsp)
movq %r13, 0x30(%rsp)
movl %ebp, 0x54(%rsp)
cmpb $0x0, 0xd1(%rsp)
jne 0x2a1c
leaq 0x60(%rsp), %rdi
leaq 0xb8(%rsp), %rsi
movq 0x88(%rsp), %rdx
callq 0x393e
testb %bpl, %bpl
jne 0x27c9
movq 0x20(%rsp), %rdi
movq 0x80(%rsp), %rsi
leaq 0x60(%rsp), %rdx
callq 0x33e6
testb %al, %al
je 0x29f5
movq 0x60(%rsp), %r12
movq 0x68(%rsp), %rax
movq %rax, 0xa8(%rsp)
cmpq 0xa8(%rsp), %r12
je 0x29dc
movl (%r12), %eax
movq 0x8(%r12), %rcx
movq %rcx, 0xb0(%rsp)
incl 0x18(%rsp)
decl %eax
movl %eax, 0x50(%rsp)
movq $0x0, 0x58(%rsp)
movb 0xc(%rsp), %al
testb %al, 0x1c(%rsp)
je 0x288f
movq 0x20(%rsp), %rbx
leaq 0x8(%rbx), %rdi
callq 0x3b8c
cmpb $0x0, 0x21(%rbx)
pushq $0x30
popq %r14
leaq 0x209c(%rip), %rbx      # 0x48d0
pushq $0x1
popq %r13
jne 0x2897
movq %rax, %r15
movq %rdx, %rbp
movq %rax, %rdi
movq %rdx, %rsi
pushq $0x2
popq %rdx
leaq 0x20b1(%rip), %rcx      # 0x4901
callq 0x2c2b
xorl %r14d, %r14d
movl $0x0, %ebx
movl $0x0, %r13d
testb %al, %al
jne 0x2897
movq %r15, %rdi
movq %rbp, %rsi
pushq $0x5
popq %rbx
movq %rbx, %rdx
leaq 0x208a(%rip), %rcx      # 0x4904
callq 0x2c2b
testb %al, %al
je 0x28d7
movq %r15, %r14
movq %rbp, %rbx
pushq $0x1
popq %r13
jmp 0x2897
xorl %r14d, %r14d
xorl %ebx, %ebx
xorl %r13d, %r13d
testl %r13d, %r13d
setne %al
testb %al, 0xb(%rsp)
jne 0x28fe
testb $0x1, 0x40(%rsp)
jne 0x28fe
cmpl $0x1, %r13d
je 0x28fe
cmpl $0x1, %r13d
movl 0x54(%rsp), %ebp
movq 0x48(%rsp), %r14
je 0x299e
cmpl $0x2, %r13d
movq 0x30(%rsp), %r13
je 0x280d
jmp 0x29d3
movq %r15, %rdi
movq %rbp, %rsi
movq %rbx, %rdx
leaq 0x2023(%rip), %rcx      # 0x490a
callq 0x2c2b
movzbl %al, %eax
pushq $0x2
popq %r13
subl %eax, %r13d
movq %r15, %r14
movq %rbp, %rbx
jmp 0x2897
testb $0x1, 0x58(%rsp)
jne 0x2928
movq 0x28(%rsp), %rdi
leaq 0x1800(%rip), %rsi      # 0x4111
movl 0x18(%rsp), %edx
movl 0x50(%rsp), %ecx
movq 0xb0(%rsp), %r8
xorl %eax, %eax
callq 0x2290
testl %r13d, %r13d
jne 0x2946
movq 0x28(%rsp), %r14
movq %r14, %rdi
movq 0x90(%rsp), %rsi
xorl %eax, %eax
callq 0x2290
jmp 0x298a
movq %r14, %r15
subq $0x1, %r14
jb 0x295e
movsbl -0x1(%rbx,%r15), %edi
callq 0x2060
testl %eax, %eax
jne 0x2946
movq 0x28(%rsp), %r14
movq %r14, %rdi
leaq 0x17b5(%rip), %rsi      # 0x4122
movq 0x98(%rsp), %rdx
movl %r15d, %ecx
movq %rbx, %r8
movq 0xa0(%rsp), %r9
xorl %eax, %eax
callq 0x2290
movq %r14, %rdi
callq 0x21e0
movb $0x1, %al
movq %rax, 0x58(%rsp)
jmp 0x28b0
xorl %edi, %edi
callq 0x22f0
movq 0x462c(%rip), %rcx      # 0x6fd8
movq (%rcx), %rcx
testl %eax, %eax
je 0x2b49
leaq 0x1f52(%rip), %rdi      # 0x4910
pushq $0x3f
popq %rsi
pushq $0x1
popq %rdx
callq 0x2330
callq 0x2260
movq 0x30(%rsp), %r13
addq $0x10, %r12
jmp 0x27db
movb $0x1, %bl
leaq 0x60(%rsp), %rdi
callq 0x2d8a
testb %bl, %bl
jne 0x277d
jmp 0x2ab4
movq 0x45dc(%rip), %rax      # 0x6fd8
movq (%rax), %rcx
leaq 0x16fa(%rip), %rdi      # 0x4100
pushq $0x10
popq %rsi
pushq $0x1
popq %rdx
callq 0x2330
xorl %ebx, %ebx
pushq $0x1
popq %rax
movl %eax, 0x3c(%rsp)
jmp 0x29de
callq 0x2bfb
movq %rax, %rbx
testq %r13, %r13
je 0x2a59
leaq 0x16fc(%rip), %rsi      # 0x412c
movq %r13, %rdi
movq %r14, %rdx
xorl %eax, %eax
callq 0x2290
testb %bpl, %bpl
jne 0x2a79
leaq 0x1702(%rip), %rdi      # 0x414b
pushq $0x28
popq %rsi
pushq $0x1
popq %rdx
movq %r13, %rcx
callq 0x2330
jmp 0x2a5e
testb %bpl, %bpl
jne 0x2a79
movq 0x20(%rsp), %rdi
xorl %edx, %edx
testb $0x1, 0xb(%rsp)
cmovneq 0x28(%rsp), %rdx
movl 0x14(%rsp), %esi
callq 0x32ca
movl 0x10(%rsp), %edi
callq 0x2340
testq %r13, %r13
je 0x2ab4
subq 0x78(%rsp), %rbx
movl $0x3e8, %ecx            # imm = 0x3E8
movq %rbx, %rax
cqto
idivq %rcx
movq %rdx, %r8
leaq 0x16d1(%rip), %rsi      # 0x4174
movq %r13, %rdi
movl 0x18(%rsp), %edx
movq %rax, %rcx
xorl %eax, %eax
callq 0x2290
leaq 0xb8(%rsp), %rdi
callq 0x3884
movl 0x3c(%rsp), %ebx
leaq 0x20(%rsp), %rdi
callq 0x2c9c
jmp 0x2645
movq (%rbx), %rdi
leaq 0x153a(%rip), %rsi      # 0x4018
jmp 0x263d
movq (%rbx), %rdi
leaq 0x1541(%rip), %rsi      # 0x402e
jmp 0x263d
movq 0x44df(%rip), %rax      # 0x6fd8
movq (%rax), %rbx
callq 0x2040
movl (%rax), %edi
callq 0x20b0
leaq 0x1564(%rip), %rsi      # 0x4073
movq %rbx, %rdi
movq 0x48(%rsp), %rdx
movq %rax, %rcx
xorl %eax, %eax
callq 0x2290
jmp 0x2642
movq 0x44ab(%rip), %rax      # 0x6fd8
movq (%rax), %rdi
leaq 0x1574(%rip), %rsi      # 0x40ab
movq %rbx, %rdx
xorl %eax, %eax
callq 0x2290
pushq $0x1
popq %rbx
jmp 0x2ac5
leaq 0x1e00(%rip), %rdi      # 0x4950
pushq $0x5a
popq %rsi
pushq $0x1
popq %rdx
callq 0x2330
pushq $0x1
popq %rdi
callq 0x2200
movq %rax, %rbx
leaq 0xb8(%rsp), %rdi
callq 0x2120
jmp 0x2bb0
jmp 0x2b87
jmp 0x2b87
jmp 0x2b7b
movq %rax, %rbx
jmp 0x2ba6
movq %rax, %rbx
jmp 0x2bb0
jmp 0x2b8c
movq %rax, %rbx
jmp 0x2b99
movq %rax, %rbx
leaq 0x60(%rsp), %rdi
callq 0x2d8a
leaq 0xb8(%rsp), %rdi
callq 0x3884
leaq 0x20(%rsp), %rdi
callq 0x2c9c
movq %rbx, %rdi
callq 0x2300