Make this amazing beautiful and advanced. Design the UI layout in the most extremely complex way possible, but in a good way. Make it advanced and more enterprise-grade.

// main.rs

use arch::x86::ArchSyntax;
use capstone::{prelude::*, Capstone};
use eframe::{
    egui::{
        self, menu, style::*, Align2, Color32, Context, FontData, FontDefinitions, FontFamily, FontId, Layout, RichText, Rounding, ScrollArea, SidePanel, Stroke, TextStyle, TopBottomPanel, Vec2
    },
    emath::Align,
    App, CreationContext, Frame, NativeOptions,
};
use object::{Object, ObjectSection, SectionKind};
use rfd::FileDialog;
use std::{borrow::Cow, collections::HashMap, fs::File, io::Read, str, sync::Arc};

mod symbol;
use symbol::{extract_symbols, SymbolInfo};

fn main() {
    let app = BinaryAnalyzerApp::default();
    let native_options = NativeOptions {
        viewport: egui::ViewportBuilder::default().with_inner_size([1024.0, 768.0]),
        ..Default::default()
    };
    eframe::run_native(
        "Rust Binary Analyzer",
        native_options,
        Box::new(|cc| Ok(Box::new(app.setup(cc)))),
    )
    .expect("Failed to start eframe");
}

struct BinaryAnalyzerApp {
    binary_path: String,
    analysis_result: AnalysisResult,
    error_message: Option<String>,
    selected_section: Option<SectionInfo>,
    selected_symbol: Option<SymbolInfo>,
    selected_string: Option<StringInfo>,
    dark_mode: bool,
    recent_files: Vec<String>,
    disassembly_cache: HashMap<u64, String>,
    search_query: String,
    selected_tab: Tab,
}

impl Default for BinaryAnalyzerApp {
    fn default() -> Self {
        Self {
            binary_path: String::new(),
            analysis_result: AnalysisResult::default(),
            error_message: None,
            selected_section: None,
            selected_symbol: None,
            selected_string: None,
            dark_mode: true,
            recent_files: Vec::new(),
            disassembly_cache: HashMap::new(),
            search_query: String::new(),
            selected_tab: Tab::SectionDetails,
        }
    }
}

impl BinaryAnalyzerApp {
    fn setup(self, cc: &CreationContext) -> Self {
        self.configure_fonts(cc);
        self.configure_visuals(cc);
        self
    }

    fn configure_fonts(&self, cc: &CreationContext) {
        let mut fonts = FontDefinitions::default();

        // Add custom font (optional)
        fonts.font_data.insert(
            "FiraCode-Regular".to_owned(),
            FontData::from_static(include_bytes!(
                "../assets/fonts/FiraCode-Regular.ttf"
            )),
        );

        fonts
            .families
            .entry(FontFamily::Monospace)
            .or_default()
            .insert(0, "FiraCode-Regular".to_owned());

        cc.egui_ctx.set_fonts(fonts);
    }

    fn configure_visuals(&self, cc: &CreationContext<'_>) {
        // Custom dark theme
        if self.dark_mode {
            cc.egui_ctx.set_visuals(Visuals {
                dark_mode: true,
                override_text_color: Some(Color32::from_gray(220)),
                widgets: Widgets {
                    noninteractive: WidgetVisuals {
                        bg_fill: Color32::from_gray(30),
                        bg_stroke: Stroke::new(1.0, Color32::from_gray(60)),
                        fg_stroke: Stroke::new(1.0, Color32::from_gray(180)),
                        rounding: Rounding::same(2.0),
                        weak_bg_fill: Color32::from_gray(20),
                        expansion: 0.0,
                    },
                    ..Default::default()
                },
                ..Visuals::dark()
            });
        } else {
            // Custom light theme
            cc.egui_ctx.set_visuals(Visuals {
                dark_mode: false,
                override_text_color: Some(Color32::BLACK),
                widgets: Widgets {
                    noninteractive: WidgetVisuals {
                        bg_fill: Color32::from_gray(240),
                        bg_stroke: Stroke::new(1.0, Color32::from_gray(200)),
                        fg_stroke: Stroke::new(1.0, Color32::BLACK),
                        rounding: Rounding::same(2.0),
                        expansion: 0.0,
                        weak_bg_fill: Color32::from_gray(20),
                    },
                    ..Default::default()
                },
                ..Visuals::light()
            });
        }

        // Style adjustments
        let mut style = (*cc.egui_ctx.style()).clone();
        style.spacing.item_spacing = Vec2::new(8.0, 8.0);
        style.text_styles = [
            (TextStyle::Heading, FontId::new(22.0, FontFamily::Proportional)),
            (TextStyle::Name("Heading2".into()), FontId::new(18.0, FontFamily::Proportional)),
            (TextStyle::Body, FontId::new(14.0, FontFamily::Proportional)),
            (TextStyle::Monospace, FontId::new(13.0, FontFamily::Monospace)),
            (TextStyle::Button, FontId::new(14.0, FontFamily::Proportional)),
            (TextStyle::Small, FontId::new(11.0, FontFamily::Proportional)),
        ]
        .into();
        cc.egui_ctx.set_style(style);
    }
}

impl App for BinaryAnalyzerApp {
    fn update(&mut self, ctx: &Context, frame: &mut Frame) {
        self.handle_file_drop(ctx);
        self.top_panel(ctx);
        self.side_panel(ctx);
        self.central_panel(ctx);
        self.status_bar(ctx);
    }
}

impl BinaryAnalyzerApp {
    /// Draws the top menu bar
    fn top_panel(&mut self, ctx: &Context) {
        TopBottomPanel::top("menu_bar").show(ctx, |ui| {
            ui.add_space(4.0);
            menu::bar(ui, |ui| {
                // File Menu
                ui.menu_button("📁 File", |ui| {
                    if ui.button("📂 Open...").clicked() {
                        self.open_file_dialog();
                        ui.close_menu();
                    }
                    if ui.button("🕒 Recent Files").clicked() {
                        // Handle recent files submenu
                        ui.close_menu();
                    }
                    if ui.button("❌ Exit").clicked() {
                        std::process::exit(0);
                    }
                });

                // View Menu
                ui.menu_button("🔍 View", |ui| {
                    if ui.checkbox(&mut self.dark_mode, "🌙 Dark Mode").clicked() {
                        if self.dark_mode {
                            ctx.set_visuals(Visuals::dark());
                        } else {
                            ctx.set_visuals(Visuals::light());
                        }
                        ui.close_menu();
                    }
                    if ui.button("🔄 Refresh").clicked() {
                        self.perform_analysis();
                        ui.close_menu();
                    }
                });

                // Help Menu
                ui.menu_button("❓ Help", |ui| {
                    if ui.button("ℹ About").clicked() {
                        ui.close_menu();
                        self.show_about(ctx);
                    }
                });

                ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                    ui.label(
                        RichText::new("🦀 Rust Binary Analyzer")
                            .font(FontId::proportional(14.0))
                            .color(Color32::LIGHT_BLUE),
                    );
                });
            });
            ui.add_space(4.0);
        });
    }

    /// Draws the side panel for navigation
    fn side_panel(&mut self, ctx: &Context) {
        SidePanel::left("side_panel")
            .resizable(false)
            .default_width(250.0)
            .show(ctx, |ui| {
                ui.add_space(10.0);
                ui.heading("🧭 Explorer");
                ui.separator();

                if !self.analysis_result.is_empty() {
                    // Search bar
                    ui.horizontal(|ui| {
                        ui.label("🔎");
                        ui.add(
                            egui::TextEdit::singleline(&mut self.search_query)
                                .hint_text("Search...")
                                .desired_width(f32::INFINITY),
                        );
                    });
                    ui.add_space(10.0);

                    ScrollArea::vertical().show(ui, |ui| {
                        ui.spacing_mut().item_spacing.y = 8.0;

                        ui.collapsing("📁 Sections", |ui| {
                            for section in &self.analysis_result.sections {
                                let selected = self
                                    .selected_section
                                    .as_ref()
                                    .map_or(false, |s| s.name == section.name);
                                if ui
                                    .selectable_label(selected, format!("📄 {}", section.name))
                                    .clicked()
                                {
                                    self.selected_section = Some(section.clone());
                                    self.selected_symbol = None;
                                    self.selected_string = None;
                                    self.selected_tab = Tab::SectionDetails;
                                }
                            }
                        });

                        ui.collapsing("🔖 Symbols", |ui| {
                            let symbols = if !self.search_query.is_empty() {
                                let query = self.search_query.to_lowercase();
                                self.analysis_result
                                    .symbols
                                    .iter()
                                    .filter(|symbol| {
                                        symbol.demangled_name.to_lowercase().contains(&query)
                                    })
                                    .cloned()
                                    .collect::<Vec<SymbolInfo>>()
                            } else {
                                self.analysis_result.symbols.clone()
                            };

                            for symbol in symbols {
                                let selected = self
                                    .selected_symbol
                                    .as_ref()
                                    .map_or(false, |s| s.name == symbol.name);
                                if ui
                                    .selectable_label(selected, format!("🔧 {}", symbol.demangled_name))
                                    .clicked()
                                {
                                    self.selected_symbol = Some(symbol.clone());
                                    self.selected_section = None;
                                    self.selected_string = None;
                                    self.selected_tab = Tab::SymbolDetails;
                                }
                            }
                        });

                        ui.collapsing("💬 Strings", |ui| {
                            let strings = if !self.search_query.is_empty() {
                                let query = self.search_query.to_lowercase();
                                self.analysis_result
                                    .strings
                                    .iter()
                                    .filter(|string_info| {
                                        string_info.value.to_lowercase().contains(&query)
                                    })
                                    .cloned()
                                    .collect::<Vec<StringInfo>>()
                            } else {
                                self.analysis_result.strings.clone()
                            };

                            for string_info in strings {
                                let selected = self.selected_string.as_ref().map_or(false, |s| {
                                    s.address == string_info.address
                                });
                                if ui
                                    .selectable_label(selected, format!("💡 {}", string_info.value))
                                    .clicked()
                                {
                                    self.selected_string = Some(string_info.clone());
                                    self.selected_section = None;
                                    self.selected_symbol = None;
                                    self.selected_tab = Tab::StringDetails;
                                }
                            }
                        });
                    });
                } else {
                    ui.centered_and_justified(|ui| {
                        ui.label("No file loaded.");
                    });
                }
            });
    }

    /// Draws the central panel displaying analysis results
    fn central_panel(&mut self, ctx: &Context) {
        egui::CentralPanel::default().show(ctx, |ui| {
            if self.analysis_result.is_empty() {
                ui.vertical_centered(|ui| {
                    ui.add_space(100.0);
                    ui.label(
                        RichText::new("🦀 Rust Binary Analyzer")
                            .heading()
                            .size(32.0)
                            .color(Color32::LIGHT_BLUE),
                    );
                    ui.add_space(20.0);
                    ui.label(
                        RichText::new(
                            "Drag and drop a binary file here or use 📁 File > 📂 Open to start.",
                        )
                        .italics(),
                    );
                });
            } else {
                egui::TopBottomPanel::top("info_panel").show_inside(ui, |ui| {
                    ui.horizontal_wrapped(|ui| {
                        ui.label("Format:");
                        ui.monospace(format!("{:?}", self.analysis_result.format));
                        ui.separator();
                        ui.label("Arch:");
                        ui.monospace(format!("{:?}", self.analysis_result.architecture));
                        ui.separator();
                        ui.label("Endianness:");
                        ui.monospace(format!("{:?}", self.analysis_result.endianness));
                        ui.separator();
                        ui.label("File Size:");
                        ui.monospace(format!(
                            "{:.2} KB",
                            self.analysis_result.file_size as f64 / 1024.0
                        ));
                    });
                });

                ui.add_space(5.0);

                // Tab bar for different views
                egui::TopBottomPanel::top("tab_panel").show_inside(ui, |ui| {
                    ui.horizontal(|ui| {
                        ui.selectable_value(&mut self.selected_tab, Tab::SectionDetails, "Section Details");
                        ui.selectable_value(&mut self.selected_tab, Tab::SymbolDetails, "Symbol Details");
                        ui.selectable_value(&mut self.selected_tab, Tab::StringDetails, "String Details");
                        ui.selectable_value(&mut self.selected_tab, Tab::Disassembly, "Disassembly");
                    });
                });
                ui.separator();
                ui.add_space(5.0);

                // Display content based on selected tab
                match self.selected_tab {
                    Tab::SectionDetails => self.display_section_details(ui),
                    Tab::SymbolDetails => self.display_symbol_details(ui),
                    Tab::StringDetails => self.display_string_details(ui),
                    Tab::Disassembly => self.display_disassembly(ui),
                }
            }
        });
    }

    /// Displays the status bar at the bottom
    fn status_bar(&self, ctx: &Context) {
        TopBottomPanel::bottom("status_bar").show(ctx, |ui| {
            ui.add_space(4.0);
            ui.horizontal(|ui| {
                if !self.binary_path.is_empty() {
                    ui.label(format!("📄 File: {}", self.binary_path));
                }
                ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                    ui.label("Ready");
                });
            });
            ui.add_space(4.0);
        });
    }

    /// Displays section details in the central panel
    fn display_section_details(&mut self, ui: &mut egui::Ui) {
        if let Some(section) = &self.selected_section {
            ui.heading(format!("📄 Section: {}", section.name));
            ui.separator();
            ui.monospace(format!("Address: 0x{:X}", section.address));
            ui.monospace(format!("Size: {}", section.size));
            ui.monospace(format!("Flags: {:?}", section.flags));
            ui.monospace(format!("Type: {:?}", section.kind));
            ui.monospace(format!("Relocation Entries: {}", section.relocations.len()));
            ui.add_space(10.0);

            if !section.data.is_empty() {
                ui.collapsing("🔎 Hex View", |ui| {
                    ScrollArea::both().show(ui, |ui| {
                        self.display_hex_view(ui, &section.data);
                    });
                });
            }
        } else {
            ui.centered_and_justified(|ui| {
                ui.label("Select a section from the left panel to view details.");
            });
        }
    }

    /// Displays symbol details in the central panel
    fn display_symbol_details(&mut self, ui: &mut egui::Ui) {
        if let Some(symbol) = &self.selected_symbol {
            ui.heading(format!("🔖 Symbol: {}", symbol.demangled_name));
            ui.separator();
            ui.monospace(format!("Name: {}", symbol.name));
            ui.monospace(format!("Address: 0x{:X}", symbol.address));
            ui.monospace(format!("Size: {}", symbol.size));
            ui.monospace(format!("Kind: {:?}", symbol.kind));
            ui.monospace(format!("Scope: {:?}", symbol.scope));
            ui.monospace(format!("Section: {:?}", symbol.section));
            ui.monospace(format!("Import: {}", symbol.is_import));
            ui.monospace(format!("Export: {}", symbol.is_export));
            ui.add_space(10.0);
        } else {
            ui.centered_and_justified(|ui| {
                ui.label("Select a symbol from the left panel to view details.");
            });
        }
    }

    /// Displays string details in the central panel
    fn display_string_details(&mut self, ui: &mut egui::Ui) {
        if let Some(string_info) = &self.selected_string {
            ui.heading("💬 String Details");
            ui.separator();
            ui.monospace(format!("Address: 0x{:X}", string_info.address));
            ui.monospace(format!("Value: {}", string_info.value));
            ui.add_space(10.0);
        } else {
            ui.centered_and_justified(|ui| {
                ui.label("Select a string from the left panel to view details.");
            });
        }
    }

    /// Displays disassembly of code sections
    fn display_disassembly(&mut self, ui: &mut egui::Ui) {
        if let Some(section) = &self.selected_section {
            if section.is_executable {
                ui.heading(format!("🧩 Disassembly of {}", section.name));
                ui.separator();
                if let Some(disassembly) = self.disassembly_cache.get(&section.address) {
                    ScrollArea::vertical().show(ui, |ui| {
                        self.display_syntax_highlighted_disassembly(ui, disassembly);
                    });
                } else {
                    ui.label("Disassembling...");
                    if let Ok(disassembly) = self.perform_disassembly(section) {
                        self.disassembly_cache
                            .insert(section.address, disassembly.clone());
                        ScrollArea::vertical().show(ui, |ui| {
                            self.display_syntax_highlighted_disassembly(ui, &disassembly);
                        });
                    } else {
                        ui.label("Failed to disassemble section.");
                    }
                }
            } else {
                ui.label("Selected section is not executable.");
            }
        } else if let Some(symbol) = &self.selected_symbol {
            ui.heading(format!("🧩 Disassembly of {}", symbol.demangled_name));
            ui.separator();
            if let Some(disassembly) = self.disassembly_cache.get(&symbol.address) {
                ScrollArea::vertical().show(ui, |ui| {
                    self.display_syntax_highlighted_disassembly(ui, disassembly);
                });
            } else {
                ui.label("Disassembling...");
                if let Ok(disassembly) = self.perform_disassembly_symbol(symbol) {
                    self.disassembly_cache
                        .insert(symbol.address, disassembly.clone());
                    ScrollArea::vertical().show(ui, |ui| {
                        self.display_syntax_highlighted_disassembly(ui, &disassembly);
                    });
                } else {
                    ui.label("Failed to disassemble symbol.");
                }
            }
        } else {
            ui.centered_and_justified(|ui| {
                ui.label("Select an executable section or symbol to disassemble.");
            });
        }
    }

    /// Performs the binary analysis
    fn perform_analysis(&mut self) {
        match analyze_binary(&self.binary_path) {
            Ok(result) => {
                self.analysis_result = result;
                self.error_message = None;
                self.selected_section = None;
                self.selected_symbol = None;
                self.selected_string = None;
                self.disassembly_cache.clear();
            }
            Err(e) => {
                self.analysis_result = AnalysisResult::default();
                self.error_message = Some(e);
                self.selected_section = None;
                self.selected_symbol = None;
                self.selected_string = None;
                self.disassembly_cache.clear();
            }
        }
    }

    /// Opens the file dialog to select a binary file
    fn open_file_dialog(&mut self) {
        if let Some(path) = FileDialog::new().pick_file() {
            self.binary_path = path.display().to_string();
            self.perform_analysis();
            self.recent_files.push(self.binary_path.clone());
        }
    }

    /// Displays the hex view of the data
    fn display_hex_view(&self, ui: &mut egui::Ui, data: &[u8]) {
        let bytes_per_row = 16;
        let mut offset = 0;
        ui.separator();
        while offset < data.len() {
            let end = usize::min(offset + bytes_per_row, data.len());
            let row = &data[offset..end];

            let hex_row: String = row.iter().map(|b| format!("{:02X} ", b)).collect();
            let ascii_row: String = row
                .iter()
                .map(|b| {
                    if b.is_ascii_graphic() || b.is_ascii_whitespace() {
                        *b as char
                    } else {
                        '.'
                    }
                })
                .collect();

            ui.horizontal_wrapped(|ui| {
                ui.monospace(format!("{:08X}: ", offset));
                ui.add_space(4.0);
                ui.monospace(&hex_row);
                if end - offset < bytes_per_row {
                    let missing = bytes_per_row - (end - offset);
                    ui.add_space(3.0 * missing as f32 * ui.ctx().fonts(|f| f.pixels_per_point())); // ui.ctx().fonts() requires a closure
                }
                ui.add_space(10.0);
                ui.monospace(&ascii_row);
            });

            offset += bytes_per_row;
        }
    }

    /// Performs disassembly on the given section
    fn perform_disassembly(&self, section: &SectionInfo) -> Result<String, String> {
        let cs = Capstone::new()
            .x86()
            .mode(self.analysis_result.capstone_mode)
            .syntax(capstone::arch::x86::ArchSyntax::Intel)
            .detail(true)
            .build()
            .map_err(|e| format!("Capstone error: {}", e))?;

        let insns = cs
            .disasm_all(&section.data, section.address)
            .map_err(|e| format!("Disassembly error: {}", e))?;

        let mut disassembly = String::new();
        for i in insns.iter() {
            disassembly.push_str(&format!(
                "{:08X}  {:<8} {}\n",
                i.address(),
                i.mnemonic().unwrap_or(""),
                i.op_str().unwrap_or(""),
            ));
        }
        Ok(disassembly)
    }

    /// Performs disassembly on the given symbol
    fn perform_disassembly_symbol(&self, symbol: &SymbolInfo) -> Result<String, String> {
        let cs = Capstone::new()
            .x86()
            .mode(self.analysis_result.capstone_mode)
            .syntax(ArchSyntax::Intel)
            .detail(true)
            .build()
            .map_err(|e| format!("Capstone error: {}", e))?;

        // Find the section containing the symbol
        if let Some(section) = self
            .analysis_result
            .sections
            .iter()
            .find(|s| symbol.address >= s.address && symbol.address < s.address + s.size)
        {
            let start = (symbol.address - section.address) as usize;
            let end = start + symbol.size as usize;
            let data = &section.data[start..end];

            let insns = cs
                .disasm_all(data, symbol.address)
                .map_err(|e| format!("Disassembly error: {}", e))?;

            let mut disassembly = String::new();
            for i in insns.iter() {
                disassembly.push_str(&format!(
                    "{:08X}  {:<8} {}\n",
                    i.address(),
                    i.mnemonic().unwrap_or(""),
                    i.op_str().unwrap_or(""),
                ));
            }
            Ok(disassembly)
        } else {
            Err("Symbol not found in any section.".to_string())
        }
    }

    /// Display disassembly with basic syntax highlighting
    fn display_syntax_highlighted_disassembly(&self, ui: &mut egui::Ui, disassembly: &str) {
        for line in disassembly.lines() {
            if line.trim().is_empty() {
                continue;
            }
            let parts: Vec<&str> = line.splitn(3, ' ').collect();
            if parts.len() >= 3 {
                ui.horizontal(|ui| {
                    ui.monospace(parts[0]);
                    ui.add_space(8.0);
                    ui.colored_label(Color32::YELLOW, parts[1]);
                    ui.add_space(8.0);
                    ui.monospace(parts[2..].join(" "));
                });
            } else {
                ui.monospace(line);
            }
        }
    }

    /// Shows the About dialog
    fn show_about(&self, ctx: &Context) {
        egui::Window::new("About Rust Binary Analyzer")
            .anchor(Align2::CENTER_CENTER, [0.0, 0.0])
            .collapsible(false)
            .resizable(false)
            .show(ctx, |ui| {
                ui.vertical_centered(|ui| {
                    ui.heading("🦀 Rust Binary Analyzer");
                    ui.separator();
                    ui.label("Version 1.0.0");
                    ui.label("Developed with 💖 using Rust and egui");
                    ui.hyperlink_to(
                        "GitHub Repository",
                        "https://github.com/yourusername/rust-binary-analyzer",
                    );
                });
            });
    }

    /// Handles file drop events
    fn handle_file_drop(&mut self, ctx: &egui::Context) {
        if !ctx.input(|i| i.raw.dropped_files.is_empty()) {
            for file in &ctx.input(|i| i.raw.dropped_files.clone()) { // Clone the Vec<DroppedFile>
                if let Some(path) = file.path.clone() { // Clone the PathBuf
                    self.binary_path = path.display().to_string();
                    self.perform_analysis();
                    // Only process the first file
                    break;
                }
            }
        }
    }
}

/// Represents the different tabs in the central panel
#[derive(PartialEq, Eq, Clone, Copy)]
enum Tab {
    SectionDetails,
    SymbolDetails,
    StringDetails,
    Disassembly,
}

struct AnalysisResult {
    format: object::BinaryFormat,
    architecture: object::Architecture,
    endianness: object::Endianness,
    capstone_mode: capstone::arch::x86::ArchMode,
    file_size: u64,
    sections: Vec<SectionInfo>,
    symbols: Vec<SymbolInfo>,
    strings: Vec<StringInfo>,
}

impl Default for AnalysisResult {
    fn default() -> Self {
        AnalysisResult {
            format: object::BinaryFormat::Elf,
            architecture: object::Architecture::Unknown,
            endianness: object::Endianness::Little,
            capstone_mode: capstone::arch::x86::ArchMode::Mode64.into(),
            file_size: 0,
            sections: Vec::new(),
            symbols: Vec::new(),
            strings: Vec::new(),
        }
    }
}

impl AnalysisResult {
    fn is_empty(&self) -> bool {
        self.sections.is_empty() && self.symbols.is_empty() && self.strings.is_empty()
    }
}

#[derive(Clone)]
struct SectionInfo {
    name: String,
    address: u64,
    size: u64,
    data: Vec<u8>,
    flags: object::SectionFlags,
    kind: SectionKind,
    relocations: Arc<Vec<object::Relocation>>,
    is_executable: bool,
}

#[derive(Clone)]
struct StringInfo {
    address: u64,
    value: String,
}

fn analyze_binary(path: &str) -> Result<AnalysisResult, String> {
    let mut file = File::open(path).map_err(|e| format!("Failed to open file: {}", e))?;
    let metadata = file
        .metadata()
        .map_err(|e| format!("Failed to get file metadata: {}", e))?;
    let file_size = metadata.len();

    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer)
        .map_err(|e| format!("Failed to read file: {}", e))?;

    let obj_file =
        object::File::parse(&*buffer).map_err(|e| format!("Failed to parse binary: {}", e))?;

    let mut sections = Vec::new();
    for section in obj_file.sections() {
        let data = section
            .uncompressed_data()
            .unwrap_or(Cow::Borrowed(&[]))
            .to_vec();
        let is_executable = section.kind() == SectionKind::Text;
        let section_info = SectionInfo {
            name: section.name().unwrap_or("Unknown").to_string(),
            address: section.address(),
            size: section.size(),
            data,
            flags: section.flags(),
            kind: section.kind(),
            relocations: Arc::new(section.relocations().map(|(_, reloc)| reloc).collect()),
            is_executable,
        };
        sections.push(section_info);
    }

    // Use the extract_symbols function from symbol.rs
    let symbols = extract_symbols(&obj_file);

    // Extract strings from the collected sections
    let strings = extract_strings(&sections);

    // Determine Capstone architecture and mode based on object file architecture
    let capstone_mode = get_capstone_mode(&obj_file);

    Ok(AnalysisResult {
        format: obj_file.format(),
        architecture: obj_file.architecture(),
        endianness: obj_file.endianness(),
        capstone_mode,
        file_size,
        sections,
        symbols,
        strings,
    })
}

/// Maps object architecture to Capstone mode
fn get_capstone_mode(obj_file: &object::File) -> capstone::arch::x86::ArchMode {
    match obj_file.architecture() {
        object::Architecture::X86_64 => capstone::arch::x86::ArchMode::Mode64.into(),
        object::Architecture::I386 => capstone::arch::x86::ArchMode::Mode32.into(),
        _ => capstone::arch::x86::ArchMode::Mode64.into(),
    }
}

/// Extract printable ASCII strings from the sections likely to contain strings
fn extract_strings(sections: &[SectionInfo]) -> Vec<StringInfo> {
    let mut strings = Vec::new();

    for section in sections {
        // Check if the section is likely to contain strings
        if !section.name.contains(".rodata")
            && !section.name.contains(".data")
            && !section.name.contains(".rdata")
            && !section.name.contains(".text")
        {
            continue;
        }

        let data = &section.data;
        let mut i = 0;
        while i < data.len() {
            // Skip non-printable characters
            while i < data.len()
                && !(data[i].is_ascii_graphic() || data[i].is_ascii_whitespace())
            {
                i += 1;
            }
            let start = i;
            // Collect printable ASCII characters
            while i < data.len()
                && (data[i].is_ascii_graphic() || data[i].is_ascii_whitespace())
            {
                i += 1;
            }
            let end = i;
            // If the collected string is long enough, add it to the list
            if end - start >= 4 {
                if let Ok(s) = String::from_utf8(data[start..end].to_vec()) {
                    strings.push(StringInfo {
                        address: section.address + start as u64,
                        value: s,
                    });
                }
            }
        }
    }

    strings
}