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
//! # ricat: A Rust-Based `cat` Command Implementation
//!
//! This project is a Rust-based reimagining of the classic Unix `cat` command, drawing inspiration from its original implementation in GNU Core Utilities. It demonstrates the power and flexibility of Rust for system utilities development.
//!
//! A key design principle of `ricat` is extensibility. By utilizing a trait, `LineTextFeature`, the application makes it straightforward to introduce new functionalities. Developers can add custom features by implementing the `apply_feature()` method for each line of text. The core logic of `ricat` seamlessly integrates these features without requiring additional modifications.
//!
//! ## Features
//!
//! - **Modular Design**: Easy to extend with new line-based text processing features.
//! - **Trait-Based Feature Implementation**: Implement the `LineTextFeature` trait to create new features.
//! - **Line Numbering**: Display line numbers for each line of the input.
//! - **Dollar Symbol at End**: Append a `$` symbol at the end of each line.
//! - **Replace Tab Spaces**: Replace tab spaces in the text with `^I`.
//! - **Compress Empty Lines**: Compress multiple consecutive empty lines into a single empty line.
//! - **Search Text**: Search for lines containing a specific text or regular expression pattern. Prefix the search text with 'reg:' to treat it as a regular expression, e.g., 'reg:\\d+' to search for digits.
//! - **Case-Insensitive Search**: Perform case-insensitive search for lines containing a specific text.
//! - **Base64 Encoding**: Encode the input text using Base64.
//! - **Base64 Decoding**: Decode Base64 encoded text.
//! - **Pagination**: Display the output in a paginated manner, allowing user to navigate through pages.
//! - **Configuration File**: Load preset features from a configuration file (`ricat_cfg.toml`) located in the user's configuration directory (`$HOME/.config/ricat`).
//!
//! ## Usage
//!
//! `ricat` supports various command-line options to enable different features and customize the output. Here are some common usage examples:
//!
//! ### Read a File directly
//! ```bash
//! ricat my_file.txt
//! ```
//!
//! ### Read a File With Line Numbering Enabled
//! ```bash
//! ricat -n my_file.txt
//! ```
//!
//! ### Read a File with `$` at End of Each Line
//! ```bash
//! ricat -d my_file.txt
//! ```
//!
//! ### Replace Tab Spaces with `^I`
//! ```bash
//! ricat -t my_file.txt
//! ```
//!
//! ### Compress Empty Lines
//! ```bash
//! ricat -s my_file.txt
//! ```
//!
//! ### Search for Lines Containing a Specific Text
//! ```bash
//! ricat --search --text "search_text" my_file.txt
//! ```
//!
//! ### Search for Lines Matching a Regular Expression
//! ```bash
//! ricat --search --text "reg:\\d+" my_file.txt
//! ```
//!
//! ### Perform Case-Insensitive Search
//! ```bash
//! ricat --search --text "search_text" -i my_file.txt
//! ```
//!
//! ### Encode Input Text Using Base64
//! ```bash
//! ricat --encode-base64 my_file.txt
//! ```
//!
//! ### Decode Base64 Encoded Text
//! ```bash
//! ricat --decode-base64 my_encoded_file.txt
//! ```
//!
//! ### Enable Pagination
//! ```bash
//! ricat --pages my_large_file.txt
//! ```
//!
//! ## Configuration File
//!
//! `ricat` supports loading preset features from a configuration file (`ricat_cfg.toml`) located in the user's configuration directory (`$HOME/.config/ricat`). The configuration file is automatically created during the installation process using `cargo install`.
//!
//! The configuration file allows users to enable or disable specific features by setting the corresponding fields to `true` or `false`. Here's an example of the `ricat_cfg.toml` file:
//!
//! ```toml
//! number_feature = true
//! dollar_sign_feature = false
//! tabs_feature = false
//! compress_empty_line_feature = false
//! ```
//!
//! When `ricat` is executed, it reads the configuration file and enables the specified features accordingly. This provides a convenient way for users to customize the behavior of `ricat` without having to specify the options every time they run the command.
//!
//! ## Benchmarks
//!
//! Added a benchmarking module to test the performance of the application. The benchmarks covers only the direct file read(without features).
//! To run the benchmarks, use the following command:
//! in src/
//! ```bash
//! ./benchmark_plot.sh
//! ```
//! The script will run the benchmarks and generate a plot using `matplotlib` Be sure to install the required dependencies before running the script.
//! Dependency: `matplotlib`
//!
//!
//! ## Extending ricat
//!
//! Adding a new feature to `ricat` is as simple as implementing the `LineTextFeature` trait for any struct. This modular approach encourages experimentation and customization.
//!
//! For example, to add a feature that highlights TODO comments in your text files, define a struct implementing `LineTextFeature` that scans each line for the pattern and applies the desired formatting.
//!
//! ## Testing
//!
//! `ricat` includes a comprehensive test suite to ensure the correctness and reliability of its functionality. The tests cover various scenarios and edge cases, including:
//!
//! - Basic functionality of each feature
//! - Interaction between multiple features
//! - Handling of empty input
//! - Proper resetting of state between input sources
//! - Encoding and decoding of text using Base64
//! - Case-insensitive search functionality
//! - Loading and applying configuration from the `ricat_cfg.toml` file
//!
//! To run the tests, clone the repo and use the `cargo test` command.
//!
//! ## Contributing
//!
//! Contributions to `ricat` are welcome! If you have an idea for a new feature or improvement, please open an issue or submit a pull request on the project's GitHub repository.
//!
//! When contributing, please ensure that your changes are well-tested and adhere to the project's coding style and conventions.
//!
//! ## License
//!
//! `ricat` is open-source software licensed under the [MIT License](https://opensource.org/licenses/MIT).

pub mod encoding_decoding_feature;
pub mod errors;
pub mod config;
mod tests;

use clap::Parser;
use crossterm::{
    cursor::{Hide, Show},
    event::{read, Event, KeyCode},
    execute,
    terminal::{self, Clear, ClearType},
};
use errors::RicatError;
use memmap2::Mmap;
use regex::Regex;
use std::{
    fs::File, io::{stdin, stdout, BufRead, BufReader, BufWriter, Read, Write}, process
};
use crate::config::load_config;


// Encoding-Decoding Module
pub use encoding_decoding_feature::{Base64, DataEncoding as _};

/// get current user terminal height for pagination
fn get_terminal_height() -> u16 {
    match terminal::size() {
        Ok((_, height)) => height,
        Err(_) => 24, //default
    }
}

/// Trait defining a text feature that can be applied to lines of input.
pub trait LineTextFeature {
    /// Applies a specific feature to a line of text and returns the modified line or None to omit the line.
    fn apply_feature(&mut self, line: &str) -> Option<String>;
}

/// Feature: adding line numbers to each line of text.
pub struct LineNumbering {
    current_line: usize,
}

impl LineNumbering {
    pub fn new() -> Self {
        Self { current_line: 1 }
    }
}
impl LineTextFeature for LineNumbering {
    fn apply_feature(&mut self, line: &str) -> Option<String> {
        let result = Some(format!("{:} {}", self.current_line, line));
        self.current_line += 1;
        result
    }
}

/// Feature: adding `$` at the last of the line
pub struct DollarSymbolAtLast;

impl DollarSymbolAtLast {
    pub fn new() -> Self {
        Self
    }
}

impl LineTextFeature for DollarSymbolAtLast {
    fn apply_feature(&mut self, line: &str) -> Option<String> {
        Some(format!("{}$", line))
    }
}

/// Feature: adding `^I` in place of all the tab-spaces used in the text.
pub struct ReplaceTabspaces;
impl ReplaceTabspaces {
    pub fn new() -> Self {
        Self
    }
}

impl LineTextFeature for ReplaceTabspaces {
    fn apply_feature(&mut self, line: &str) -> Option<String> {
        Some(line.replace('\t', "^I"))
    }
}

/// Feature: Compresses multiple consecutive empty lines into a single empty line
pub struct CompressEmptyLines {
    was_last_line_empty: bool,
}

impl CompressEmptyLines {
    pub fn new() -> Self {
        Self {
            was_last_line_empty: false,
        }
    }
}

impl LineTextFeature for CompressEmptyLines {
    fn apply_feature(&mut self, line: &str) -> Option<String> {
        if line.trim().is_empty() {
            if self.was_last_line_empty {
                None
            } else {
                self.was_last_line_empty = true;
                Some(String::new()) // Return an empty string to indicate a single empty line should be printed.
            }
        } else {
            self.was_last_line_empty = false;
            Some(line.to_string())
        }
    }
}

/// Feature: Returns Lines which contain a given text/regex
pub struct LineWithGivenText {
    /// search pattern or string input
    search_pattern: String,
    /// ignore case for search
    _ignore_case: bool,
    /// compiled regex; is cached.
    regex: Option<Regex>,
}

impl LineWithGivenText {
    pub fn new(text: &str, ignore_case: bool) -> Self {
        let (is_regex, clean_text) = if text.starts_with("reg:") {
            (true, &text["reg:".len()..]) // Strip the prefix and treat the rest as a regex
        } else {
            (false, text) // literal text
        };

        let pattern = if is_regex {
            if ignore_case {
                format!("(?i){}", clean_text)
            } else {
                clean_text.to_string()
            }
        } else {
            let escaped_text = regex::escape(clean_text);
            if ignore_case {
                format!("(?i){}", escaped_text)
            } else {
                escaped_text
            }
        };

        Self {
            search_pattern: pattern,
            _ignore_case: ignore_case,
            regex: None,
        }
    }
}

impl LineTextFeature for LineWithGivenText {
    fn apply_feature(&mut self, line: &str) -> Option<String> {
        if self.regex.is_none() {
            self.regex = Regex::new(&self.search_pattern)
                .map_err(|err| RicatError::RegexCompilationError(format!("Invalid regex '{}': {}", self.search_pattern, err)))
                .ok();
        }

        if let Some(ref regex) = self.regex {
            if regex.is_match(line) {
                return Some(line.to_string());
            }
        }
        None
    }
}

/// Base64 Encoding Feature Integration
pub struct Base64Encoding;

impl Base64Encoding {
    pub fn new() -> Self {
        Self
    }
}

impl LineTextFeature for Base64Encoding {
    fn apply_feature(&mut self, line: &str) -> Option<String> {
        Base64::encode(line)
    }
}

/// Base64 Decoding Feature Integration
pub struct Base64Decoding;

impl Base64Decoding {
    pub fn new() -> Self {
        Self
    }
}

impl LineTextFeature for Base64Decoding {
    fn apply_feature(&mut self, line: &str) -> Option<String> {
        Base64::decode(line)
    }
}

/// Command line arguments struct, parsed using `clap`.
#[derive(Parser)]
#[clap(
    version = "0.4.5",
    author = "Aditya Navphule <adityanav@duck.com>",
    about = "ricat (Rust Implemented `cat`) : A custom implementation of cat command in Rust"
)]
struct Cli {
    /// Enables line numbering for each line of the input.
    #[clap(short = 'n', long, action = clap::ArgAction::SetTrue, help = "shows line numbers for each line")]
    numbers: bool,

    #[clap(short = 'd', long, action = clap::ArgAction::SetTrue, help = "adds `$` to mark end of each line")]
    dollar: bool,

    #[clap(short = 't', long, action = clap::ArgAction::SetTrue, help = "replaces the tab spaces in the text with ^I")]
    tabs: bool,

    #[clap(short = 's', long, action = clap::ArgAction::SetTrue, help = "suppress repeated empty output lines")]
    squeeze_blank: bool,

    #[clap(
        long = "search", 
        action = clap::ArgAction::SetTrue, 
        help = "Search text inside the file. Returns all lines containing the text."
    )]
    search_flag: bool,
    
    #[clap(
        long = "text",
        help = "Search text: only considered when --search flag is used. Use 'reg:' prefix for regex search, e.g., 'reg:\\\\w+' for words."
    )]
    search_text: Option<String>,
    
    #[clap(
        short = 'i',
        long = "ignore-case",
        help = "Ignore case for searching text: only considered when --search flag is used.",
        action=clap::ArgAction::SetTrue,
    )]
    ignore_case: bool,
    

    #[clap(long = "pages", action = clap::ArgAction::SetTrue, help = "Apply Pagination to the output")]
    pagination: bool,

    #[clap(long = "encode-base64", action = clap::ArgAction::SetTrue, help = "Encode the input text using Base64")]
    encode: bool,

    #[clap(long = "decode-base64", action = clap::ArgAction::SetTrue, help = "Decode the input text using Base64")]
    decode: bool,

    /// Optional file path to read from instead of standard input.
    #[clap(help = "File(s) you want to read, multiple files will be appended one after another")]
    files: Vec<String>,
}

fn main() {
    match run() {
        Ok(_) => {}
        Err(error) => {
            eprintln!("Error: {}", error);
            process::exit(1);
        }
    }
}

// DEBUG print if each feature is enabled or not
// fn see_features(arguments: &Cli) {
//     println!("Features Enabled:");
//     println!("Line Numbers: {}", arguments.numbers);
//     println!("Dollar Symbol: {}", arguments.dollar);
//     println!("Tabs: {}", arguments.tabs);
//     println!("Compress Empty Lines: {}", arguments.squeeze_blank);
//     println!("Search: {}", arguments.search_flag);
//     println!("Pagination: {}", arguments.pagination);
//     println!("Encode Base64: {}", arguments.encode);
//     println!("Decode Base64: {}", arguments.decode);
//     println!();
// }

/// Starts Executing Ricat
fn run() -> Result<(), RicatError> {
    // Load the configuration file
    let configuration = load_config();


    let mut arguments = Cli::parse();

    enable_features_from_config(&configuration, &mut arguments);
    let mut features = add_features_from_args(&arguments); // stores the implemented features
       

    // Determine the input source based on command line arguments
    match (arguments.files.is_empty(), features.is_empty()) {
        (true, true) => handle_via_std_output(&arguments),
        (true, false) | (false, false) => handle_files_or_features(&arguments, &mut features),
        (false, true) => handle_files_without_features(&arguments),
    }
}

/// handling empty files and features
fn handle_via_std_output(_arguments: &Cli) -> Result<(), RicatError> {
    let input = stdin();
    let output = stdout();
    copy(input, output)?;

    Ok(())
}

/// handle files or features : features are enabled, files can/cannot be passed
fn handle_files_or_features(
    arguments: &Cli,
    features: &mut [Box<dyn LineTextFeature>],
) -> Result<(), RicatError> {
    if arguments.files.is_empty() {
        process_input_stdout(stdin(), features, false).map_err(|error| {
            RicatError::LineProcessingError(format!("Error processing line: {}", error))
        })?;
        Ok(())
    } else {
        let reader_sources: Result<Vec<Box<dyn Read>>, RicatError> = arguments
            .files
            .iter()
            .map(|file_path| {
                File::open(file_path)
                    .map(|file| Box::new(file) as Box<dyn Read>)
                    .map_err(|error| {
                        RicatError::FileOpenError(format!(
                            "Failed to open {}: {}",
                            file_path, error
                        ))
                    })
            })
            .collect();

        let reader_sources = reader_sources?;

        let mut all_processed_lines = Vec::<String>::new();

        for source in reader_sources {
            let processed_lines = process_input_ret(source, features).map_err(|error| {
                RicatError::LineProcessingError(format!("Error processing line: {}", error))
            })?;
            all_processed_lines.extend(processed_lines);
        }

        if arguments.pagination {
            match paginate_output(all_processed_lines, stdout()) {
                Ok(completed) => {
                    if completed {
                        Ok(())
                    } else {
                        Ok(())
                    }
                }
                Err(error) => Err(RicatError::PaginationError(format!("Error paginating: {}", error))),
            }
        } else {
            let stdout = stdout();
            let mut buf_writer = BufWriter::new(stdout.lock());

            for line in all_processed_lines {
                writeln!(buf_writer, "{}", line).map_err(|error| {
                    RicatError::LineProcessingError(format!("Error writing line: {}", error))
                })?;
            }

            buf_writer.flush().map_err(|error| {
                RicatError::OutputFlushError(format!("Error flushing output: {}", error))
            })?;
            Ok(())
        }
    }
}
/// handle files without features
fn handle_files_without_features(arguments: &Cli) -> Result<(), RicatError> {
    if arguments.pagination {
        let mut all_lines = Vec::<String>::new();
        for file_path in &arguments.files {
            let file = File::open(file_path).map_err(|error| {
                RicatError::FileOpenError(format!("Error opening file {}: {}", file_path, error))
            })?;
            let processed_lines =
                process_input_ret(BufReader::new(file), &mut []).map_err(|error| {
                    RicatError::LineProcessingError(format!("Error processing line: {}", error))
                })?;

            all_lines.extend(processed_lines);
        }
        match paginate_output(all_lines, stdout()) {
            Ok(completed) => {
                if completed {
                    Ok(())
                } else {
                    Ok(())
                }
            }
            Err(error) => Err(RicatError::PaginationError(format!("Error paginating: {}", error))),
        }
    } else {
        // Directly copy files to standard output
        for file_path in &arguments.files {
            copy_mmap(file_path, stdout()).map_err(|error| error)?;
        }
        Ok(())
    }
}
/// Generate Feature Vector: Will Add Features based on arguments passed
fn add_features_from_args(arguments: &Cli) -> Vec<Box<dyn LineTextFeature>> {
    let mut features = Vec::<Box<dyn LineTextFeature>>::new();
    if arguments.squeeze_blank {
        features.push(Box::new(CompressEmptyLines::new()));
    }

    if arguments.encode {
        features.push(Box::new(Base64Encoding::new()));
    }

    if arguments.decode {
        features.push(Box::new(Base64Decoding::new()));
    }

    if arguments.search_flag {
        let text_to_search = match &arguments.search_text {
            None => "",
            Some(text) => text,
        };
        features.push(Box::new(LineWithGivenText::new(
            text_to_search.trim(),
            arguments.ignore_case,
        )));
    }

    if arguments.numbers {
        features.push(Box::new(LineNumbering::new()));
    }

    if arguments.dollar {
        features.push(Box::new(DollarSymbolAtLast::new()));
    }

    if arguments.tabs {
        features.push(Box::new(ReplaceTabspaces::new()));
    }

    features
}

/// Add features from configuration file
fn enable_features_from_config(config: &config::RicatConfig, arguments: &mut Cli) {
    // println!("Config: {:#?}", config);
    if config.number_feature && !arguments.numbers {
       arguments.numbers = true; 
    }

    if config.dollar_sign_feature && !arguments.dollar {
        arguments.dollar = true;
    }

    if config.tabs_feature && !arguments.tabs {
        arguments.tabs = true;
    }

    if config.compress_empty_line_feature && !arguments.squeeze_blank {
        arguments.squeeze_blank = true;
    }
}


/// Copies data from the reader to the writer without modification.
/* Less System Calls: the number of read and write system calls is reduced */
pub fn copy<R: Read, W: Write>(mut reader: R, mut writer: W) -> Result<(), RicatError> {
    // buffer to hold chunks of the file
    const BUFFER_SIZE: usize = 4096;
    let mut buffer = vec![0_u8; BUFFER_SIZE];

    loop {
        let len = reader.read(&mut buffer)?;
        if len == 0 {
            break; // End of file or stream
        }
        writer.write_all(&buffer[..len])?;
    }
    Ok(())
}

/*In Memory Copy: Via Memory Mapped IO */
// Memory-mapped I/O (MMIO) is a technique that allows the physical memory of a computer to be accessed using software. Specifically, memory-mapped I/O is used for accessing memory-mapped registers in the I/O space of a computer.
// Memory-mapped I/O is used to reduce the overhead of accessing the computer's memory by allowing the memory to be accessed directly by the CPU. This can improve the performance of the computer by reducing the number of instructions required to access the memory.
/// Copies data from the file to the writer using memory-mapped I/O.
pub fn copy_mmap<W:Write>(file_path: &str, mut writer: W) -> Result<(), RicatError> {
    let file = File::open(file_path).map_err(|error| {
        RicatError::FileOpenError(format!("Error opening file {}: {}", file_path, error))
    })?;

    let mmap = unsafe { Mmap::map(&file) }.map_err(|error| {
        RicatError::MemoryMapError(format!("Error mapping file to memory: {}", error))
    })?;

    writer.write_all(&mmap).map_err(|error| {
        RicatError::MemoryMapWriteError(format!("Error writing to output: {}", error))
    })?;

    Ok(())
}

/// Processing input and flushing to standard output
pub fn process_input_stdout<R: Read>(
    reader: R,
    features: &mut [Box<dyn LineTextFeature>],
    is_live: bool,
) -> Result<(), RicatError> {
    let buf_reader = BufReader::new(reader);
    let stdout = stdout();
    let stdout_lock = stdout.lock();

    let mut writer: Box<dyn Write> = if is_live {
        Box::new(BufWriter::new(stdout_lock))
    } else {
        Box::new(stdout_lock)
    };

    for line_result in buf_reader.lines() {
        let line = line_result?;
        let mut processed_line = Some(line);

        for feature in features.iter_mut() {
            if let Some(curr_line) = processed_line {
                processed_line = feature.apply_feature(&curr_line);
            } else {
                break;
            }
        }

        if let Some(curr_line) = processed_line {
            writeln!(writer, "{}", curr_line).map_err(|error| {
                RicatError::LineProcessingError(format!("Error writing line: {}", error))
            })?;
        }
    }

    writer.flush().map_err(|error| {
        RicatError::OutputFlushError(format!("Error flushing output: {}", error))
    })?;

    Ok(())
}/// Processes input by applying each configured text feature to every line.
pub fn process_input_ret<R: Read>(
    reader: R,
    features: &mut [Box<dyn LineTextFeature>],
) -> Result<Vec<String>, RicatError> {
    let buf_reader = BufReader::new(reader);
    let mut processed_lines = Vec::new();

    for line_result in buf_reader.lines() {
        let line = line_result?;
        let mut processed_line = Some(line);

        for feature in features.iter_mut() {
            if let Some(current_line) = processed_line {
                processed_line = feature.apply_feature(&current_line);
            } else {
                break;
            }
        }

        if let Some(current_line) = processed_line {
            processed_lines.push(current_line);
        }
    }
    Ok(processed_lines)
}

/// Paginate output
pub fn paginate_output<W: Write>(lines: Vec<String>, mut writer: W) -> Result<bool, RicatError> {
    let terminal_height = get_terminal_height() as usize;
    let page_size = terminal_height.saturating_sub(1);

    for (index, current_line) in lines.iter().enumerate() {
        writeln!(writer, "{}\r", current_line).map_err(|error| {
            RicatError::PaginationError(format!("Error writing line: {}", error))
        })?;
        if (index + 1) % page_size == 0 {
            match wait_for_user_input(&mut writer) {
                Ok(true) => continue,
                Ok(false) => return Ok(false),
                Err(error) => return Err(error),
            }
        }
    }
    Ok(true)
}

// Paginate Output using Iterators
fn _paginate_output_iterator<W: Write> (
    lines: impl Iterator<Item = String>,
    mut writer: W,
) -> Result<bool, RicatError> {
    let terminal_height = get_terminal_height() as usize;
    let page_size = terminal_height.saturating_sub(1);

    let mut lines_iter = lines.enumerate();

    loop {
        let mut current_page_lines = Vec::new();
        for (_idx, curr_line) in lines_iter.by_ref().take(page_size) {
            current_page_lines.push(curr_line);
        }

        if current_page_lines.is_empty() {
            break;
        }

        for curr_line in current_page_lines {
            writeln!(writer, "{}\r", curr_line).map_err(|error| {
                RicatError::PaginationError(format!("Error writing line: {}", error))
            })?;
        }

        match wait_for_user_input(&mut writer) {
            Ok(true) => continue,
            Ok(false) => return Ok(false),
            Err(error) => return Err(error),
        }
    }
    Ok(true)
}

/// Waiting for User Input
pub fn wait_for_user_input<W: Write>(writer: &mut W) -> Result<bool, RicatError> {
    execute!(writer, Hide).map_err(|error| RicatError::CursorHideError(error.to_string()))?;

    write!(writer, "--More--(press any key || q to quit)")
        .map_err(|error| RicatError::LineWriteError(error.to_string()))?;
    writer
        .flush()
        .map_err(|error| RicatError::OutputFlushError(error.to_string()))?;

    crossterm::terminal::enable_raw_mode()
        .map_err(|error| RicatError::RawModeEnableError(error.to_string()))?;

    let has_user_quit = loop {
        match read() {
            Ok(Event::Key(key_event)) => {
                if key_event.code == KeyCode::Char('q') {
                    break true;
                }
                break false;
            }
            Ok(_) => continue,
            Err(error) => {
                return Err(RicatError::InputReadError(error.to_string()));
            }
        }
    };

    crossterm::terminal::disable_raw_mode()
        .map_err(|error| RicatError::RawModeDisableError(error.to_string()))?;
    execute!(writer, Show).map_err(|error| RicatError::CursorShowError(error.to_string()))?;

    execute!(writer, Clear(ClearType::CurrentLine))
        .map_err(|error| RicatError::ClearLineError(error.to_string()))?;
    write!(writer, "\r").map_err(|error| RicatError::CursorMoveError(error.to_string()))?;

    Ok(!has_user_quit)
}