The following Rust struct's "new" function has many problems. It's too convoluted, there is a lot of repeated logic, it's inefficient, and it's hard to understand. Please rewrite this code to solve those problems (without losing the core functionality already present):

pub struct ImageScheduler<'a> {
    primary_images: Vec<ImageState>,
    overlay_images: Vec<ImageState>,
    rng: ThreadRng,
    config: &'a Config,
    global_effects: Vec<ImageState>,
    transitions: Vec<Transition>,
    overlay_schedule: Vec<usize>,
}

impl<'a> ImageScheduler<'a> {
    pub fn new(
        images: &'a [Media],
        config: &'a crate::config::Config,
        effect_factory: &mut effects::EffectFactory,
    ) -> Self {
        let mut rng = rand::thread_rng();
        let mut scheduled_images = Vec::new();
        let mut overlay_images = Vec::new();

        // Randomly schedule primary images
        for _ in 0..(config.total_frames / 5) {
            // Randomly select an image
            let media = images.choose(&mut rng).unwrap();

            // Random start frame
            let start_frame = rng.gen_range(0..config.total_frames) as u32;
            // Maximum duration in frames (2 seconds at 30 fps)
            let max_duration = (config.framerate * 2).min(config.total_frames as u32 - start_frame) as usize; // Up to 2 seconds
            // Generate duration favoring shorter durations
            let duration = Self::generate_weighted_duration(&mut rng, max_duration);

            // Process media into frames and durations
            let mut video_start_time = None;
            let frames: ImageFrames = match media {
                Media::Static(img) => {
                    ImageFrames::Static(img.clone())
                },
                Media::Animated { path, total_duration_ms, frame_count } => {
                    // For simplicity, we'll loop the GIF if needed to cover the duration
                    ImageFrames::Animated {
                        path: path.clone(),
                        total_duration_ms: *total_duration_ms,
                        frame_count: *frame_count,
                    }
                },
                Media::Video { path, total_duration_ms, frame_rate, width, height } => 
                {
                    let max_start_time_ms = *total_duration_ms as i64
                        - (duration as i64 * 1000 / config.framerate as i64);
                    let video_start_time_ms = if max_start_time_ms > 0 {
                        rng.gen_range(0..=max_start_time_ms as u64)
                    } else {
                        0
                    };
                    video_start_time = Some(video_start_time_ms);
                    ImageFrames::Video { path, total_duration_ms, frame_rate, width, height }
                }
            };
            let any_frame = frames.get_first_frame().unwrap_or_else(|| {
                // In case of error, use a placeholder image
                RgbaImage::new(1, 1)
            });

            // Calculate scale
            let scale: f32;
            let frames = match media {
                Media::Static(img) => {
                    scale = Self::calculate_scale(&any_frame, config, &mut rng);

                    // Apply scaling
                    let img = image::imageops::resize(
                        img,
                        (img.width() as f32 * scale) as u32,
                        (img.height() as f32 * scale) as u32,
                        image::imageops::FilterType::Lanczos3,
                    );

                    ImageFrames::Static(img)
                },
                Media::Animated { path, total_duration_ms, frame_count } => {
                    // For simplicity, we'll loop the GIF if needed to cover the duration
                    scale = Self::calculate_scale(&any_frame, config, &mut rng);

                    ImageFrames::Animated {
                        path: path.clone(),
                        total_duration_ms: *total_duration_ms,
                        frame_count: *frame_count,
                    }
                },
                Media::Video { path, total_duration_ms, frame_rate, width, height } => 
                {
                    // TODO: Handle this somehow
                    ImageFrames::Video { path, total_duration_ms, frame_rate, width, height }
                },
            };

            // Random position
            let max_x = config.width.saturating_sub(any_frame.width() as usize) as i64;
            let max_y = config.height.saturating_sub(any_frame.height() as usize) as i64;
            let x = if max_x > 0 {
                rng.gen_range(0..=max_x)
            } else {
                0
            };
            let y = if max_y > 0 {
                rng.gen_range(0..=max_y)
            } else {
                0
            };

            // Random effects
            let random_effects = effect_factory.generate_random_effects();

            // Create the image state
            let image_state = ImageState {
                frames,
                position: (x, y),
                scale,
                start_frame: start_frame as usize,
                end_frame: start_frame as usize + duration,
                effects: random_effects,
                video_start_time_ms: video_start_time,
            };

            scheduled_images.push(image_state);
        }

        // Generate a schedule for overlay images
        let overlay_schedule = Self::generate_overlay_schedule(config.total_frames, &mut rng);

        // Schedule overlay images
        for frame_number in &overlay_schedule {
            // Randomly select an image
            let media = images.choose(&mut rng).unwrap();

            // Short durations for overlay images
            let max_duration = 10.min(config.total_frames - frame_number) as usize;
            let duration = Self::generate_short_duration(&mut rng, max_duration);
            let end_frame = frame_number + duration;

            // Process media into frames and durations
            let mut video_start_time = None;
            let frames: ImageFrames = match media {
                Media::Static(img) => {
                    ImageFrames::Static(img.clone())
                },
                Media::Animated { path, total_duration_ms, frame_count } => {
                    ImageFrames::Animated {
                        path: path.clone(),
                        total_duration_ms: *total_duration_ms,
                        frame_count: *frame_count,
                    }
                },
                Media::Video { path, total_duration_ms, frame_rate, width, height } => 
                {
                    let max_start_time_ms = *total_duration_ms as i64
                        - (duration as i64 * 1000 / config.framerate as i64);
                    let video_start_time_ms = if max_start_time_ms > 0 {
                        rng.gen_range(0..=max_start_time_ms as u64)
                    } else {
                        0
                    };
                    video_start_time = Some(video_start_time_ms);
                    ImageFrames::Video { path, total_duration_ms, frame_rate, width, height }
                }
            };

            let any_frame = frames.get_first_frame().unwrap_or_else(|| {
                // In case of error, use a placeholder image
                RgbaImage::new(1, 1)
            });

            // Small scaling factor
            let scale = rng.gen_range(0.05..=0.2); // Images scaled down to 5% - 20% of original size

            // Random position
            let max_x = config.width.saturating_sub(any_frame.width() as usize) as i64;
            let max_y = config.height.saturating_sub(any_frame.height() as usize) as i64;
            let x = if max_x > 0 {
                rng.gen_range(0..=max_x)
            } else {
                0
            };
            let y = if max_y > 0 {
                rng.gen_range(0..=max_y)
            } else {
                0
            };

            // Random effects
            let random_effects = effect_factory.generate_overlay_effects();

            // Create the image state
            let image_state = ImageState {
                frames,
                position: (x, y),
                scale,
                start_frame: *frame_number,
                end_frame,
                effects: random_effects,
                video_start_time_ms: video_start_time,
            };

            overlay_images.push(image_state);
        }
        
        // Schedule larger, slower overlay images
        for _ in 0..(config.total_frames / 100) { // Adjust the count as needed
            // Randomly select an image
            let media = images.choose(&mut rng).unwrap();

            // Random start frame
            let start_frame = rng.gen_range(0..config.total_frames) as usize;

            let min_duration = config.framerate * 2;
            let max_possible_duration = config.total_frames - start_frame;

            // Longer duration
            let max_duration = (config.framerate * 5).min(max_possible_duration as u32);
            let duration = if max_duration >= min_duration {
                rng.gen_range(min_duration..=max_duration)
            } else if max_duration > 0 {
                // If max_duration is less than min_duration but greater than zero
                rng.gen_range(1..=max_duration)
            } else {
                // If there's no room for duration, skip this iteration
                continue;
            };
            let end_frame = start_frame + duration as usize;

            // Process media into frames and durations
            let mut video_start_time = None;
            let frames: ImageFrames = match media {
                Media::Static(img) => {
                    ImageFrames::Static(img.clone())
                },
                Media::Animated { path, total_duration_ms, frame_count } => {
                    ImageFrames::Animated {
                        path: path.clone(),
                        total_duration_ms: *total_duration_ms,
                        frame_count: *frame_count,
                    }
                },
                Media::Video { path, total_duration_ms, frame_rate, width, height } => 
                {
                    let max_start_time_ms = *total_duration_ms as i64
                        - (duration as i64 * 1000 / config.framerate as i64);
                    let video_start_time_ms = if max_start_time_ms > 0 {
                        rng.gen_range(0..=max_start_time_ms as u64)
                    } else {
                        0
                    };
                    video_start_time = Some(video_start_time_ms);
                    ImageFrames::Video { path, total_duration_ms, frame_rate, width, height }
                }
            };
            let any_frame = frames.get_first_frame().unwrap_or_else(|| {
                // In case of error, use a placeholder image
                RgbaImage::new(1, 1)
            });

            // Larger scaling factor
            let scale = rng.gen_range(0.5..=1.5); // Images scaled between 50% and 150% of original size

            // Random position
            let max_x = config.width.saturating_sub(any_frame.width() as usize) as i64;
            let max_y = config.height.saturating_sub(any_frame.height() as usize) as i64;
            let x = if max_x > 0 {
                rng.gen_range(0..=max_x)
            } else {
                0
            };
            let y = if max_y > 0 {
                rng.gen_range(0..=max_y)
            } else {
                0
            };

            // Apply low opacity with occasional flashes
            let effects = vec![Effect::LowOpacityFlash {
                flash_duration: rng.gen_range(1..=3), // Flash lasts 1 to 3 frames
                flash_interval: rng.gen_range(30..=100), // Flash every 30 to 100 frames
            }];

            // Create the image state
            let image_state = ImageState {
                frames,
                position: (x, y),
                scale,
                start_frame,
                end_frame,
                effects,
                video_start_time_ms: video_start_time,
            };

            overlay_images.push(image_state);
        }

        // Generate global effects
        let mut global_effects = Vec::new();
        for _ in 0..(config.total_frames / 50) { // Adjust the frequency as needed
            // Random start frame
            let start_frame = rng.gen_range(0..config.total_frames);

            // Maximum duration in frames
            let max_duration = ((config.framerate as f32 * 2.5)
                .min(config.total_frames as f32 - start_frame as f32)) as usize;
            let duration = Self::generate_weighted_duration(&mut rng, max_duration);
            let end_frame = start_frame + duration;

            // Generate global effects
            let effects = effect_factory.generate_random_global_effects();

            // Create a dummy ImageState for global effects
            let image_state = ImageState {
                frames: ImageFrames::Static(image::RgbaImage::new(config.width as u32, config.height as u32)),
                position: (0, 0),
                scale: 1.0,
                start_frame,
                end_frame,
                effects,
                video_start_time_ms: 0,
            };

            global_effects.push(image_state);
        }

        // Sort images by start frame
        // TODO: Is this line a hallucination?
        scheduled_images.sort_by_key(|state| state.start_frame);

        let mut scheduler = Self {
            primary_images: scheduled_images,
            overlay_images,
            transitions: Vec::new(),
            rng,
            config,
            global_effects,
            overlay_schedule,
        };

        // Schedule transitions between images
        scheduler.schedule_transitions();

        scheduler
    }
}