// File: /workspace/github_cpp_makefile_star2_O1/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, %r13
movl %edi, %ebp
movq 0x496f(%rip), %rax      # 0x6fd8
movq (%rax), %rbx
movl $0x2, %edi
callq 0x22e0
testl %eax, %eax
leaq 0x1a91(%rip), %rcx      # 0x4110
leaq 0x1983(%rip), %rax      # 0x4009
cmoveq %rcx, %rax
movq %rax, 0xa0(%rsp)
leaq 0x196b(%rip), %rax      # 0x4004
cmoveq %rcx, %rax
movq %rax, 0x98(%rsp)
movl $0x1, 0x4(%rsp)
movl $0x9c4, 0x18(%rsp)      # imm = 0x9C4
movb $0x1, %r12b
leaq 0x194f(%rip), %r14      # 0x400e
movq 0x4902(%rip), %r15      # 0x6fc8
movq %rbx, 0x20(%rsp)
movq %rbx, %rax
xorl %ebx, %ebx
movq %rax, 0x48(%rsp)
movb $0x1, %al
movq %rax, 0x40(%rsp)
movb $0x1, %al
movl %eax, 0x28(%rsp)
movb $0x1, %al
movl %eax, 0x1c(%rsp)
movl %ebx, %ecx
movl %ecx, %ebx
movl %ebp, %edi
movq %r13, %rsi
movq %r14, %rdx
callq 0x2070
movb $0x1, %cl
cmpl $0x6e, %eax
je 0x26ea
cmpl $0x62, %eax
jle 0x2734
cmpl $0x70, %eax
jle 0x275c
cmpl $0x73, %eax
je 0x2772
cmpl $0x71, %eax
jne 0x2d52
movq $0x0, 0x48(%rsp)
movq 0x40(%rsp), %rax
movl %eax, %r12d
movq $0x0, 0x40(%rsp)
jmp 0x26e8
cmpl $-0x1, %eax
je 0x2798
cmpl $0x46, %eax
je 0x278b
cmpl $0x62, %eax
jne 0x2d52
movq (%r15), %rdi
callq 0x22b0
movl %eax, 0x4(%rsp)
testl %eax, %eax
jg 0x26e8
jmp 0x2dba
cmpl $0x63, %eax
jne 0x2d43
movl $0x0, 0x28(%rsp)
jmp 0x26e8
movq (%r15), %rdi
callq 0x22b0
movl %eax, 0x18(%rsp)
testl %eax, %eax
jns 0x26e8
jmp 0x2db0
movl $0x0, 0x1c(%rsp)
jmp 0x26e8
movq 0x4841(%rip), %rax      # 0x6fe0
movslq (%rax), %rax
cmpl %ebp, %eax
jge 0x2d5c
movl %ebx, %r15d
movq (%r13,%rax,8), %rbx
leaq 0xc8(%rsp), %r14
movq %r14, -0x10(%r14)
leaq 0x18ac(%rip), %rsi      # 0x4071
leaq 0x18a6(%rip), %rdx      # 0x4072
leaq 0xb8(%rsp), %rdi
callq 0x2e6a
leaq 0xb8(%rsp), %rdi
movq %rbx, %rsi
callq 0x20a0
testl %eax, %eax
movq %rbx, 0x38(%rsp)
je 0x2804
movq %rbx, %rdi
xorl %esi, %esi
xorl %eax, %eax
callq 0x2130
movl %eax, 0x14(%rsp)
jmp 0x280c
movl $0x0, 0x14(%rsp)
movq 0xb8(%rsp), %rdi
cmpq %r14, %rdi
je 0x2829
movq 0xc8(%rsp), %rsi
incq %rsi
callq 0x21a0
cmpl $0x0, 0x14(%rsp)
js 0x2d66
movq 0x47a5(%rip), %rax      # 0x6fe0
movslq (%rax), %rax
decl %ebp
cmpl %ebp, %eax
jge 0x284b
movq 0x8(%r13,%rax,8), %r14
jmp 0x2852
leaq 0x183a(%rip), %r14      # 0x408c
movl %r15d, %ebx
leaq 0x1845(%rip), %rsi      # 0x40a1
movq %r14, %rdi
callq 0x2260
testl %eax, %eax
sete %al
orb %al, %bl
movq $0x0, 0x8(%rsp)
movq 0x38(%rsp), %r15
jne 0x28b8
movq %r14, %rdi
callq 0x3064
movq 0x8(%rsp), %r13
movq %rax, 0x8(%rsp)
testq %r13, %r13
je 0x28a7
movq %r13, %rdi
callq 0x3044
movl $0x48, %esi
movq %r13, %rdi
callq 0x21a0
cmpq $0x0, 0x8(%rsp)
movq 0x38(%rsp), %r15
je 0x2d89
movq 0x8(%rsp), %rdi
testq %rdi, %rdi
je 0x28d8
xorl %edx, %edx
testb $0x1, 0x40(%rsp)
cmovneq 0x20(%rsp), %rdx
movl 0x18(%rsp), %esi
callq 0x3464
movq 0x48(%rsp), %rdi
testq %rdi, %rdi
je 0x290a
testb %bl, %bl
leaq 0x180a(%rip), %r8       # 0x40f5
leaq 0x181e(%rip), %rax      # 0x4110
cmoveq %rax, %r8
leaq 0x17cf(%rip), %rsi      # 0x40cc
movq %r15, %rdx
movq %r14, %rcx
xorl %eax, %eax
callq 0x2280
movzbl 0x28(%rsp), %ecx
andl $0x1, %ecx
leaq 0xb8(%rsp), %rdi
movl $0x100000, %edx         # imm = 0x100000
movl 0x14(%rsp), %esi
callq 0x393c
movl $0x100000, %edi         # imm = 0x100000
callq 0x2030
movq %rax, 0x80(%rsp)
movl %ebx, %r13d
notb %r13b
leaq 0x58(%rsp), %r14
movq %r14, %rdi
xorl %esi, %esi
callq 0x22c0
movabsq $-0x20c49ba5e353f7cf, %rax # imm = 0xDF3B645A1CAC0831
imulq 0x8(%r14)
movq %rdx, %rax
shrq $0x3f, %rax
sarq $0x7, %rdx
addq %rax, %rdx
movq %rdx, 0x78(%rsp)
testb %r13b, 0x1c(%rsp)
movq (%r14), %rax
movq %rax, 0x70(%rsp)
movl 0x4(%rsp), %eax
movq %rax, 0x88(%rsp)
leaq 0x177f(%rip), %rax      # 0x410f
leaq 0x1784(%rip), %rcx      # 0x411b
cmoveq %rax, %rcx
movq %rcx, 0x90(%rsp)
movl $0x0, 0x4(%rsp)
movl $0x0, 0x34(%rsp)
movb %r12b, 0x3(%rsp)
movl %ebx, 0x50(%rsp)
cmpb $0x0, 0xd1(%rsp)
jne 0x2c38
leaq 0x58(%rsp), %rdi
leaq 0xb8(%rsp), %rsi
movq 0x88(%rsp), %rdx
callq 0x3a22
testb %bl, %bl
jne 0x2a07
movq 0x8(%rsp), %rdi
movq 0x80(%rsp), %rsi
leaq 0x58(%rsp), %rdx
callq 0x35d6
testb %al, %al
je 0x2c27
movq 0x58(%rsp), %r15
movq 0x60(%rsp), %rax
movq %rax, 0xa8(%rsp)
cmpq %rax, %r15
je 0x2bff
movl (%r15), %eax
movq 0x8(%r15), %rcx
movq %rcx, 0xb0(%rsp)
incl 0x4(%rsp)
decl %eax
movl %eax, 0x54(%rsp)
movq $0x0, 0x28(%rsp)
testb %r13b, 0x1c(%rsp)
je 0x2ad2
movq 0x8(%rsp), %rbx
leaq 0x8(%rbx), %rdi
callq 0x3cac
cmpb $0x0, 0x21(%rbx)
je 0x2a76
movl $0x1, %ebx
movl $0x30, %ebp
leaq 0x1e5c(%rip), %r14      # 0x48d0
jmp 0x2ad9
movq %rax, %rbp
movq %rdx, %r14
cmpq $0x2, %rax
jb 0x2a9a
movl $0x2, %edx
movq %r14, %rdi
leaq 0x1e70(%rip), %rsi      # 0x4901
callq 0x2210
testl %eax, %eax
je 0x2ad2
movl $0x2, %ebx
cmpq $0x5, %rbp
jb 0x2ad9
setb %bl
movl $0x5, %edx
movq %r14, %rdi
leaq 0x1e4d(%rip), %rsi      # 0x4904
callq 0x2210
xorl %ecx, %ecx
testl %eax, %eax
sete %al
orb %al, %bl
je 0x2b02
movb %al, %cl
movl $0x2, %ebx
subl %ecx, %ebx
jmp 0x2ad9
xorl %ebp, %ebp
xorl %r14d, %r14d
xorl %ebx, %ebx
testl %ebx, %ebx
setne %al
testb %r12b, %al
jne 0x2b43
testb $0x1, 0x40(%rsp)
jne 0x2b43
cmpl $0x1, %ebx
je 0x2b43
cmpl $0x1, %ebx
je 0x2b23
cmpl $0x2, %ebx
je 0x2a44
jmp 0x2be9
movl $0x5, %edx
movq %r14, %rdi
leaq 0x1df9(%rip), %rsi      # 0x490a
callq 0x2210
cmpl $0x1, %eax
movl $0x2, %ebx
sbbl $0x0, %ebx
jmp 0x2ad9
xorl %edi, %edi
callq 0x22e0
movq 0x44a7(%rip), %rcx      # 0x6fd8
movq (%rcx), %rdi
testl %eax, %eax
je 0x2dab
callq 0x248e
jmp 0x2af4
testb $0x1, 0x28(%rsp)
jne 0x2b74
movq 0x20(%rsp), %rdi
leaq 0x15bb(%rip), %rsi      # 0x4111
movl 0x4(%rsp), %edx
movl 0x54(%rsp), %ecx
movq 0xb0(%rsp), %r8
xorl %eax, %eax
callq 0x2280
movb $0x1, %al
movq %rax, 0x28(%rsp)
testl %ebx, %ebx
jne 0x2b91
movq 0x20(%rsp), %r12
movq %r12, %rdi
movq 0x90(%rsp), %rsi
xorl %eax, %eax
callq 0x2280
jmp 0x2bd7
testq %rbp, %rbp
je 0x2bac
movsbl -0x1(%r14,%rbp), %edi
callq 0x2060
testl %eax, %eax
je 0x2bac
decq %rbp
jne 0x2b96
xorl %ebp, %ebp
movq 0x20(%rsp), %r12
movq %r12, %rdi
leaq 0x1567(%rip), %rsi      # 0x4122
movq 0x98(%rsp), %rdx
movl %ebp, %ecx
movq %r14, %r8
movq 0xa0(%rsp), %r9
xorl %eax, %eax
callq 0x2280
movq %r12, %rdi
callq 0x21d0
movb 0x3(%rsp), %r12b
jmp 0x2aef
addq $0x10, %r15
cmpq 0xa8(%rsp), %r15
jne 0x2a22
movl 0x50(%rsp), %ebx
movb $0x1, %bpl
movq 0x58(%rsp), %rdi
testq %rdi, %rdi
je 0x2c19
movq 0x68(%rsp), %rsi
subq %rdi, %rsi
callq 0x21a0
testb %bpl, %bpl
jne 0x29bc
jmp 0x2d26
callq 0x246c
movl $0x1, 0x34(%rsp)
xorl %ebp, %ebp
jmp 0x2c02
movl %ebx, %ebp
leaq 0x58(%rsp), %r12
movq %r12, %rdi
xorl %esi, %esi
callq 0x22c0
movabsq $0x20c49ba5e353f7cf, %r14 # imm = 0x20C49BA5E353F7CF
movq %r14, %rax
imulq 0x8(%r12)
movq %rdx, %r13
movq (%r12), %rbx
movq 0x48(%rsp), %r15
testq %r15, %r15
je 0x2c82
leaq 0x14b9(%rip), %rsi      # 0x412c
movq %r15, %rdi
movq 0x38(%rsp), %rdx
xorl %eax, %eax
callq 0x2280
testb %bpl, %bpl
movq 0x20(%rsp), %r12
jne 0x2cc3
testq %r15, %r15
je 0x2caa
leaq 0x14b3(%rip), %rdi      # 0x414b
movl $0x28, %esi
movl $0x1, %edx
movq %r15, %rcx
callq 0x2320
movq 0x8(%rsp), %rdi
xorl %edx, %edx
testb $0x1, 0x3(%rsp)
cmovneq %r12, %rdx
movl 0x18(%rsp), %esi
callq 0x3464
movl 0x14(%rsp), %edi
callq 0x2330
testq %r15, %r15
je 0x2d26
movq %r13, %rax
shrq $0x3f, %rax
sarq $0x7, %r13
addq %rax, %r13
addq 0x78(%rsp), %r13
subq 0x70(%rsp), %rbx
imulq $0x3e8, %rbx, %r8       # imm = 0x3E8
addq %r13, %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 0x145c(%rip), %rsi      # 0x4174
movq %r15, %rdi
movl 0x4(%rsp), %edx
xorl %eax, %eax
callq 0x2280
leaq 0xb8(%rsp), %rdi
callq 0x3978
movl 0x34(%rsp), %ebx
leaq 0x8(%rsp), %rdi
callq 0x2e36
jmp 0x2d75
cmpl $0x68, %eax
jne 0x2d52
movq %r13, %rdi
callq 0x2350
jmp 0x2d70
movq %r13, %rdi
callq 0x2508
jmp 0x2d70
movq %r13, %rdi
callq 0x2425
jmp 0x2d70
movq 0x38(%rsp), %rdi
callq 0x24cc
movl $0x1, %ebx
movl %ebx, %eax
addq $0xf8, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
movq 0x4248(%rip), %rax      # 0x6fd8
movq (%rax), %rdi
leaq 0x1311(%rip), %rsi      # 0x40ab
movq %r14, %rdx
xorl %eax, %eax
callq 0x2280
movl $0x1, %ebx
jmp 0x2d37
callq 0x24ae
movq %r13, %rdi
callq 0x2397
jmp 0x2d70
movq %r13, %rdi
callq 0x23de
jmp 0x2d70
movq %rax, %rbx
movq 0xb8(%rsp), %rdi
cmpq %r14, %rdi
je 0x2e2e
movq 0xc8(%rsp), %rsi
incq %rsi
callq 0x21a0
jmp 0x2e2e
jmp 0x2df8
jmp 0x2df8
jmp 0x2dec
movq %rax, %rbx
jmp 0x2e24
movq %rax, %rbx
jmp 0x2e2e
jmp 0x2dfd
movq %rax, %rbx
jmp 0x2e17
movq %rax, %rbx
movq 0x58(%rsp), %rdi
testq %rdi, %rdi
je 0x2e17
movq 0x68(%rsp), %rsi
subq %rdi, %rsi
callq 0x21a0
leaq 0xb8(%rsp), %rdi
callq 0x3978
leaq 0x8(%rsp), %rdi
callq 0x2e36
movq %rbx, %rdi
callq 0x22f0