        ReplaySaveParam(mb_to_utf16(rep_name, 932).c_str(), thPracParam.GetJson());
    }

    static float MInterpolation(float t, float a, float b)
    {
        if (t < 0.0f) {
            return a;
        } else if (t < 0.5) {
            float k = (b - a) * 2.0f;
            return k * t * t + a;
        } else if (t < 1.0f) {
            float k = (b - a) * 2.0f;
            t = t - 1.0f;
            return -k * t * t + b;
        }
        return b;
    }
    static void RenderRepMarker(ImDrawList* p)
    {
        if (g_adv_igi_options.th06_showRepMarker) {
            DWORD is_rep = *(DWORD*)(0x69BCBC);
            DWORD gameState = *(DWORD*)(0x6C6EA4);
            if (is_rep && gameState == 2) {
                auto f = ImGui::GetFont();
                auto sz = f->CalcTextSizeA(20, 100, 100, "ＲＥＰ");
                ImVec2 p1 = { 416.0f, 464.0f };
                p->AddRectFilled({ p1.x - sz.x, p1.y - sz.y }, p1, 0x77000000);
                p->AddText(f, 20, { p1.x - sz.x, p1.y - sz.y }, 0xFFFFFFFF, "ＲＥＰ");
            }
        }
    }
    static void RenderPlHitbox(ImDrawList* p)
    {
        { // player hitbox
            static float t = 0.0f;
            static bool is_shift_pressed = false;
            if (g_adv_igi_options.th06_show_hitbox && g_hitbox_textureID != NULL) {
                bool is_time_stopped = *(BYTE*)(0x69BCCC);
                DWORD gameState = *(DWORD*)(0x6C6EA4);
                BYTE pauseMenuState = *(BYTE*)(0x69D4BF);
                WORD keyState = *(WORD*)(0x69D904);
                if (!is_time_stopped)
                    is_shift_pressed = keyState & 0x4;
                if (gameState == 2 && is_shift_pressed) {
                    if (pauseMenuState == 0) {
                        if (!is_time_stopped)
                            t += 1.0f;
                        float scale = MInterpolation(t / 18.0f, 1.5f, 1.0f),
                              scale2 = MInterpolation(t / 12.0f, 0.3f, 1.0f),
                              angle = 3.14159f,
                              angle2 = 0.0f,
                              alpha = t < 6.0f ? t / 6.0f : 1.0f;
                        if (t < 18.0f) {
                            angle = MInterpolation(t / 18.0f, 3.14159f, -3.14159f);
                            angle2 = -angle;
                        } else {
                            angle = -3.14159f + t * 0.05235988f;
                            angle2 = 3.14159f - t * 0.05235988f;
                        }
                        scale *= 0.75f;
                        scale2 *= 0.75f; // 32->24
                        p->PushClipRect({ 32.0f, 16.0f }, { 416.0f, 464.0f });
                        ImVec2 p1 = { *(float*)(0x6CAA68) + 32.0f, *(float*)(0x6CAA6C) + 16.0f };
                        float c, s;
                        c = cosf(angle) * scale * g_hitbox_sz.x, s = sinf(angle) * scale * g_hitbox_sz.y;
                        p->AddImageQuad(g_hitbox_textureID, { p1.x + c, p1.y + s }, { p1.x - s, p1.y + c }, { p1.x - c, p1.y - s }, { p1.x + s, p1.y - c }, { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 }, ImGui::ColorConvertFloat4ToU32({ 1, 1, 1, alpha }));
                        c = cosf(angle2) * scale2 * g_hitbox_sz.x, s = sinf(angle2) * scale2 * g_hitbox_sz.y;
                        p->AddImageQuad(g_hitbox_textureID, { p1.x + c, p1.y + s }, { p1.x - s, p1.y + c }, { p1.x - c, p1.y - s }, { p1.x + s, p1.y - c });
                        p->PopClipRect();
                    }
                } else {
                    t = 0.0f;
                }
            }
        }
    }
    static void RenderBtHitbox(ImDrawList* p)
    {
        // show bullet hitbox
        if (g_show_bullet_hitbox) {
            DWORD is_practice = *(DWORD*)(0x69d4c3);
            DWORD gameState = *(DWORD*)(0x6C6EA4);
            DWORD is_rep = *(DWORD*)(0x69BCBC);
            if (((is_practice) || (is_rep) || (thPracParam.mode)) && gameState == 2) {
                p->PushClipRect({ 32.0f, 16.0f }, { 416.0f, 464.0f });
                ImVec2 stage_pos = { 32.0f, 16.0f };
                ImVec2 plpos1 = *(ImVec2*)(0x6CAA80);
                ImVec2 plpos2 = *(ImVec2*)(0x6CAA8C);
                float plhit = plpos2.x - plpos1.x;

                // bullet hitbox
                for (int i = 0; i < 640; i++) {
                    DWORD pbt = 0x005AB5F8 + i * 0x5C4;
                    if ((*(WORD*)(pbt + 0x5BE) != 1) || (*(WORD*)(pbt + 0x5BE) == 0)) {
                        continue;
                    }
                    ImVec2 pos = *(ImVec2*)(pbt + 0x560);
                    ImVec2 hit = *(ImVec2*)(pbt + 0x550);

                    ImVec2 p1 = { pos.x - hit.x * 0.5f - plhit * 0.5f + stage_pos.x, pos.y - hit.y * 0.5f - plhit * 0.5f + stage_pos.y };
                    ImVec2 p2 = { pos.x + hit.x * 0.5f + plhit * 0.5f + stage_pos.x, pos.y + hit.y * 0.5f + plhit * 0.5f + stage_pos.y };
                    p->AddRectFilled(p1, p2, 0x88002288);
                    p->AddRect(p1, p2, 0xFFFFFFFF, 0.0f);
                }

                // laser hitbox
                for (int i = 0; i < 64; i++) {
                    DWORD pls = 0x00691FF8 + 0x270 * i;
                    DWORD is_used = *(DWORD*)(pls + 0x258);
                    if (is_used) {
                        ImVec2 pos = *(ImVec2*)(pls + 0x220);
                        float angle = *(float*)(pls + 0x22C);
                        float quat_width = *(float*)(pls + 0x23C) * 0.5f * 0.5f;
                        float half_width_pl = plhit * 0.5f;
                        float start_ofs = *(float*)(pls + 0x230);
                        float end_ofs = *(float*)(pls + 0x234);
                        int state = *(DWORD*)(pls + 0x26C);

                        int start_time_graze = *(DWORD*)(pls + 0x248);
                        int end_time_graze = *(DWORD*)(pls + 0x254);
                        int time_cur_state = *(DWORD*)(pls + 0x264);
                        float sub_frame = *(float*)(pls + 0x260);
                        if (state == 0) {
                            int state_change_time_hit = *(DWORD*)(pls + 0x244);
                            float l2 = 0.0f;
                            if (time_cur_state <= state_change_time_hit - std::max(30, state_change_time_hit)) {
                                l2 = 1.2f * 0.5f;
                            } else {
                                l2 = quat_width * ((float)time_cur_state + sub_frame) / (float)state_change_time_hit;
                            }
                            float mid = (start_ofs + end_ofs) * 0.5f;
                            start_ofs = mid - l2;
                            end_ofs = mid + l2;
                        }
                        if (state == 2) {
                            int state_change_time_disappear = *(DWORD*)(pls + 0x250);
                            float l2 = 0.0f;
                            if (state_change_time_disappear > 0) {
                                l2 = quat_width - quat_width * ((float)time_cur_state + sub_frame) / (float)state_change_time_disappear;
                            }
                            float mid = (start_ofs + end_ofs) * 0.5f;
                            start_ofs = mid - l2;
                            end_ofs = mid + l2;
                        }
                        if (state == 1 || (state == 0 && time_cur_state >= start_time_graze) || (state == 2 && time_cur_state < end_time_graze)) {
                            float c = cosf(angle);
                            float s = sinf(angle);
                            ImVec2 hitpos[4] = {
                                { start_ofs - half_width_pl, -quat_width - half_width_pl },
                                { end_ofs + half_width_pl, -quat_width - half_width_pl },
                                { end_ofs + half_width_pl, quat_width + half_width_pl },
                                { start_ofs - half_width_pl, quat_width + half_width_pl }
                            };
                            auto RotPos = [](ImVec2 p, float c, float s) -> ImVec2 {
                                return { p.x * c - p.y * s, p.x * s + p.y * c };
                            };
                            for (int j = 0; j < 4; j++) {
                                hitpos[j] = RotPos(hitpos[j], c, s);
                                hitpos[j].x += pos.x + stage_pos.x;
                                hitpos[j].y += pos.y + stage_pos.y;
                            }
                            p->AddQuad(hitpos[0], hitpos[1], hitpos[2], hitpos[3], 0xFFFF0000);
                            p->AddQuadFilled(hitpos[0], hitpos[1], hitpos[2], hitpos[3], 0x88882200);
                        }
                    }
                }

                // enemy hitbox
                for (int i = 0; i < 0x100; i++) {
                    DWORD penm = 0x4B79C8 + 0xED0 + i * 0xEC8;
                    if (*(char*)(0xE50 + penm) < 0) {
                        if ((*(BYTE*)(penm + 0xE51) & 4) != 0 && (*(BYTE*)(penm + 0xE51) & 2) != 0 && (*(BYTE*)(penm + 0xE51) & 1) != 0) {
                            ImVec2 pos = *(ImVec2*)(penm + 0xC6C);
                            ImVec2 hit = *(ImVec2*)(penm + 0xC78);
                            hit.x *= 0.666666f;
                            hit.y *= 0.666666f;
                            ImVec2 p1 = { pos.x - hit.x * 0.5f - plhit * 0.5f + stage_pos.x, pos.y - hit.y * 0.5f - plhit * 0.5f + stage_pos.y };
                            ImVec2 p2 = { pos.x + hit.x * 0.5f + plhit * 0.5f + stage_pos.x, pos.y + hit.y * 0.5f + plhit * 0.5f + stage_pos.y };
                            p->AddRectFilled(p1, p2, 0xAAFF5500);
                            p->AddRect(p1, p2, 0xFFFFFFFF);
                        }
                    }
                }
                 p->PopClipRect();
            }
        }
    }
    static void RenderLockTimer(ImDrawList* p)
    {
        if (g_adv_igi_options.enable_lock_timer_autoly && *THOverlay::singleton().mTimeLock) {
            std::string time_text = std::format("{:.2f}", (float)g_lock_timer / 60.0f);
            auto sz = ImGui::CalcTextSize(time_text.c_str());
            p->AddRectFilled({ 32.0f, 0.0f }, { 110.0f, sz.y }, 0xFFFFFFFF);
            p->AddText({ 110.0f - sz.x, 0.0f }, 0xFF000000, time_text.c_str());
        }
    }

    EHOOK_ST(th06_result_screen_create, 0x42d812, 4, {
        self->Disable();
        *(uint32_t*)(*(uint32_t*)(pCtx->Ebp - 0x10) + 0x8) = 0xA;
        pCtx->Eip = 0x42d839;
    });

    // It would be good practice to run Setup() on this
    // But due to the way this new hooking system works
    // running Setup is only needed for Hooks, not patches
    PATCH_ST(th06_white_screen, 0x42fee0, "c3");

    HOOKSET_DEFINE(THMainHook)
    PATCH_DY(th06_reacquire_input, 0x41dc58, "0000000074")
    EHOOK_DY(th06_activateapp, 0x420D96, 3, {
        // Wacky hack to disable rendering for one frame to prevent the game from crasing when alt tabbing into it if the pause menu is open and the game is in fullscreen mode
        GameGuiProgress = 1;
    })
    EHOOK_DY(th06_bgm_play, 0x424b5d, 1, {
        int32_t retn_addr = ((int32_t*)pCtx->Esp)[0];

        if (THPauseMenu::singleton().el_bgm_signal) {
            pCtx->Eip = 0x424d35;
        }
        if (retn_addr == 0x418db4) {
            THPauseMenu::singleton().el_bgm_changed = true;
        }
    })
    EHOOK_DY(th06_bgm_stop, 0x430f80, 1, {
        if (THPauseMenu::singleton().el_bgm_signal) {
            pCtx->Eip = 0x43107b;
        }
    })
    EHOOK_DY(th06_prac_menu_1, 0x437179, 7, {
        THGuiPrac::singleton().State(1);
    })
    EHOOK_DY(th06_prac_menu_3, 0x43738c, 3, {
        THGuiPrac::singleton().State(3);
    })
    EHOOK_DY(th06_prac_menu_4, 0x43723f, 3, {
        THGuiPrac::singleton().State(4);
    })
    EHOOK_DY(th06_prac_menu_enter, 0x4373a3, 5, {
        *(int32_t*)(0x69d6d4) = *(int32_t*)(0x69d6d8) = thPracParam.stage;
        if (thPracParam.stage == 6)
            *(int8_t*)(0x69bcb0) = 4;
        else
            *(int8_t*)(0x69bcb0) = *(int8_t*)(0x6c6e49);
    })
    EHOOK_DY(th06_pause_menu, 0x401b8f, 2, {
        if (thPracParam.mode && (*((int32_t*)0x69bcbc) == 0)) {
            auto sig = THPauseMenu::singleton().PMState();
            if (sig == THPauseMenu::SIGNAL_RESUME) {
                pCtx->Eip = 0x40223d;
            } else if (sig == THPauseMenu::SIGNAL_EXIT) {
                *(uint32_t*)0x6c6ea4 = 7; // Set gamemode to result screen
                *(uint16_t*)0x69d4bf = 0; // Close pause menu
                th06_result_screen_create.Enable();
            } else if (sig == THPauseMenu::SIGNAL_RESTART) {
                pCtx->Eip = 0x40263c;
            } else if (sig == THPauseMenu::SIGNAL_EXIT2) {
                *(uint32_t*)0x6c6ea4 = 1; 
                *(uint16_t*)0x69d4bf = 0;
                th06_result_screen_create.Enable();
            } else {
                pCtx->Eip = 0x4026a6;
            }
        }
        // escR patch
        DWORD thiz = pCtx->Ecx;
        if (!thPracParam.mode && (*((int32_t*)0x69bcbc) == 0))
        {
            if (*(DWORD*)(thiz) != 7) {
                WORD key = *(WORD*)(0x69D904);
                //WORD key_last = *(WORD*)(0x69D908);
                if (Gui::KeyboardInputGetRaw('R') || (key & 0x124) == 0x124) { // ctrl+shift+down or R
                    *(DWORD*)(thiz) = 7;
                    threstartflag_normalgame = true;
                }
            }
        }
        if (*(DWORD*)(thiz) == 7) {
            pCtx->Eip = 0x40263c;
        }
    })
    
    EHOOK_DY(th06_inf_lives,0x00428DEB,2,{
        if ((*(THOverlay::singleton().mInfLives)))
        {
            if (!g_adv_igi_options.map_inf_life_to_no_continue){
                pCtx->Eax += 1;
            }else{
                if ((pCtx->Eax & 0xFF) == 0)
                    pCtx->Eax += 1;
            }
        }  
    })

    EHOOK_DY(th06_pause_menu_pauseBGM, 0x402714,3,{
        if (g_adv_igi_options.th06_pauseBGM) {
            DWORD soundstruct = *(DWORD*)(0x6D457C);
            if (soundstruct)
            {
                int32_t n = *(int32_t*)(soundstruct + 0x10);
                IDirectSoundBuffer** soundbuffers = *(IDirectSoundBuffer***)(soundstruct + 0x4);
                if (*(BYTE*)(0x69D4BF) == 0 || (*(THOverlay::singleton().mElBgm) && thPracParam.mode)) // show menu==0
                {
                    for (int i = 0; i < n; i++) {
                        DWORD st = 0;
                        soundbuffers[i]->GetStatus(&st);
                        if (!(st & DSBSTATUS_PLAYING)) {
                            soundbuffers[i]->Play(0, 0, DSBPLAY_LOOPING);
                        }
                    }
                } else {
                    for (int i = 0; i < n; i++) {
                        DWORD st = 0;
                        soundbuffers[i]->GetStatus(&st);
                        if (st & DSBSTATUS_PLAYING) {
                            soundbuffers[i]->Stop();
                        }
                    }
                }
            }
        }
    })
    EHOOK_DY(th06_unpause_prevent_desyncs, 0x40223d, 6, {
        if (!GAME_MANAGER->isInReplay) {
            *(WORD*)(INPUT_ADDR) &= ~0x2; // clear bomb bit from input

            uint32_t GUI_impl = *(uint32_t*)(0x69bc30 + 0x4);
            if (*(int32_t*)(GUI_impl + 0x253c) >= 0) // in dialogue
                *(WORD*)(INPUT_ADDR) &= ~0x1; // clear shoot bit from input
        }
    })
    EHOOK_DY(th06_patch_main, 0x41c17a,5, {
        THPauseMenu::singleton().el_bgm_changed = false;
        if (thPracParam.mode == 1) {
            // TODO: Probably remove this ASM comment?
            /*
                    mov eax,dword ptr [@MENU_RANK]
                    mov dword ptr [69d710],eax
                    cmp dword ptr [@MENU_RANKLOCK],@MENU_ON_STR
                    jnz @f
                    mov dword ptr [69d714],eax
                    mov dword ptr [69d718],eax
                */
            *(int8_t*)(0x69d4ba) = (int8_t)thPracParam.life;
            *(int8_t*)(0x69d4bb) = (int8_t)thPracParam.bomb;
            *(int16_t*)(0x69d4b0) = (int16_t)thPracParam.power;
            *(int32_t*)(0x69bca0) = *(int32_t*)(0x69bca4) = (int32_t)thPracParam.score;
            *(int32_t*)(0x69bcb4) = *(int32_t*)(0x69bcb8) = (int32_t)thPracParam.graze;
            *(int16_t*)(0x69d4b4) = *(int16_t*)(0x69d4b6) = (int16_t)thPracParam.point;
            *(uint32_t*)0x5a5fb0 = thPracParam.frame;

            if (*(int8_t*)(0x69bcb0) != 4) {
                if (thPracParam.score >= 60000000)
                    *(int8_t*)(0x69d4bc) = 4;
                else if (thPracParam.score >= 40000000)
                    *(int8_t*)(0x69d4bc) = 3;
                else if (thPracParam.score >= 20000000)
                    *(int8_t*)(0x69d4bc) = 2;
                else if (thPracParam.score >= 10000000)
                    *(int8_t*)(0x69d4bc) = 1;
            }

            *(int32_t*)(0x69d710)  = (int32_t)thPracParam.rank;
            if (thPracParam.rankLock) {
                *(int32_t*)(0x69d714)  = (int32_t)thPracParam.rank;
                *(int32_t*)(0x69d718)  = (int32_t)thPracParam.rank;
            }

            THSectionPatch();
        }
        thPracParam._playLock = true;

        if (THPauseMenu::singleton().el_bgm_signal) {
            THPauseMenu::singleton().el_bgm_signal = false;
            pCtx->Eip = 0x41c18a;
        } else if (THBGMTest()) {
            pCtx->Eax += 0x310;
            pCtx->Eip = 0x41c17f;
        }
    })
    EHOOK_DY(th06_restart, 0x435901, 5, {
        if (!threstartflag_normalgame && !thRestartFlag) {
            th06_white_screen.Disable();
        }
        if (threstartflag_normalgame)
        {
            th06_white_screen.Enable();
            threstartflag_normalgame = false;
            pCtx->Eip = 0x436DCB;
        }
        if (thRestartFlag) {
            th06_white_screen.Enable();
            thRestartFlag = false;
            pCtx->Eip = 0x43738c;
        } else {
            thPracParam.Reset();
        }
    })
    EHOOK_DY(th06_title, 0x41ae2c, 7, {
        if (thPracParam.mode != 0 && thPracParam.section) {
            pCtx->Eip = 0x41af35;
        }
    })
    PATCH_DY(th06_preplay_1, 0x42d835, "09")
    EHOOK_DY(th06_preplay_2, 0x418ef9, 5, {
        if (thPracParam.mode && !THGuiRep::singleton().mRepStatus) {
            *(uint32_t*)0x69bca0 = *(uint32_t*)0x69bca4;
            pCtx->Eip = 0x418f0e;
        }
    })
    EHOOK_DY(th06_save_replay, 0x42b03b, 3, {
        char* rep_name = *(char**)(pCtx->Ebp + 0x8);
        if (thPracParam.mode)
            THSaveReplay(rep_name);
    })
    EHOOK_DY(th06_rep_menu_1, 0x438262, 6, {
        THGuiRep::singleton().State(1);
    })
    EHOOK_DY(th06_rep_menu_2, 0x4385d5, 6, {
        THGuiRep::singleton().State(2);
    })
    EHOOK_DY(th06_rep_menu_3, 0x438974, 10, {
        THGuiRep::singleton().State(3);
    })
    EHOOK_DY(th06_fake_shot_type, 0x40b2f9, 6, {
        if (thPracParam.fakeType) {
            *((int32_t*)0x487e44) = thPracParam.fakeType - 1;
            pCtx->Eip = 0x40b2ff;
        }
    })
    EHOOK_DY(th06_patchouli, 0x40c100, 1, {
        int32_t* var = *(int32_t**)(pCtx->Esp + 4);
        if (thPracParam.fakeType) {
            var[618] = ((int32_t*)0x476264)[3 * (thPracParam.fakeType - 1)];
            var[619] = ((int32_t*)0x476268)[3 * (thPracParam.fakeType - 1)];
            var[620] = ((int32_t*)0x47626c)[3 * (thPracParam.fakeType - 1)];
            pCtx->Eip = 0x40c174;
        }
    })
    EHOOK_DY(th06_cancel_muteki, 0x429ec4, 7, {
        if (thPracParam.mode) {
            *(uint8_t*)(pCtx->Eax + 0x9e0) = 0;
            pCtx->Eip = 0x429ecb;
        }
    })
    EHOOK_DY(th06_set_deathbomb_timer, 0x42a09c, 10, {
        if (thPracParam.mode) {
            *(uint32_t*)(pCtx->Eax + 0x9d8) = 6;
            pCtx->Eip = 0x42a0a6;
        }
    })
    EHOOK_DY(th06_hamon_rage, 0x40e1c7, 10, {
        if (thPracParam.mode && thPracParam.stage == 6 && thPracParam.section == TH06_ST7_END_S10 && thPracParam.phase == 1) {
            pCtx->Eip = 0x40e1d8;
        }
    })
    EHOOK_DY(th06_wall_prac_boss_pos, 0x40907F,3,{
        if (thPracParam.mode && thPracParam.stage == 5 && thPracParam.wall_prac_st6 && thPracParam.section == TH06_ST6_BOSS9) {
            DWORD penm = *(DWORD*)(pCtx->Ebp + 0x8);
            g_last_boss_x = *(float*)(penm + 0xC6C);
            g_last_boss_y = *(float*)(penm + 0xC70);
        }
    })
    EHOOK_DY(th06_wall_prac, 0x40D57C,7,{
        if (thPracParam.mode && thPracParam.stage == 5  && thPracParam.wall_prac_st6) {
            auto GetRandF = []() -> float {
                unsigned int(__fastcall * sb_41E7F0_rand_int)(DWORD thiz);
                sb_41E7F0_rand_int = (decltype(sb_41E7F0_rand_int))0x41E7F0;
                unsigned int randi = sb_41E7F0_rand_int(0x69D8F8);
                return static_cast<float>((double)randi / 4294967296.0);
            }; // rand from 0 to 1
            if (thPracParam.section == TH06_ST6_BOSS6)
            {
                float posb1 = 0.4;
                float posb2 = 0.9;
                float posb3 = 0.2;
               
                float* wall_angle = (float*)(pCtx->Ebp - 0x68);
                DWORD penm = *(DWORD*)(pCtx->Ebp + 0x8);
                float bossx = *(float*)(penm + 0xC6C);
                float bossy = *(float*)(penm + 0xC70);
                float plx = *(float*)(0x6CAA68);
                float ply = *(float*)(0x6CAA6C);
                float angle_pl = atan2f(ply - bossy, plx - bossx);
                float dist_pl = hypotf(ply - bossy, plx - bossx);
                
                float decision = GetRandF();
                
                // - 1.570796f + GetRandF() * 1.745329f
                if (decision < posb1) {
                    float min_dist_bt = 99999.0f;
                    for (int i = 0; i < 640; i++) {
                        DWORD pbt = 0x005AB5F8 + i * 0x5C4;
                        if (*(WORD*)(pbt + 0x5BE)
                            && *(WORD*)(pbt + 0x5BE) != 5
                            && *(DWORD*)(pbt + 0xC0)
                            && *(float*)(*(DWORD*)(pbt + 0xC0) + 0x2C) < 30.0
                            && *(float*)(pbt + 0x584) == 0.0)
                        {
                            ImVec2 pos = *(ImVec2*)(pbt + 0x560);
                            min_dist_bt = std::min(min_dist_bt, hypotf(pos.x - bossx, pos.y - bossy));
                        }
                    }
                    if (decision < posb3)
                        *wall_angle = angle_pl - min_dist_bt * 3.14159f / 256.0f - 0.5235988f + GetRandF() * 0.5235988f; // -30 deg ~ 0deg
                    else
                        *wall_angle = angle_pl - min_dist_bt * 3.14159f / 256.0f - 1.570796f + GetRandF() * 1.745329f; // -90 deg ~ 10deg
                } else if (decision < posb2) {
                    // angle = randA + dist*pi/256 = pi
                    // => randA = pi - dist*pi/256
                    *wall_angle = 3.14159f - dist_pl * 3.14159f / 256.0f - 0.2617f + GetRandF() * 0.5235988f; //
                }else {
                    *wall_angle = GetRandF() * 6.28318f - 3.1415926f;
                }
            } else if (thPracParam.section == TH06_ST6_BOSS9) {
                float* wall_angle = (float*)(pCtx->Ebp - 0x68);
                DWORD penm = *(DWORD*)(pCtx->Ebp + 0x8);
                float bossx = *(float*)(penm + 0xC6C);
                float bossy = *(float*)(penm + 0xC70);
                float plx = *(float*)(0x6CAA68);
                float ply = *(float*)(0x6CAA6C);
                float angle_pl = atan2f(ply - bossy, plx - bossx);

                float decision = GetRandF();
                if (decision < 0.8) {
                    float min_dist_bt = 99999.0f;
                    ImVec2 bt_pos = { 0.0f, 0.0f };
                    for (int i = 0; i < 640; i++) {
                        DWORD pbt = 0x005AB5F8 + i * 0x5C4;
                        if (*(WORD*)(pbt + 0x5BE)
                            && *(WORD*)(pbt + 0x5BE) != 5
                            && *(DWORD*)(pbt + 0xC0)
                            && *(float*)(*(DWORD*)(pbt + 0xC0) + 0x2C) < 30.0
                            && *(float*)(pbt + 0x584) == 0.0) {
                            ImVec2 pos = *(ImVec2*)(pbt + 0x560);
                            auto dist = hypotf(pos.x - g_last_boss_x, pos.y - g_last_boss_y);
                            if (min_dist_bt > dist) {
                                min_dist_bt = dist;
                                bt_pos = pos;
                            }
                        }
                    }
                    *wall_angle = angle_pl - hypotf(bt_pos.x - bossx, bt_pos.y - bossy) * 3.14159f / 256.0f + (GetRandF() - 0.5f) * 2.0f * 0.34f;
                }else {
                    *wall_angle = GetRandF() * 6.28318f - 3.1415926f;
                }
            }
        }
    })
    EHOOK_DY(th06_wall_prac2, 0x0040D900,6,{
        if (thPracParam.mode && thPracParam.stage == 5 && thPracParam.wall_prac_st6 && thPracParam.section == TH06_ST6_BOSS9 
            && (thPracParam.snipeF > 0 || thPracParam.snipeN > 0)
            ) {
                float* angle = (float*)(pCtx->Ebp - 0x70);
                DWORD pbt = *(DWORD*)(pCtx->Ebp - 0x60);
                ImVec2 pos = *(ImVec2*)(pbt + 0x560);
                float plx = *(float*)(0x6CAA68);
                float ply = *(float*)(0x6CAA6C);
                float dist_pl = hypotf(plx - pos.x, ply - pos.y);
                float angle_pl = atan2f(ply - pos.y, plx - pos.x);
                float random_near = 1.0f - thPracParam.snipeN/100.0f;
                float random_far = 1.0f - thPracParam.snipeF / 100.0f;
                if (dist_pl > 400.0f) {
                    dist_pl = 400.0f;
                }
                *angle = *angle * (dist_pl * (random_far - random_near) / 400.0f + random_near) + angle_pl;

        }
    })
    PATCH_DY(th06_disable_menu, 0x439ab2, "9090909090")
    EHOOK_DY(th06_update, 0x41caac, 1, {
        GameGuiBegin(IMPL_WIN32_DX8, !THAdvOptWnd::singleton().IsOpen());
        
        // Gui components update
        Gui::KeyboardInputUpdate(VK_ESCAPE);
        THPauseMenu::singleton().Update();
        THGuiPrac::singleton().Update();
        THGuiRep::singleton().Update();
        THOverlay::singleton().Update();
        TH06InGameInfo::singleton().Update();
        if (TH06InGameInfo::singleton().booksInfo.is_books) {
            TH06InGameInfo::singleton().booksInfo.time_books++;
        }
        TH06Save::singleton().IncreaseGameTime();

        auto p = ImGui::GetOverlayDrawList();
        RenderPlHitbox(ImGui::GetBackgroundDrawList());
        SSS::SSS_Update(6);

        RenderRepMarker(p);
        RenderBtHitbox(p);
        RenderLockTimer(p);
        GameUpdateOuter(p, 6);
        if (g_adv_igi_options.show_keyboard_monitor && (*(DWORD*)(0x6C6EA4) == 2)) {
            g_adv_igi_options.keyboard_style.size = { 48.0f, 48.0f };
            KeysHUD(6, { 1280.0f, 0.0f }, { 833.0f, 0.0f }, g_adv_igi_options.keyboard_style);
        }
        {
            if (THAdvOptWnd::singleton().forceBossMoveDown) {
                auto sz = ImGui::CalcTextSize(S(TH_BOSS_FORCE_MOVE_DOWN));
                p->AddRectFilled({ 120.0f, 0.0f }, { sz.x + 120.0f, sz.y }, 0xFFCCCCCC);
                p->AddText({ 120.0f, 0.0f }, 0xFFFF0000, S(TH_BOSS_FORCE_MOVE_DOWN));
            }
        }
        
        GameGuiEnd(THAdvOptWnd::StaticUpdate() || THGuiPrac::singleton().IsOpen() || THPauseMenu::singleton().IsOpen());
    })
    EHOOK_DY(th06_render, 0x41cb6d, 1, {
        GameGuiRender(IMPL_WIN32_DX8);

        if (Gui::GetChordPressed(Gui::GetScreenshotChord()))
            THSnapshot::Snapshot(*(IDirect3DDevice8**)0x6c6d20);
    })
    EHOOK_DY(th06_player_state, 0x4288C0,1,
    {
        if (g_adv_igi_options.show_keyboard_monitor)
            RecordKey(6, *(WORD*)(0x69D904));
    })
    EHOOK_DY(th06_rep_seed,0x42A97E,10,{
       g_last_rep_seed = *(uint16_t*)(0x0069D8F8);
    })
    EHOOK_DY(th06_fix_seed, 0x41BE47,7,{
        if (g_adv_igi_options.th06_fix_seed)
        {
            if ((*(DWORD*)(0x69d6d4) == 1 || *(DWORD*)(0x69d6d4) == 7)) {
                if ((!thPracParam.mode) || thPracParam.section == 10000 + 1 * 100 + 1 || thPracParam.section == 0)
                {
                    *(uint16_t*)(0x69D8F8) = (uint16_t)((int32_t)g_adv_igi_options.th06_seed & 0xFFFF);
                }
            }
        }
    })
    HOOKSET_ENDDEF()

    HOOKSET_DEFINE(THInGameInfo)
    EHOOK_DY(th06_enter_game, 0x41BDE8,4, // set inner misscount to 0
    {
        TH06InGameInfo::singleton().GameStartInit();
        // TH06InGameInfo::singleton().Retry();
    })
    // EHOOK_DY(miss_spellcard_get_failed, 0x4277C3,3,
    // {
    //     is_died = true;
    // })
    EHOOK_DY(th06_miss, 0x428DD9,2,// dec life
    {
        TH06InGameInfo::singleton().mMissCount++;
        FastRetry(thPracParam.mode);
    })
    EHOOK_DY(th06_bomb, 0x4289CC, 6, {
    })
    EHOOK_DY(th06_lock_timer1, 0x41B27C,3, // initialize
    {
        g_lock_timer = 0;
    })
    EHOOK_DY(th06_lock_timer2, 0x409A10,6, // set timeout case 115
    {
        g_lock_timer = 0;
    })
    EHOOK_DY(th06_lock_timer3, 0x408DDA,2, // set boss mode case 101
    {
        g_lock_timer = 0;
    })
    EHOOK_DY(th06_lock_timer4, 0x411F88,6, // decrease time (update)
    {
        g_lock_timer++;
    })

    EHOOK_DY(th06_autoName_score,0x42BE49,5,{
        if (g_adv_igi_options.th06_autoname){
            int size = strlen(g_adv_igi_options.th06_autoname_name);
            if (size > 8)
                size = 8;
            if (size >= 1){
                *(DWORD*)(pCtx->Eax + 0x10) = size - 1;
                for (int i = 0; i < size; i++) {
                    *(char*)(pCtx->Eax + 0x5193 + i) = (g_adv_igi_options.th06_autoname_name[i] == '~') ? '\xA5' : g_adv_igi_options.th06_autoname_name[i]; // red slash = 0xA5
                }
            }
        }
    })
    EHOOK_DY(th06_autoName_rep_overwrite, 0x42D085,7,
    {
        if (g_adv_igi_options.th06_autoname) {
            bool set_name = true;
            int name_len = 0;
            for (int i = 0; i < 8; i++) {
                char ch = *(char*)(pCtx->Eax + 0x34 + i);
                if (ch != ' ' && ch!=0) {
                    set_name = false;
                    name_len = i;
                }
            }
            if (set_name) {
                int size = strlen(g_adv_igi_options.th06_autoname_name);
                if (size > 8)
                    size = 8;
                if (size >= 1) {
                    *(DWORD*)(pCtx->Eax + 0x10) = size - 1;
                    for (int i = 0; i < 8; i++) {
                        if (i < size)
                            *(char*)(pCtx->Eax + 0x34 + i) = (g_adv_igi_options.th06_autoname_name[i] == '~') ? '\xA5' : g_adv_igi_options.th06_autoname_name[i]; // red slash = 0xA5
                        else
                            *(char*)(pCtx->Eax + 0x34 + i) = ' ';
                    }
                }
            }else{
                *(DWORD*)(pCtx->Eax + 0x10) = name_len;
            }
        }
    })
    EHOOK_DY(th06_autoName_rep, 0x42C8A0,2,
    {
        if (g_adv_igi_options.th06_autoname) {
            bool set_name = true;
            int name_len = 0;
            for (int i = 0; i < 8; i++){
                char ch = *(char*)(pCtx->Eax + 0x34 + i);
                if (ch != ' ' && ch != 0) {
                    set_name = false;
                    name_len = i;
                }
            }
            if (set_name){
                int size = strlen(g_adv_igi_options.th06_autoname_name);
                if (size > 8)
                    size = 8;
                if (size >= 1) {
                    *(DWORD*)(pCtx->Eax + 0x10) = size - 1;
                    for (int i = 0; i < 8; i++) {
                        if (i < size)
                            *(char*)(pCtx->Eax + 0x34 + i) = (g_adv_igi_options.th06_autoname_name[i] == '~') ? '\xA5' : g_adv_igi_options.th06_autoname_name[i]; // red slash = 0xA5
                        else
                            *(char*)(pCtx->Eax + 0x34 + i) = ' ';
                    }
                    pCtx->Eip = 0x42C91C;
                }
            }else{
                *(DWORD*)(pCtx->Eax + 0x10) = name_len;
                pCtx->Eip = 0x42C91C;
            }
        }
       
    })
    HOOKSET_ENDDEF()

    HOOKSET_DEFINE(TH06_SavesHook)
    EHOOK_DY(th06BooksStart, 0x41188A, 3, {
        // timeline ins_4
        // also saves books' pos
        if (*(DWORD*)0x69d6d4 == 4) { // stage 4
            DWORD pCode = *(DWORD*)0x487e50;
            DWORD pCodeOfs = *(DWORD*)(pCtx->Ebp - 0x14) - 8;
            float posx = *(float*)(pCtx->Ebp - 0x20);
            float posy = *(float*)(pCtx->Ebp - 0x1C);
            int n = (pCodeOfs - pCode - 0xCDD4) / 0x1C;
            g_books_pos[n] = { posx, posy };

            if (n == 0) {//1st book
                TH06InGameInfo::singleton().booksInfo.is_books = true;
                TH06InGameInfo::singleton().booksInfo.time_books = 0;
                TH06InGameInfo::singleton().booksInfo.is_died = false;
                TH06InGameInfo::singleton().booksInfo.miss_count = TH06InGameInfo::singleton().mMissCount;
                TH06InGameInfo::singleton().booksInfo.bomb_count = *(int8_t*)(0x0069BCC4);
                bool is_rep = *(BYTE*)0x69BCBC;
                if (!is_rep) {
                    if ( !(thPracParam.mode && thPracParam.stage == 3 && thPracParam.section == TH06_ST4_BOOKS && thPracParam.phase != 0)) {// not in other Tests
                        byte cur_player_typea = *(byte*)(0x69D4BD);
                        byte cur_player_typeb = *(byte*)(0x69D4BE);
                        byte cur_player_type = (cur_player_typea << 1) | cur_player_typeb;
                        int8_t diff = *(int8_t*)(0x69bcb0);
                        int32_t spell_id = TH06Save::spellid_books;
                        TH06Save::singleton().AddAttempt(spell_id, diff, cur_player_type);
                    }
                }
            }
        }
    })
    EHOOK_DY(th06BooksEnd, 0x411669, 3, {
        // timeline ins_0
        // also saves books' pos
        if (*(DWORD*)0x69d6d4 == 4 && TH06InGameInfo::singleton().booksInfo.is_books == true) { // stage 4
            DWORD pCode = *(DWORD*)0x487e50;
            DWORD pCodeOfs = *(DWORD*)(pCtx->Ebp - 0xC) - 8;
            if (pCodeOfs - pCode == 0xCE7C) { // mid boss

                TH06InGameInfo::singleton().booksInfo.is_books = false;
                TH06InGameInfo::singleton().booksInfo.time_books = 0;
                bool is_rep = *(BYTE*)0x69BCBC;
                if (!is_rep) {
                    if (!(thPracParam.mode && thPracParam.stage == 3 && thPracParam.section == TH06_ST4_BOOKS && thPracParam.phase != 0)) { // not in other Tests

                        if (TH06InGameInfo::singleton().booksInfo.is_died == false
                        && TH06InGameInfo::singleton().booksInfo.miss_count == TH06InGameInfo::singleton().mMissCount
                        && TH06InGameInfo::singleton().booksInfo.bomb_count == *(int8_t*)(0x0069BCC4)) {
                            byte cur_player_typea = *(byte*)(0x69D4BD);
                            byte cur_player_typeb = *(byte*)(0x69D4BE);
                            byte cur_player_type = (cur_player_typea << 1) | cur_player_typeb;
                            int8_t diff = *(int8_t*)(0x69bcb0);
                            int32_t spell_id = TH06Save::spellid_books;
                            TH06Save::singleton().AddCapture(spell_id, diff, cur_player_type);
                        }
                        TH06InGameInfo::singleton().booksInfo.is_died = false;
                    }
                }
            }
        }
    })
    EHOOK_DY(miss_spellcard_get_failed, 0x4277C3, 3,
    {
        if (TH06InGameInfo::singleton().booksInfo.is_books == true)
        {
            TH06InGameInfo::singleton().booksInfo.is_died = true;
        }
    })
    EHOOK_DY(th06_close, 0x420669, 2, {
        TH06Save::singleton().SaveSave();
    })
    EHOOK_DY(th06_spellStart, 0x4096e8, 7,
        {
            bool is_rep = *(BYTE*)0x69BCBC;
            if (!is_rep) {
                byte cur_player_typea = *(byte*)(0x69D4BD);
                byte cur_player_typeb = *(byte*)(0x69D4BE);
                byte cur_player_type = (cur_player_typea << 1) | cur_player_typeb;
                int8_t diff = *(int8_t*)(0x69bcb0);
                int32_t spell_id = *(int8_t*)(0x5A5F98);
                TH06Save::singleton().AddAttempt(spell_id, diff, cur_player_type);
            }
        })
    EHOOK_DY(th06_spellCapture, 0x409978, 6,
        {
            bool is_rep = *(BYTE*)0x69BCBC;
            if (!is_rep) {
                byte cur_player_typea = *(byte*)(0x69D4BD);
                byte cur_player_typeb = *(byte*)(0x69D4BE);
                byte cur_player_type = (cur_player_typea << 1) | cur_player_typeb;
                int8_t diff = *(int8_t*)(0x69bcb0);
                int32_t spell_id = *(int8_t*)(0x5A5F98);
                TH06Save::singleton().AddCapture(spell_id, diff, cur_player_type);
            }
        })
    EHOOK_DY(th06_spellTimeout, 0x412056, 10,
        {
            bool is_rep = *(BYTE*)0x69BCBC;
            if (!is_rep) {
                DWORD is_capture = *(DWORD*)(0x5A5F8C);
                if (is_capture)
                {
                    byte cur_player_typea = *(byte*)(0x69D4BD);
                    byte cur_player_typeb = *(byte*)(0x69D4BE);
                    byte cur_player_type = (cur_player_typea << 1) | cur_player_typeb;
                    int8_t diff = *(int8_t*)(0x69bcb0);
                    int32_t spell_id = *(int8_t*)(0x5A5F98);
                    int32_t stage = *(DWORD*)0x69d6d4;
                    if (! (spell_id == 1 && stage != 1))// to avoid spell record bug
                    {
                        TH06Save::singleton().AddTimeOut(spell_id, diff, cur_player_type);
                    }
                }
            }
        })
    HOOKSET_ENDDEF()

     static __declspec(noinline) void THGuiCreate()
     {
         if (ImGui::GetCurrentContext()) {
             return;
         }

        // Init
        GameGuiInit(IMPL_WIN32_DX8, 0x6c6d20, 0x6c6bd4,
            Gui::INGAGME_INPUT_GEN1, 0x69d904, 0x69d908, 0x69d90c,
            -1);
         SetDpadHook(0x41D330, 3);
        // g_adv_igi_options.th06_showHitbox
        g_hitbox_textureID = ReadImage(8, *(DWORD*)0x6c6d20, "hitbox.png", hitbox_file, sizeof(hitbox_file));
        D3DSURFACE_DESC desc;
        ((LPDIRECT3DTEXTURE8)g_hitbox_textureID)->GetLevelDesc(0, &desc);
        g_hitbox_sz.x = static_cast<float>(desc.Width), g_hitbox_sz.y = static_cast<float>(desc.Height);

        // Gui components creation
        THGuiPrac::singleton();
        THPauseMenu::singleton();
        THGuiRep::singleton();
        THOverlay::singleton();
        TH06InGameInfo::singleton();
        TH06Save::singleton();
        // Hooks
        EnableAllHooks(THMainHook);
        EnableAllHooks(THInGameInfo);
        EnableAllHooks(TH06_SavesHook);

        th06_white_screen.Setup();
        th06_result_screen_create.Setup();
        if (g_adv_igi_options.th06_bg_fix)
        {
            EnableAllHooks(TH06BgFix);
        }

        // Reset thPracParam
        thPracParam.Reset();

    }

    HOOKSET_DEFINE(THInitHook)
    EHOOK_DY(th06_gui_init_1, 0x43596f, 3, {
        THGuiCreate();
        self->Disable();
    })
    EHOOK_DY(th06_gui_init_2, 0x42140c, 1, {
        THGuiCreate();
        self->Disable();
    })
    HOOKSET_ENDDEF()
}
#include <d3d9types.h>
void TH06Init()
{
    EnableAllHooks(TH06::THInitHook);
    InitHook(6,(void*)0x420f59);
}

}
