from ED6ScenarioHelper import *

def main():
    SetCodePage("ms932")

    # 柏斯

    CreateScenaFile(
        FileName            = 'T1511   ._SN',
        MapName             = 'Bose',
        Location            = 'T1511.x',
        MapIndex            = 1,
        MapDefaultBGM       = "ed60084",
        Flags               = 0,
        EntryFunctionIndex  = 0xFFFF,
        Reserved            = 0,
        IncludedScenario    = [
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            ''
        ],
    )

    BuildStringList(
        '@FileName',                            # 8
        'Lenard',                               # 9
        'Sophina',                              # 10
        'Lloyd',                                # 11
        'Elke',                                 # 12
        'Anette',                               # 13
        'Olivier',                              # 14
        'Olivier',                              # 15
    )

    DeclEntryPoint(
        Unknown_00              = 0,
        Unknown_04              = 0,
        Unknown_08              = 6000,
        Unknown_0C              = 4,
        Unknown_0E              = 0,
        Unknown_10              = 0,
        Unknown_14              = 9500,
        Unknown_18              = -10000,
        Unknown_1C              = 0,
        Unknown_20              = 0,
        Unknown_24              = 0,
        Unknown_28              = 2800,
        Unknown_2C              = 262,
        Unknown_30              = 225,
        Unknown_32              = 0,
        Unknown_34              = 360,
        Unknown_36              = 0,
        Unknown_38              = 0,
        Unknown_3A              = 0,
        InitScenaIndex          = 0,
        InitFunctionIndex       = 0,
        EntryScenaIndex         = 0,
        EntryFunctionIndex      = 1,
    )

    AddCharChip(
        'ED6_DT07/CH01270 ._CH',             # 00
        'ED6_DT07/CH01690 ._CH',             # 01
        'ED6_DT07/CH01023 ._CH',             # 02
        'ED6_DT07/CH01180 ._CH',             # 03
        'ED6_DT07/CH01210 ._CH',             # 04
        'ED6_DT06/CH20050 ._CH',             # 05
    )

    AddCharChipPat(
        'ED6_DT07/CH01270P._CP',             # 00
        'ED6_DT07/CH01690P._CP',             # 01
        'ED6_DT07/CH01023P._CP',             # 02
        'ED6_DT07/CH01180P._CP',             # 03
        'ED6_DT07/CH01210P._CP',             # 04
        'ED6_DT06/CH20050P._CP',             # 05
    )

    DeclNpc(
        X                   = 24400,
        Z                   = 0,
        Y                   = 9200,
        Direction           = 0,
        Unknown2            = 0,
        Unknown3            = 0,
        ChipIndex           = 0x0,
        NpcIndex            = 0x101,
        InitFunctionIndex   = 0,
        InitScenaIndex      = 2,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 4,
    )

    DeclNpc(
        X                   = 14000,
        Z                   = 0,
        Y                   = 3600,
        Direction           = 180,
        Unknown2            = 0,
        Unknown3            = 1,
        ChipIndex           = 0x1,
        NpcIndex            = 0x101,
        InitFunctionIndex   = 0,
        InitScenaIndex      = 2,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 5,
    )

    DeclNpc(
        X                   = 49500,
        Z                   = 200,
        Y                   = 26230,
        Direction           = 90,
        Unknown2            = 0,
        Unknown3            = 2,
        ChipIndex           = 0x2,
        NpcIndex            = 0x155,
        InitFunctionIndex   = -1,
        InitScenaIndex      = -1,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 8,
    )

    DeclNpc(
        X                   = 54500,
        Z                   = 0,
        Y                   = 3400,
        Direction           = 180,
        Unknown2            = 0,
        Unknown3            = 3,
        ChipIndex           = 0x3,
        NpcIndex            = 0x101,
        InitFunctionIndex   = 0,
        InitScenaIndex      = 2,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 6,
    )

    DeclNpc(
        X                   = 49900,
        Z                   = 0,
        Y                   = 5800,
        Direction           = 135,
        Unknown2            = 0,
        Unknown3            = 4,
        ChipIndex           = 0x4,
        NpcIndex            = 0x101,
        InitFunctionIndex   = 0,
        InitScenaIndex      = 3,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 7,
    )

    DeclNpc(
        X                   = 109100,
        Z                   = 600,
        Y                   = 5100,
        Direction           = 270,
        Unknown2            = 0,
        Unknown3            = 5,
        ChipIndex           = 0x5,
        NpcIndex            = 0x156,
        InitFunctionIndex   = -1,
        InitScenaIndex      = -1,
        TalkFunctionIndex   = -1,
        TalkScenaIndex      = -1,
    )

    DeclNpc(
        X                   = 110010,
        Z                   = -500,
        Y                   = 5150,
        Direction           = 0,
        Unknown2            = 0,
        Unknown3            = 5,
        ChipIndex           = 0x5,
        NpcIndex            = 0x156,
        InitFunctionIndex   = -1,
        InitScenaIndex      = -1,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 9,
    )

    DeclActor(
        TriggerX            = 80610,
        TriggerZ            = 0,
        TriggerY            = 9100,
        TriggerRange        = 1400,
        ActorX              = 80610,
        ActorZ              = 1500,
        ActorY              = 9100,
        Flags               = 0x7C,
        TalkScenaIndex      = 0,
        TalkFunctionIndex   = 11,
        Unknown_22          = 0,
    )

    ScpFunction(
        "Function_0_1DE",          # 00, 0
        "Function_1_1ED",          # 01, 1
        "Function_2_1EE",          # 02, 2
        "Function_3_204",          # 03, 3
        "Function_4_228",          # 04, 4
        "Function_5_2B1",          # 05, 5
        "Function_6_341",          # 06, 6
        "Function_7_3D9",          # 07, 7
        "Function_8_48E",          # 08, 8
        "Function_9_67B",          # 09, 9
        "Function_10_6B9",         # 0A, 10
        "Function_11_EA8",         # 0B, 11
    )

    def Function_0_1DE(): pass

    label("Function_0_1DE")

    Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x7F, 2)), scpexpr(EXPR_END)), "loc_1EC")
    OP_A3(0x3FA)
    Event(0, 10)

    label("loc_1EC")

    Return()

    # Function_0_1DE end

    def Function_1_1ED(): pass

    label("Function_1_1ED")

    Return()

    # Function_1_1ED end

    def Function_2_1EE(): pass

    label("Function_2_1EE")

    Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_203")
    OP_99(0xFE, 0x0, 0x7, 0x5DC)
    Jump("Function_2_1EE")

    label("loc_203")

    Return()

    # Function_2_1EE end

    def Function_3_204(): pass

    label("Function_3_204")

    Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_227")
    OP_8D(0xFE, 50200, 5000, 54800, 6300, 2000)
    Jump("Function_3_204")

    label("loc_227")

    Return()

    # Function_3_204 end

    def Function_4_228(): pass

    label("Function_4_228")

    TalkBegin(0x8)

    ChrTalk(    #0
        0xFE,
        "Are you going out?\x02",
    )

    CloseMessageWindow()

    ChrTalk(    #1
        0xFE,
        (
            "If you're going to fish at night,\x01",
            "you're going to need an orbment\x01",
            "light or you won't be able to see.\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0x8)
    Return()

    # Function_4_228 end

    def Function_5_2B1(): pass

    label("Function_5_2B1")

    TalkBegin(0x9)

    ChrTalk(    #2
        0xFE,
        (
            "That gentleman with you seems\x01",
            "to have drunk a lot. Is he going\x01",
            "to be all right?\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #3
        0xFE,
        (
            "If you would like, I can bring\x01",
            "you some water.\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0x9)
    Return()

    # Function_5_2B1 end

    def Function_6_341():

    label("Function_6_341")

    TalkBegin(0xB)

    ChrTalk(    #4
        0xFE,
        "Good evening.\x02",
    )

    CloseMessageWindow()

    ChrTalk(    #5
        0xFE,
        (
            "Seeing another group of lodgers\x01",
            "is something I enjoy.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #6
        0xFE,
        (
            "I'd love to keep company with\x01",
            "you if that would be all right.\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0xB)
    Return()

    # Function_6_341 end

    def Function_7_3D9(): pass

    label("Function_7_3D9")

    TalkBegin(0xC)

    ChrTalk(    #7
        0xFE,
        (
            "My mother seems to be\x01",
            "enjoying the atmosphere.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #8
        0xFE,
        (
            "I was the first person to recommend\x01",
            "this inn to my mother.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #9
        0xFE,
        (
            "Now she invites me to come\x01",
            "here with her every year.\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0xC)
    Return()

    # Function_7_3D9 end

    def Function_8_48E(): pass

    label("Function_8_48E")

    TalkBegin(0xA)
    Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_63C")
    OP_A2(0x0)
    SetMessageWindowPos(72, 320, 56, 3)
    FadeToDark(300, 0, 100)

    AnonymousTalk(    #10
        "\x07\x05Lloyd is staring at an open map. It appears to be a map of Valleria Lake.\x02",
    )

    CloseMessageWindow()
    OP_56(0x0)
    FadeToBright(300, 0)

    ChrTalk(    #11
        0xFE,
        (
            "There are hardly any structures\x01",
            "on the west side, and I didn't get\x01",
            "many bites either.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #12
        0xFE,
        (
            "And all I'm getting on the east\x01",
            "side are small sized fish.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #13
        0xFE,
        (
            "The Guardian probably won't appear\x01",
            "in either of these two places...\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #14
        0xFE,
        (
            "I guess the best thing I can\x01",
            "do is to continue fishing\x01",
            "from the shore.\x02",
        )
    )

    CloseMessageWindow()
    Jump("loc_677")

    label("loc_63C")

    ChrTalk(    #15
        0xFE,
        (
            "I'm going to catch the Guardian this\x01",
            "time for sure...\x02",
        )
    )

    CloseMessageWindow()

    label("loc_677")

    TalkEnd(0xA)
    Return()

    # Function_8_48E end

    def Function_9_67B(): pass

    label("Function_9_67B")

    TalkBegin(0xD)

    ChrTalk(    #16
        0xFE,
        (
            "Ugh... Schera...please...\x01",
            "I can't take another...\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0xD)
    Return()

    # Function_9_67B end

    def Function_10_6B9(): pass

    label("Function_10_6B9")

    ClearMapFlags(0x1)
    EventBegin(0x0)
    AddParty(0x2, 0xFF)
    SetChrPos(0x101, 107680, 0, 5310, 90)
    SetChrPos(0x103, 109180, 0, 6400, 180)
    SetChrPos(0x102, 107620, 0, 6630, 135)
    OP_6D(107890, 0, 13120, 0)
    OP_A2(0x34E)
    OP_28(0x38, 0x1, 0x80)
    FadeToBright(2000, 0)
    OP_6D(109120, 0, 5740, 3000)

    ChrTalk(    #17
        0xE,
        (
            "#038F#6POhhh... Uggghhh...\x02\x03",

            "Uhhh... Gehhh...\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #18
        0x101,
        (
            "#007F#6POh, he's totally plastered.\x02\x03",

            "It looks like even a guy who takes his\x01",
            "sweet time for everything couldn't stand\x01",
            "up to a drunken Schera.\x02",
        )
    )

    CloseMessageWindow()
    OP_62(0x103, 0x0, 2000, 0x26, 0x27, 0xFA, 0x2)
    Sleep(1200)

    ChrTalk(    #19
        0x103,
        (
            "#021F#6POh, wow. What a night of drinking.\x02\x03",

            "I've been so busy lately I haven't\x01",
            "been able to enjoy myself like\x01",
            "this for a while.\x02",
        )
    )

    CloseMessageWindow()
    TurnDirection(0x102, 0x103, 200)

    ChrTalk(    #20
        0x102,
        (
            "#017FAnd you're not even red in the\x01",
            "face either from all that alcohol...\x02\x03",

            "#018FAre you sure you haven't had\x01",
            "some special kind of training,\x01",
            "Schera?\x02",
        )
    )

    CloseMessageWindow()
    TurnDirection(0x103, 0x102, 400)

    ChrTalk(    #21
        0x103,
        (
            "#020F#6PUm, it could have been all the\x01",
            "bizarre liquors I drank while\x01",
            "I was in the troupe.\x02\x03",

            "You know, like the ones with\x01",
            "scorpions and asps in them.\x02\x03",

            "#021FI might have built up my resistance\x01",
            "that way, but who knows.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #22
        0x102,
        (
            "#017FSomehow...I don't think that that's\x01",
            "the case.\x02",
        )
    )

    CloseMessageWindow()
    TurnDirection(0x101, 0x103, 400)

    ChrTalk(    #23
        0x101,
        (
            "#009F#6PBy the way, what do you plan on\x01",
            "doing with him? He's pretty much\x01",
            "useless as he is.\x02",
        )
    )

    CloseMessageWindow()
    TurnDirection(0x103, 0x101, 400)

    ChrTalk(    #24
        0x103,
        (
            "#026F#6PLet's just let him sleep. He looks\x01",
            "so peaceful now, and we wouldn't\x01",
            "want to disturb him.\x02\x03",

            "#022FThere's a very high possibility\x01",
            "that we'll have a direct encounter\x01",
            "with the sky bandits tonight.\x02\x03",

            "And getting a civilian wrapped up\x01",
            "in the middle of it all wouldn't\x01",
            "be a good idea.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #25
        0x101,
        (
            "#004F#6PDon't tell me you...\x02\x03",

            "You got Olivier drunk so he wouldn't\x01",
            "be able to come along, didn't you?\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #26
        0x103,
        (
            "#023F#6PWell...\x02\x03",

            "...\x02\x03",

            "#021FOf course I did. And he'll thank\x01",
            "me in the long run, too. After\x01",
            "his raging hangover, anyway...\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #27
        0x101,
        "#509F#6PAnd so that whole time...\x02",
    )

    CloseMessageWindow()

    ChrTalk(    #28
        0x102,
        (
            "#018FYou were just toying with him,\x01",
            "weren't you?\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #29
        0x103,
        (
            "#026F#6PLet's see... It's getting late.\x02\x03",

            "Let's hurry and begin our stakeout\x01",
            "around the inn.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #30
        0x101,
        (
            "#507F#6PDon't skirt around the issue,\x01",
            "Schera.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #31
        0x103,
        (
            "#022F#6PQuiet, you!\x02\x03",

            "For the time being, we're going\x01",
            "to circle up to the far pier.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #32
        0x102,
        "#010FUnderstood.\x02",
    )

    CloseMessageWindow()

    ChrTalk(    #33
        0x101,
        "#006F#6PAll right then, let's go!\x02",
    )

    CloseMessageWindow()
    FadeToDark(1000, 0, -1)
    OP_0D()
    SetChrPos(0x101, 107480, 0, 9560, 0)
    SetChrPos(0x103, 107480, 0, 9560, 0)
    SetChrPos(0x102, 107480, 0, 9560, 0)
    OP_6D(107480, 0, 9560, 0)
    Sleep(500)
    FadeToBright(1000, 0)
    EventEnd(0x0)
    ClearMapFlags(0x10000000)
    Return()

    # Function_10_6B9 end

    def Function_11_EA8(): pass

    label("Function_11_EA8")

    FadeToDark(300, 0, 100)
    SetMessageWindowPos(72, 320, 56, 3)
    SetChrName("")

    AnonymousTalk(    #34
        "\x07\x05There are some fishing rods propped against the rack.\x02",
    )

    CloseMessageWindow()
    OP_56(0x0)
    SetMessageWindowPos(72, 320, 56, 3)
    FadeToBright(300, 0)
    TalkEnd(0xFF)
    Return()

    # Function_11_EA8 end

    SaveToFile()

Try(main)


from ED6ScenarioHelper import *

def main():
    SetCodePage("ms932")

    # 柏斯

    CreateScenaFile(
        FileName            = 'T1511   ._SN',
        MapName             = 'Bose',
        Location            = 'T1511.x',
        MapIndex            = 1,
        MapDefaultBGM       = "ed60084",
        Flags               = 0,
        EntryFunctionIndex  = 0xFFFF,
        Reserved            = 0,
        IncludedScenario    = [
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            ''
        ],
    )

    BuildStringList(
        '@FileName',                            # 8
        'Lenard',                               # 9
        'Sophina',                              # 10
        'Lloyd',                                # 11
        'Elke',                                 # 12
        'Anette',                               # 13
        'Olivier',                              # 14
        'Olivier',                              # 15
    )

    DeclEntryPoint(
        Unknown_00              = 0,
        Unknown_04              = 0,
        Unknown_08              = 6000,
        Unknown_0C              = 4,
        Unknown_0E              = 0,
        Unknown_10              = 0,
        Unknown_14              = 9500,
        Unknown_18              = -10000,
        Unknown_1C              = 0,
        Unknown_20              = 0,
        Unknown_24              = 0,
        Unknown_28              = 2800,
        Unknown_2C              = 262,
        Unknown_30              = 225,
        Unknown_32              = 0,
        Unknown_34              = 360,
        Unknown_36              = 0,
        Unknown_38              = 0,
        Unknown_3A              = 0,
        InitScenaIndex          = 0,
        InitFunctionIndex       = 0,
        EntryScenaIndex         = 0,
        EntryFunctionIndex      = 1,
    )

    AddCharChip(
        'ED6_DT07/CH01270 ._CH',             # 00
        'ED6_DT07/CH01690 ._CH',             # 01
        'ED6_DT07/CH01023 ._CH',             # 02
        'ED6_DT07/CH01180 ._CH',             # 03
        'ED6_DT07/CH01210 ._CH',             # 04
        'ED6_DT06/CH20050 ._CH',             # 05
    )

    AddCharChipPat(
        'ED6_DT07/CH01270P._CP',             # 00
        'ED6_DT07/CH01690P._CP',             # 01
        'ED6_DT07/CH01023P._CP',             # 02
        'ED6_DT07/CH01180P._CP',             # 03
        'ED6_DT07/CH01210P._CP',             # 04
        'ED6_DT06/CH20050P._CP',             # 05
    )

    DeclNpc(
        X                   = 24400,
        Z                   = 0,
        Y                   = 9200,
        Direction           = 0,
        Unknown2            = 0,
        Unknown3            = 0,
        ChipIndex           = 0x0,
        NpcIndex            = 0x101,
        InitFunctionIndex   = 0,
        InitScenaIndex      = 2,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 4,
    )

    DeclNpc(
        X                   = 14000,
        Z                   = 0,
        Y                   = 3600,
        Direction           = 180,
        Unknown2            = 0,
        Unknown3            = 1,
        ChipIndex           = 0x1,
        NpcIndex            = 0x101,
        InitFunctionIndex   = 0,
        InitScenaIndex      = 2,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 5,
    )

    DeclNpc(
        X                   = 49500,
        Z                   = 200,
        Y                   = 26230,
        Direction           = 90,
        Unknown2            = 0,
        Unknown3            = 2,
        ChipIndex           = 0x2,
        NpcIndex            = 0x155,
        InitFunctionIndex   = -1,
        InitScenaIndex      = -1,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 8,
    )

    DeclNpc(
        X                   = 54500,
        Z                   = 0,
        Y                   = 3400,
        Direction           = 180,
        Unknown2            = 0,
        Unknown3            = 3,
        ChipIndex           = 0x3,
        NpcIndex            = 0x101,
        InitFunctionIndex   = 0,
        InitScenaIndex      = 2,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 6,
    )

    DeclNpc(
        X                   = 49900,
        Z                   = 0,
        Y                   = 5800,
        Direction           = 135,
        Unknown2            = 0,
        Unknown3            = 4,
        ChipIndex           = 0x4,
        NpcIndex            = 0x101,
        InitFunctionIndex   = 0,
        InitScenaIndex      = 3,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 7,
    )

    DeclNpc(
        X                   = 109100,
        Z                   = 600,
        Y                   = 5100,
        Direction           = 270,
        Unknown2            = 0,
        Unknown3            = 5,
        ChipIndex           = 0x5,
        NpcIndex            = 0x156,
        InitFunctionIndex   = -1,
        InitScenaIndex      = -1,
        TalkFunctionIndex   = -1,
        TalkScenaIndex      = -1,
    )

    DeclNpc(
        X                   = 110010,
        Z                   = -500,
        Y                   = 5150,
        Direction           = 0,
        Unknown2            = 0,
        Unknown3            = 5,
        ChipIndex           = 0x5,
        NpcIndex            = 0x156,
        InitFunctionIndex   = -1,
        InitScenaIndex      = -1,
        TalkFunctionIndex   = 0,
        TalkScenaIndex      = 9,
    )

    DeclActor(
        TriggerX            = 80610,
        TriggerZ            = 0,
        TriggerY            = 9100,
        TriggerRange        = 1400,
        ActorX              = 80610,
        ActorZ              = 1500,
        ActorY              = 9100,
        Flags               = 0x7C,
        TalkScenaIndex      = 0,
        TalkFunctionIndex   = 11,
        Unknown_22          = 0,
    )

    ScpFunction(
        "Function_0_1DE",          # 00, 0
        "Function_1_1ED",          # 01, 1
        "Function_2_1EE",          # 02, 2
        "Function_3_204",          # 03, 3
        "Function_4_228",          # 04, 4
        "Function_5_2B1",          # 05, 5
        "Function_6_341",          # 06, 6
        "Function_7_3D9",          # 07, 7
        "Function_8_48E",          # 08, 8
        "Function_9_67B",          # 09, 9
        "Function_10_6B9",         # 0A, 10
        "Function_11_EA8",         # 0B, 11
    )

    def Function_0_1DE(): pass

    label("Function_0_1DE")

    Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x7F, 2)), scpexpr(EXPR_END)), "loc_1EC")
    OP_A3(0x3FA)
    Event(0, 10)

    label("loc_1EC")

    Return()

    # Function_0_1DE end

    def Function_1_1ED(): pass

    label("Function_1_1ED")

    Return()

    # Function_1_1ED end

    def Function_2_1EE(): pass

    label("Function_2_1EE")

    Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_203")
    OP_99(0xFE, 0x0, 0x7, 0x5DC)
    Jump("Function_2_1EE")

    label("loc_203")

    Return()

    # Function_2_1EE end

    def Function_3_204(): pass

    label("Function_3_204")

    Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_227")
    OP_8D(0xFE, 50200, 5000, 54800, 6300, 2000)
    Jump("Function_3_204")

    label("loc_227")

    Return()

    # Function_3_204 end

    def Function_4_228(): pass

    label("Function_4_228")

    TalkBegin(0x8)

    ChrTalk(    #0
        0xFE,
        "Are you going out?\x02",
    )

    CloseMessageWindow()

    ChrTalk(    #1
        0xFE,
        (
            "If you're going to fish at night,\x01",
            "you're going to need an orbment\x01",
            "light or you won't be able to see.\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0x8)
    Return()

    # Function_4_228 end

    def Function_5_2B1(): pass

    label("Function_5_2B1")

    TalkBegin(0x9)

    ChrTalk(    #2
        0xFE,
        (
            "That gentleman with you seems\x01",
            "to have drunk a lot. Is he going\x01",
            "to be all right?\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #3
        0xFE,
        (
            "If you would like, I can bring\x01",
            "you some water.\x02",
        )
    )

    C

    TalkEnd(0x9)
    Return()

    # Function_5_2B1 end

    def Function_6_341(): pass

    label("Function_6_341")

    TalkBegin(0xB)

    ChrTalk(    #4
        0xFE,
        "Good evening.\x02",
    )

    CloseMessageWindow()

    ChrTalk(    #5
        0xFE,
        (
            "Seeing another group of lodgers\x01",
            "is something I enjoy.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #6
        0xFE,
        (
            "I'd love to keep company with\x01",
            "you if that would be all right.\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0xB)
    Return()

    # Function_6_341 end

    def Function_7_3D9(): pass

    label("Function_7_3D9")

    TalkBegin(0xC)

    ChrTalk(    #7
        0xFE,
        (
            "My mother seems to be\x01",
            "enjoying the atmosphere.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #8
        0xFE,
        (
            "I was the first person to recommend\x01",
            "this inn to my mother.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #9
        0xFE,
        (
            "Now she invites me to come\x01",
            "here with her every year.\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0xC)
    Return()

    # Function_7_3D9 end

    def Function_8_48E(): pass

    label("Function_8_48E")

    TalkBegin(0xA)
    Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_63C")
    OP_A2(0x0)
    SetMessageWindowPos(72, 320, 56, 3)
    FadeToDark(300, 0, 100)

    AnonymousTalk(    #10
        "\x07\x05Lloyd is staring at an open map. It appears to be a map of Valleria Lake.\x02",
    )

    CloseMessageWindow()
    OP_56(0x0)
    FadeToBright(300, 0)

    ChrTalk(    #11
        0xFE,
        (
            "There are hardly any structures\x01",
            "on the west side, and I didn't get\x01",
            "many bites either.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #12
        0xFE,
        (
            "And all I'm getting on the east\x01",
            "side are small sized fish.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #13
        0xFE,
        (
            "The Guardian probably won't appear\x01",
            "in either of these two places...\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #14
        0xFE,
        (
            "I guess the best thing I can\x01",
            "do is to continue fishing\x01",
            "from the shore.\x02",
        )
    )

    CloseMessageWindow()
    Jump("loc_677")

    label("loc_63C")

    ChrTalk(    #15
        0xFE,
        (
            "I'm going to catch the Guardian this\x01",
            "time for sure...\x02",
        )
    )

    CloseMessageWindow()

    label("loc_677")

    TalkEnd(0xA)
    Return()

    # Function_8_48E end

    def Function_9_67B(): pass

    label("Function_9_67B")

    TalkBegin(0xD)

    ChrTalk(    #16
        0xFE,
        (
            "Ugh... Schera...please...\x01",
            "I can't take another...\x02",
        )
    )

    CloseMessageWindow()
    TalkEnd(0xD)
    Return()

    # Function_9_67B end

    def Function_10_6B9(): pass

    label("Function_10_6B9")

    ClearMapFlags(0x1)
    EventBegin(0x0)
    AddParty(0x2, 0xFF)
    SetChrPos(0x101, 107680, 0, 5310, 90)
    SetChrPos(0x103, 109180, 0, 6400, 180)
    SetChrPos(0x102, 107620, 0, 6630, 135)
    OP_6D(107890, 0, 13120, 0)
    OP_A2(0x34E)
    OP_28(0x38, 0x1, 0x80)
    FadeToBright(2000, 0)
    OP_6D(109120, 0, 5740, 3000)

    ChrTalk(    #17
        0xE,
        (
            "#038F#6POhhh... Uggghhh...\x02\x03",

            "Uhhh... Gehhh...\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #18
        0x101,
        (
            "#007F#6POh, he's totally plastered.\x02\x03",

            "It looks like even a guy who takes his\x01",
            "sweet time for everything couldn't stand\x01",
            "up to a drunken Schera.\x02",
        )
    )

    CloseMessageWindow()
    OP_62(0x103, 0x0, 2000, 0x26, 0x27, 0xFA, 0x2)
    Sleep(1200)

    ChrTalk(    #19
        0x103,
        (
            "#021F#6POh, wow. What a night of drinking.\x02\x03",

            "I've been so busy lately I haven't\x01",
            "been able to enjoy myself like\x01",
            "this for a while.\x02",
        )
    )

    CloseMessageWindow()
    TurnDirection(0x102, 0x103, 200)

    ChrTalk(    #20
        0x102,
        (
            "#017FAnd you're not even red in the\x01",
            "face either from all that alcohol...\x02\x03",

            "#018FAre you sure you haven't had\x01",
            "some special kind of training,\x01",
            "Schera?\x02",
        )
    )

    CloseMessageWindow()
    TurnDirection(0x103, 0x102, 400)

    ChrTalk(    #21
        0x103,
        (
            "#020F#6PUm, it could have been all the\x01",
            "bizarre liquors I drank while\x01",
            "I was in the troupe.\x02\x03",

            "You know, like the ones with\x01",
            "scorpions and asps in them.\x02\x03",

            "#021FI might have built up my resistance\x01",
            "that way, but who knows.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #22
        0x102,
        (
            "#017FSomehow...I don't think that that's\x01",
            "the case.\x02",
        )
    )

    CloseMessageWindow()
    TurnDirection(0x101, 0x103, 400)

    ChrTalk(    #23
        0x101,
        (
            "#009F#6PBy the way, what do you plan on\x01",
            "doing with him? He's pretty much\x01",
            "useless as he is.\x02",
        )
    )

    CloseMessageWindow()
    TurnDirection(0x103, 0x101, 400)

    ChrTalk(    #24
        0x103,
        (
            "#026F#6PLet's just let him sleep. He looks\x01",
            "so peaceful now, and we wouldn't\x01",
            "want to disturb him.\x02\x03",

            "#022FThere's a very high possibility\x01",
            "that we'll have a direct encounter\x01",
            "with the sky bandits tonight.\x02\x03",

            "And getting a civilian wrapped up\x01",
            "in the middle of it all wouldn't\x01",
            "be a good idea.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #25
        0x101,
        (
            "#004F#6PDon't tell me you...\x02\x03",

            "You got Olivier drunk so he wouldn't\x01",
            "be able to come along, didn't you?\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #26
        0x103,
        (
            "#023F#6PWell...\x02\x03",

            "...\x02\x03",

            "#021FOf course I did. And he'll thank\x01",
            "me in the long run, too. After\x01",
            "his raging hangover, anyway...\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #27
        0x101,
        "#509F#6PAnd so that whole time...\x02",
    )

    CloseMessageWindow()

    ChrTalk(    #28
        0x102,
        (
            "#018FYou were just toying with him,\x01",
            "weren't you?\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #29
        0x103,
        (
            "#026F#6PLet's see... It's getting late.\x02\x03",

            "Let's hurry and begin our stakeout\x01",
            "around the inn.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #30
        0x101,
        (
            "#507F#6PDon't skirt around the issue,\x01",
            "Schera.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #31
        0x103,
        (
            "#022F#6PQuiet, you!\x02\x03",

            "For the time being, we're going\x01",
            "to circle up to the far pier.\x02",
        )
    )

    CloseMessageWindow()

    ChrTalk(    #32
        0x102,
        "#010FUnderstood.\x02",
    )

    CloseMessageWindow()

    ChrTalk(    #33
        0x101,
        "#006F#6PAll right then, let's go!\x02",
    )

    CloseMessageWindow()
    FadeToDark(1000, 0, -1)
    OP_0D()
    SetChrPos(0x101, 107480, 0, 9560, 0)
    SetChrPos(0x103, 107480, 0, 9560, 0)
    SetChrPos(0x102, 107480, 0, 9560, 0)
    OP_6D(107480, 0, 9560, 0)
    Sleep(500)
    FadeToBright(1000, 0)
    EventEnd(0x0)
    ClearMapFlags(0x10000000)
    Return()

    # Function_10_6B9 end

    def Function_11_EA8(): pass

    label("Function_11_EA8")

    FadeToDark(300, 0, 100)
    SetMessageWindowPos(72, 320, 56, 3)
    SetChrName("")

    AnonymousTalk(    #34
        "\x07\x05There are some fishing rods propped against the rack.\x02",
    )

    CloseMessageWindow()
    OP_56(0x0)
    SetMessageWindowPos(72, 320, 56, 3)
    FadeToBright(300, 0)
    TalkEnd(0xFF)
    Return()

    # Function_11_EA8 end

    SaveToFile()

Try(main)


"""

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None
	return False


def extractDescentSubs(item):
	"""

	"""
	vol, chp, frag, postfix = extractVolChapte

	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None
	return False


	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None
	return False

def extractDescentSubs(item):
	"""

	"""


return ' '.join(html.findAll(text=True))

source = "http://example.com"

html = scraperwiki.scrape(source)        #print html
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) #print soup
items = soup.findAll('item')             #print type(items) #print items[0]

article = {}

for item in items:
    article['title']         = item.find('title').text
    article['description']   = item.find('description').text
    article['url']           = item.find('link').next # wow, this worked!
    article['pubdate']       = dateutil.parser.parse(item.find('pubdate').text)
    article['lat']           = item.find('geo:lat').text
    article['long']          = item.find('geo:long').text
    article['magnitude']     = item.find('dc:subject').text

    print article
    # the sensfull thing here would be to build a func to scrape the url form here.

    scraperwiki.sqlite.save(['title'], article)
import scraperwiki
from BeautifulSoup import BeautifulSoup
import dateutil.parser
from datetime import datetime
import re

def strip_tags(html):
    return ' '.join(html.findAll(text=True))

source = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M7.xml"

html = scraperwiki.scrape(source)        #print html
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) #print soup
items = soup.findAll('item')             #print type(items) #print items[0]

article = {}

for item in items:
    article['title']         = item.find('title').text
    article['description']   = item.find('description').text
    article['url']           = item.find('link').next # wow, this worked!
    article['pubdate']       = dateutil.parser.parse(item.find('pubdate').text)
    article['lat']           = item.find('geo:lat').text
    article['long']          = item.find('geo:long').text
    article['magnitude']     = item.find('dc:subject').text

    print article
    # the sensfull thing here would be to build a func to scrape the url form here.

    scraperwiki.sqlite.save(['title'], article)


source = "http://example.com"

html = scraperwiki.scrape(source)        #print html
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) #print soup
items = soup.findAll('item')             #print type(items) #print items[0]

article = {}

for item in items:
    article['title']         = item.find('title').text
    article['description']   = item.find('description').text
    article['url']           = item.find('link').next # wow, this worked!
    article['pubdate']       = dateutil.parser.parse(item.find('pubdate').text)
    article['lat']           = item.find('geo:lat').text
    article['long']          = item.find('geo:long').text
    article['magnitude']     = item.find('dc:subject').text

    print article
    # the sensfull thing here would be to build a func to scrape the url form here.

    scraperwiki.sqlite.save(['title'], article)
import scraperwiki
from BeautifulSoup import BeautifulSoup
import dateutil.parser
from datetime import datetime
import re

def strip_tags(html):
    return ' '.join(html.findAll(text=True))

source = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M7.xml"

html = scraperwiki.scrape(source)        #print html
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) #print soup
items = soup.findAll('item')             #print type(items) #print items[0]

article = {}

for item in items:
    article['title']         = item.find('title').text
    article['description']   = item.find('description').text
    article['url']           = item.find('link').next # wow, this worked!
    article['pubdate']       = dateutil.parser.parse(item.find('pubdate').text)
    article['lat']           = item.find('geo:lat').text
    article['long']          = item.find('geo:long').text
    article['magnitude']     = item.find('dc:subject').text

    print article
    # the sensfull thing here would be to build a func to scrape the url form here.

    scraperwiki.sqlite.save(['title'], article)


import scraperwiki
from BeautifulSoup import BeautifulSoup
import dateutil.parser
from datetime import datetime
import re

def strip_tags(html):
    return ' '.join(html.findAll(text=True))

source = "http://example.com"

html = scraperwiki.scrape(source)        #print html
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) #print soup
items = soup.findAll('item')             #print type(items) #print items[0]

article = {}

for item in items:
    article['title']         = item.find('title').text
    article['description']   = item.find('description').text
    article['url']           = item.find('link').next # wow, this worked!
    article['pubdate']       = dateutil.parser.parse(item.find('pubdate').text)
    article['lat']           = item.find('geo:lat').text
    article['long']          = item.find('geo:long').text
    article['magnitude']     = item.find('dc:subject').text

    print article
    # the sensfull thing here would be to build a func to scrape the url form here.

    scraperwiki.sqlite.save(['title'], article)
import scraperwiki
from BeautifulSoup import BeautifulSoup
import dateutil.parser
from datetime import datetime
import re

def strip_tags(html):
    return ' '.join(h

source = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M7.xml"

html = scraperwiki.scrape(source)        #print html
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) #print soup
items = soup.findAll('item')             #print type(items) #print items[0]

article = {}

for item in items:
    article['title']         = item.find('title').text
    article['description']   = item.find('description').text
    article['url']           = item.find('link').next # wow, this worked!
    article['pubdate']       = dateutil.parser.parse(item.find('pubdate').text)
    article['lat']           = item.find('geo:lat').text
    article['long']          = item.find('geo:long').text
    article['magnitude']     = item.find('dc:subject').text

    print article
    # the sensfull thing here would be to build a func to scrape the url form here.

    scraperwiki.sqlite.save(['title'], article)


import logging

import flask
from web.cache import cache
from raven.contrib.flask import Sentry
from flask_jwt_extended import JWTManager

import db
import web.api.api as api

try:
    import secrets
    _SENTRY_DSN = getattr(secrets, 'SENTRY_DSN', None)
    _JWT_SECRET = getattr(secrets, 'JWT_SECRET', None)
except ImportError:
    _SENTRY_DSN = None
    _JWT_SECRET = None

r_conn = db.util.r_conn

app = flask.Flask(__name__)
app.config.from_envvar('FLASK_CONFIG')
app.register_blueprint(api.api)
cache.init_app(app)
app.config['JWT_SECRET_KEY'] = _JWT_SECRET
jwt = JWTManager(app)
# Initialize the Sentry plugin
Sentry(app, dsn=_SENTRY_DSN)

# Add logging handlers on the production server.
if app.config['ENV'] == 'prod':
    from logging.handlers import TimedRotatingFileHandler
    logging.basicConfig(level=logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(levelname)s in'
            ' %(module)s:%(lineno)d %(message)s')

    # Log everything at the INFO level or higher to file.
    file_handler = TimedRotatingFileHandler(filename=app.config['LOG_PATH'],
            when='D')
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    logging.getLogger('').addHandler(file_handler)  # Root handler

# Catch-all route for single-page app. We specify our own `key_prefix` to
# @cache.cached instead of using the default `request.path` because this is
# a catch-all route for many different paths which all should have the same
# TODO(david): Alternatively serve this out of Nginx
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
@cache.cached(timeout=60 * 60 * 28, key_prefix='index.html')

return flask.render_template('index.html', env=app.config['ENV'])

@app.route('/crash')
def crash():
    """Throw an exception to test error logging."""
    class WhatIsTorontoError(Exception):
        pass

    logging.warn("Crashing because you want me to (hit /crash)")
    raise WhatIsTorontoError("OH NOES we've crashed!!!!!!!!!! /crash was hit")

if __name__ == '__main__':
    app.debug = True
    app.run(port=5001)


import logging

import flask
from web.cache import cache
from raven.contrib.flask import Sentry
from flask_jwt_extended import JWTManager

import db
import web.api.api as api

try:
    import secrets
    _SENTRY_DSN = getattr(secrets, 'SENTRY_DSN', None)
    _JWT_SECRET = getattr(secrets, 'JWT_SECRET', None)
except ImportError:
    _SENTRY_DSN = None
    _JWT_SECRET = None

r_conn = db.util.r_conn

app = flask.Flask(__name__)
app.config.from_envvar('FLASK_CONFIG')
app.register_blueprint(api.api)
cache.init_app(app)
app.config['JWT_SECRET_KEY'] = _JWT_SECRET
jwt = JWTManager(app)
# Initialize the Sentry plugin
Sentry(app, dsn=_SENTRY_DSN)

# Add logging handlers on the production server.
if app.config['ENV'] == 'prod':
    from logging.handlers import TimedRotatingFileHandler
    logging.basicConfig(level=logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(levelname)s in'
            ' %(module)s:%(lineno)d %(message)s')

    # Log everything at the INFO level or higher to file.
    file_handler = TimedRotatingFileHandler(filename=app.config['LOG_PATH'],
            when='D')
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    logging.getLogger('').addHandler(file_handler)  # Root handler

# Catch-all route for single-page app. We specify our own `key_prefix` to
# @cache.cached instead of using the default `request.path` because this is
# a catch-all route for many different paths which all should have the same
# TODO(david): Alternatively serve this out of Nginx
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
@cache.cached(timeout=60 * 60 * 28, key_prefix='index.html')
def index(path):

@app.route('/crash')
def crash():
    """Throw an exception to test error logging."""
    class WhatIsTorontoError(Exception):
        pass

    logging.warn("Crashing because you want me to (hit /crash)")
    raise WhatIsTorontoError("OH NOES we've crashed!!!!!!!!!! /crash was hit")

if __name__ == '__main__':
    app.debug = True
    app.run(port=5001)


import logging

import flask
from web.cache import cache
from raven.contrib.flask import Sentry
from flask_jwt_extended import JWTManager

import db
import web.api.api as api

try:
    import secrets
    _SENTRY_DSN = getattr(secrets, 'SENTRY_DSN', None)
    _JWT_SECRET = getattr(secrets, 'JWT_SECRET', None)
except ImportError:
    _SENTRY_DSN = None
    _JWT_SECRET = None

r_conn = db.util.r_conn

app = flask.Flask(__name__)
app.config.from_envvar('FLASK_CONFIG')
app.register_blueprint(api.api)
cache.init_app(app)
app.config['JWT_SECRET_KEY'] = _JWT_SECRET
jwt = JWTManager(app)
# Initialize the Sentry plugin
Sentry(app, dsn=_SENTRY_DSN)

# Add logging handlers on the production server.
if app.config['ENV'] == 'prod':
    from logging.handlers import TimedRotatingFileHandler
    logging.basicConfig(level=logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(levelname)s in'
            ' %(module)s:%(lineno)d %(message)s')

    # Log everything at the INFO level or higher to file.
    file_handler = TimedRotatingFileHandler(filename=app.config['LOG_PATH'],
            when='D')
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    logging.getLogger('').addHandler(file_handler)  # Root handler

# Catch-all route for single-page app. We specify our own `key_prefix` to
# @cache.cached instead of using the default `request.path` because this is
# a catch-all route for many different paths which all should have the same
# TODO(david): Alternatively serve this out of Nginx
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
@cache.cached(timeout=60 * 60 * 28, key_prefix='index.html')
def index(path):
    return flask.render_template('index.html', env=


    class WhatIsTorontoError(Exception):
        pass

    logging.warn("Crashing because you want me to (hit /crash)")
    raise WhatIsTorontoError("OH NOES we've crashed!!!!!!!!!! /crash was hit")

import logging

import flask
from web.cache import cache
from raven.contrib.flask import Sentry
from flask_jwt_extended import JWTManager

import db
import web.api.api as api

try:
    import secrets
    _SENTRY_DSN = getattr(secrets, 'SENTRY_DSN', None)
    _JWT_SECRET = getattr(secrets, 'JWT_SECRET', None)
except ImportError:
    _SENTRY_DSN = None
    _JWT_SECRET = None

r_conn = db.util.r_conn

app = flask.Flask(__name__)
app.config.from_envvar('FLASK_CONFIG')
app.register_blueprint(api.api)
cache.init_app(app)
app.config['JWT_SECRET_KEY'] = _JWT_SECRET
jwt = JWTManager(app)
# Initialize the Sentry plugin
Sentry(app, dsn=_SENTRY_DSN)

# Add logging handlers on the production server.
if app.config['ENV'] == 'prod':
    from logging.handlers import TimedRotatingFileHandler
    logging.basicConfig(level=logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(levelname)s in'
            ' %(module)s:%(lineno)d %(message)s')

    # Log everything at the INFO level or higher to file.
    file_handler = TimedRotatingFileHandler(filename=app.config['LOG_PATH'],
            when='D')
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    logging.getLogger('').addHandler(file_handler)  # Root handler

# Catch-all route for single-page app. We specify our own `key_prefix` to
# @cache.cached instead of using the default `request.path` because this is
# a catch-all route for many different paths which all should have the same
# TODO(david): Alternatively serve this out of Nginx
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
@cache.cached(timeout=60 * 60 * 28, key_prefix='index.html')
def index(path):
    return flask.render_template('index.html', env=app.config['ENV'])

@app.route('/crash')
def crash():
    """Throw an exception to test error logging."""

if __name__ == '__main__':
    app.debug = True
    app.run(port=5001)


try:
    import secrets
    _SENTRY_DSN = getattr(secrets, 'SENTRY_DSN', None)
    _JWT_SECRET = getattr(secrets, 'JWT_SECRET', None)
except ImportError:
    _SENTRY_DSN = None
    _JWT_SECRET = None

import logging

import flask
from web.cache import cache
from raven.contrib.flask import Sentry
from flask_jwt_extended import JWTManager

import db
import web.api.api as api

r_conn = db.util.r_conn

app = flask.Flask(__name__)
app.config.from_envvar('FLASK_CONFIG')
app.register_blueprint(api.api)
cache.init_app(app)
app.config['JWT_SECRET_KEY'] = _JWT_SECRET
jwt = JWTManager(app)
# Initialize the Sentry plugin
Sentry(app, dsn=_SENTRY_DSN)

# Add logging handlers on the production server.
if app.config['ENV'] == 'prod':
    from logging.handlers import TimedRotatingFileHandler
    logging.basicConfig(level=logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(levelname)s in'
            ' %(module)s:%(lineno)d %(message)s')

    # Log everything at the INFO level or higher to file.
    file_handler = TimedRotatingFileHandler(filename=app.config['LOG_PATH'],
            when='D')
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    logging.getLogger('').addHandler(file_handler)  # Root handler

# Catch-all route for single-page app. We specify our own `key_prefix` to
# @cache.cached instead of using the default `request.path` because this is
# a catch-all route for many different paths which all should have the same
# TODO(david): Alternatively serve this out of Nginx
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
@cache.cached(timeout=60 * 60 * 28, key_prefix='index.html')
def index(path):
    return flask.render_template('index.html', env=app.config['ENV'])

@app.route('/crash')
def crash():
    """Throw an exception to test error logging."""
    class WhatIsTorontoError(Exception):
        pass

    logging.warn("Crashing because you want me to (hit /crash)")
    raise WhatIsTorontoError("OH NOES we've crashed!!!!!!!!!! /crash was hit")

if __name__ == '__main__':
    app.debug = True
    app.run(port=5001)


def validate_transaction(self, transaction: SignedTransactionAPI) -> None:

from typing import Type

from eth.abc import (
    ComputationAPI,
    SignedTransactionAPI,
)
from eth.vm.forks.frontier.state import (
    FrontierState,
    FrontierTransactionExecutor,
)

from .computation import HomesteadComputation
from .validation import validate_homestead_transaction

class HomesteadState(FrontierState):
    computation_class: Type[ComputationAPI] = HomesteadComputation

validate_homestead_transaction(self, transaction)

class HomesteadTransactionExecutor(FrontierTransactionExecutor):
    pass


from typing import Type

from eth.abc import (
    ComputationAPI,
    SignedTransactionAPI,
)
from eth.vm.forks.frontier.state import (
    FrontierState,
    FrontierTransactionExecutor,
)

from .computation import HomesteadComputation
from .validation import validate_homestead_transaction

class HomesteadState(FrontierState):
    computation_class: Type[ComputationAPI] = HomesteadComputation

    def validate_transaction(self, transaction: SignedTransactionAPI) -> None:

class HomesteadTransactionExecutor(FrontierTransactionExecutor):
    pass


from typing import Type

from eth.abc import (
    ComputationAPI,
    SignedTransactionAPI,
)
from eth.vm.forks.frontier.state import (
    FrontierState,
    FrontierTransactionExecutor,
)

from .computation import HomesteadComputation
from .validation import validate_homestead_transaction

class HomesteadState(FrontierState):
    computation_class: Type[ComputationAPI] = HomesteadComputation

    def validate_transaction(self, transaction: SignedTransactionAPI) -> None:
        validate_homestead_transaction(self, tra


async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:

"""Support for Modbus Register sensors."""
from __future__ import annotations

from datetime import datetime
from typing import Any

from homeassistant.components.sensor import CONF_STATE_CLASS, SensorEntity
from homeassistant.const import CONF_NAME, CONF_SENSORS, CONF_UNIT_OF_MEASUREMENT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import get_hub
from .base_platform import BaseStructPlatform
from .modbus import ModbusHub

PARALLEL_UPDATES = 1

"""Set up the Modbus sensors."""
    sensors = []

    if discovery_info is None:  # pragma: no cover
        return

    for entry in discovery_info[CONF_SENSORS]:
        hub = get_hub(hass, discovery_info[CONF_NAME])
        sensors.append(ModbusRegisterSensor(hub, entry))

    async_add_entities(sensors)

class ModbusRegisterSensor(BaseStructPlatform, RestoreEntity, SensorEntity):
    """Modbus register sensor."""

    def __init__(
        self,
        hub: ModbusHub,
        entry: dict[str, Any],
    ) -> None:
        """Initialize the modbus register sensor."""
        super().__init__(hub, entry)
        self._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)
        self._attr_state_class = entry.get(CONF_STATE_CLASS)

    async def async_added_to_hass(self) -> None:
        """Handle entity which will be added."""
        await self.async_base_added_to_hass()
        if state := await self.async_get_last_state():
            self._attr_native_value = state.state

    async def async_update(self, now: datetime | None = None) -> None:
        """Update the state of the sensor."""
        # remark "now" is a dummy parameter to avoid problems with
        result = await self._hub.async_pymodbus_call(
            self._slave, self._address, self._count, self._input_type
        )
        if result is None:
            if self._lazy_errors:
                self._lazy_errors -= 1
                return
            self._lazy_errors = self._lazy_error_count
            self._attr_available = False
            self.async_write_ha_state()
            return

        self._attr_native_value = self.unpack_structure_result(result.registers)
        if self._attr_native_value is None:
            self._attr_available = False
        else:
            self._attr_available = True
        self._lazy_errors = self._lazy_error_count
        self.async_write_ha_state()


"""Initialize the modbus register sensor."""
        super().__init__(hub, entry)
        self._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)
        self._attr_state_class = entry.get(CONF_STATE_CLASS)

"""Support for Modbus Register sensors."""
from __future__ import annotations

from datetime import datetime
from typing import Any

from homeassistant.components.sensor import CONF_STATE_CLASS, SensorEntity
from homeassistant.const import CONF_NAME, CONF_SENSORS, CONF_UNIT_OF_MEASUREMENT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import get_hub
from .base_platform import BaseStructPlatform
from .modbus import ModbusHub

PARALLEL_UPDATES = 1

async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Modbus sensors."""
    sensors = []

    if discovery_info is None:  # pragma: no cover
        return

    for entry in discovery_info[CONF_SENSORS]:
        hub = get_hub(hass, discovery_info[CONF_NAME])
        sensors.append(ModbusRegisterSensor(hub, entry))

    async_add_entities(sensors)

class ModbusRegisterSensor(BaseStructPlatform, RestoreEntity, SensorEntity):
    """Modbus register sensor."""

    def __init__(
        self,
        hub: ModbusHub,
        entry: dict[str, Any],
    ) -> None:

    async def async_added_to_hass(self) -> None:
        """Handle entity which will be added."""
        await self.async_base_added_to_hass()
        if state := await self.async_get_last_state():
            self._attr_native_value = state.state

    async def async_update(self, now: datetime | None = None) -> None:
        """Update the state of the sensor."""
        # remark "now" is a dummy parameter to avoid problems with
        result = await self._hub.async_pymodbus_call(
            self._slave, self._address, self._count, self._input_type
        )
        if result is None:
            if self._lazy_errors:
                self._lazy_errors -= 1
                return
            self._lazy_errors = self._lazy_error_count
            self._attr_available = False
            self.async_write_ha_state()
            return

        self._attr_native_value = self.unpack_structure_result(result.registers)
        if self._attr_native_value is None:
            self._attr_available = False
        else:
            self._attr_available = True
        self._lazy_errors = self._lazy_error_count
        self.async_write_ha_state()


"""Support for Modbus Register sensors."""
from __future__ import annotations

from datetime import datetime
from typing import Any

from homeassistant.components.sensor import CONF_STATE_CLASS, SensorEntity
from homeassistant.const import CONF_NAME, CONF_SENSORS, CONF_UNIT_OF_MEASUREMENT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import get_hub
from .base_platform import BaseStructPlatform
from .modbus import ModbusHub

PARALLEL_UPDATES = 1

async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Modbus sensors."""
    sensors = []

    if discovery_info is None:  # pragma: no cover
        return

    for entry in discovery_info[CONF_SENSORS]:
        hub = get_hub(hass, discovery_info[CONF_NAME])
        sensors.append(ModbusRegisterSensor(hub, entry))

    async_add_entities(sensors)

class ModbusRegisterSensor(BaseStructPlatform, RestoreEntity, SensorEntity):
    """Modbus register sensor."""

    def __init__(
        self,
        hub: ModbusHub,
        entry: dict[str, Any],
    ) -> None:
        """Initialize the modbus register sensor."""
        super().__init__(hub, entry)
        self._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)
        self._attr_state_class = entry.get(CONF_STATE_CLASS)

    async def async_added_to_hass(self) -> None:
        """Handle entity which will be added."""
        await self.async_base_added_to_hass()
        if state := await self.async_get_last_state():
            self._attr_native_value = state.state

    async def async_update(self, now: datetime | None = None) -> None:
        """Update the state of the sensor."""
        # remark "now" is a dummy parameter to avoid problems with
        result = await self._hub.async_pymodbus_call(
            self._slave, self._address, self._count, self._input_type
        )
        if result is None:
            if self._lazy_errors:
                self._lazy_errors -= 1
                return
            self._lazy_errors = self._lazy_error_count
            self._attr_available = False
            self.async_write_ha_state()
            return

        self._attr_native_value = self.unpack_structure_result(result.registers)
        if self._attr_native_value is None:
            self._attr_available = False
        else:
            self._attr_available = True
        self._lazy_errors = self


        await self.async_base_added_to_hass()
        if state := await self.async_get_last_state():
            self._attr_native_value = state.state

"""Support for Modbus Register sensors."""
from __future__ import annotations

from datetime import datetime
from typing import Any

from homeassistant.components.sensor import CONF_STATE_CLASS, SensorEntity
from homeassistant.const import CONF_NAME, CONF_SENSORS, CONF_UNIT_OF_MEASUREMENT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import get_hub
from .base_platform import BaseStructPlatform
from .modbus import ModbusHub

PARALLEL_UPDATES = 1

async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Modbus sensors."""
    sensors = []

    if discovery_info is None:  # pragma: no cover
        return

    for entry in discovery_info[CONF_SENSORS]:
        hub = get_hub(hass, discovery_info[CONF_NAME])
        sensors.append(ModbusRegisterSensor(hub, entry))

    async_add_entities(sensors)

class ModbusRegisterSensor(BaseStructPlatform, RestoreEntity, SensorEntity):
    """Modbus register sensor."""

    def __init__(
        self,
        hub: ModbusHub,
        entry: dict[str, Any],
    ) -> None:
        """Initialize the modbus register sensor."""
        super().__init__(hub, entry)
        self._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)
        self._attr_state_class = entry.get(CONF_STATE_CLASS)

    async def async_added_to_hass(self) -> None:
        """Handle entity which will be added."""

    async def async_update(self, now: datetime | None = None) -> None:
        """Update the state of the sensor."""
        # remark "now" is a dummy parameter to avoid problems with
        result = await self._hub.async_pymodbus_call(
            self._slave, self._address, self._count, self._input_type
        )
        if result is None:
            if self._lazy_errors:
                self._lazy_errors -= 1
                return
            self._lazy_errors = self._lazy_error_count
            self._attr_available = False
            self.async_write_ha_state()
            return

        self._attr_native_value = self.unpack_structure_result(result.registers)
        if self._attr_native_value is None:
            self._attr_available = False
        else:
            self._attr_available = True
        self._lazy_errors = self._lazy_error_count
        self.async_write_ha_state()


for entry in discovery_info[CONF_SENSORS]:
        hub = get_hub(hass, discovery_info[CONF_NAME])
        sensors.append(ModbusRegisterSensor(hub, entry))

"""Support for Modbus Register sensors."""
from __future__ import annotations

from datetime import datetime
from typing import Any

from homeassistant.components.sensor import CONF_STATE_CLASS, SensorEntity
from homeassistant.const import CONF_NAME, CONF_SENSORS, CONF_UNIT_OF_MEASUREMENT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import get_hub
from .base_platform import BaseStructPlatform
from .modbus import ModbusHub

PARALLEL_UPDATES = 1

async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Modbus sensors."""
    sensors = []

    if discovery_info is None:  # pragma: no cover
        return

    async_add_entities(sensors)

class ModbusRegisterSensor(BaseStructPlatform, RestoreEntity, SensorEntity):
    """Modbus register sensor."""

    def __init__(
        self,
        hub: ModbusHub,
        entry: dict[str, Any],
    ) -> None:
        """Initialize the modbus register sensor."""
        super().__init__(hub, entry)
        self._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)
        self._attr_state_class = entry.get(CONF_STATE_CLASS)

    async def async_added_to_hass(self) -> None:
        """Handle entity which will be added."""
        await self.async_base_added_to_hass()
        if state := await self.async_get_last_state():
            self._attr_native_value = state.state

    async def async_update(self, now: datetime | None = None) -> None:
        """Update the state of the sensor."""
        # remark "now" is a dummy parameter to avoid problems with
        result = await self._hub.async_pymodbus_call(
            self._slave, self._address, self._count, self._input_type
        )
        if result is None:
            if self._lazy_errors:
                self._lazy_errors -= 1
                return
            self._lazy_errors = self._lazy_error_count
            self._attr_available = False
            self.async_write_ha_state()
            return

        self._attr_native_value = self.unpack_structure_result(result.registers)
        if self._attr_native_value is None:
            self._attr_available = False
        else:
            self._attr_available = True
        self._lazy_errors = self._lazy_error_count
        self.async_write_ha_state()


import ivy

class Param:

    def __init__(self, ptype, tree_depth, shape=None):
        self._count = 0
        self._ptype = ptype
        self._tree_depth = tree_depth
        self._param_stack = list()
        self._shape = tuple(shape) if ivy.exists(shape) else None

    def set(self, val):
        self._param_stack = [val]*self._count

self._count = count

    def get(self):
        return self._param_stack.pop()

    def __repr__(self):
        return '<Param, type={}, depth={}, count={}, current={}>'.format(
            self._ptype, self._tree_depth, self._count, len(self._param_stack))

    def __len__(self):
        return len(self._param_stack)

    @property
    def count(self):
        return self._count

    @property
    def depth(self):
        return self._tree_depth

    @property
    def ptype(self):
        return self._ptype

    @property
    def shape(self):
        return self._shape


import ivy

class Param:

    def __init__(self, ptype, tree_depth, shape=None):
        self._count = 0
        self._ptype = ptype
        self._tree_depth = tree_depth
        self._param_stack = list()
        self._shape = tuple(shape) if ivy.exists(shape) else None

    def set(self, val):
        self._param_stack = [val]*self._count

    def set_count(self, count):
        self._count = count

    def get(self):

    def __repr__(self):
        return '<Param, type={}, depth={}, count={}, current={}>'.format(
            self._ptype, self._tree_depth, self._count, len(self._param_stack))

    def __len__(self):
        return len(self._param_stack)

    @property
    def count(self):
        return self._count

    @property
    def depth(self):
        return self._tree_depth

    @property
    def ptype(self):
        return self._ptype

    @property
    def shape(self):
        return self._shape


import ivy

class Param:

    def __init__(self, ptype, tree_depth, shape=None):
        self._count = 0
        self._ptype = ptype
        self._tree_depth = tree_depth
        self._param_stack = list()
        self._shape = tuple(shape) if ivy.exists(shape) else None

    def set(self, val):
        self._param_stack = [val]*self._count

    def set_count(self, count):
        self._count = count

    def get(self):
        return self._param_stack.pop()

    def __repr__(self):
        return '<Param, type={}, depth={}, count={}, current={}>'.format(
            self._ptype, self._tree_depth, self._count, len(self._param_stack))

    def __len__(self):
        return len(self._param_stack)

    @property
    def count(self):
        return self._count

    @property
    def depth(self):
        return self._tree_depth

    @property
    def ptype(self):
        return self._ptype

    @property
    def shape(self):
        retur


def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):

"""distutils.unixccompiler

Contains the UnixCCompiler class, a subclass of CCompiler that handles
the "typical" Unix-style command-line C compiler:
  * macros defined with -Dname[=value]
  * macros undefined with -Uname
  * include search directories specified with -Idir
  * libraries specified with -lllib
  * library search directories specified with -Ldir
  * compile handled by 'cc' (or similar) executable with -c option:
    compiles .c to .o
  * link static library handled by 'ar' command (possibly with 'ranlib')
  * link shared library handled by 'cc -shared'
"""

import os, sys, re

from distutils import sysconfig
from distutils.dep_util import newer
from distutils.ccompiler import \
     CCompiler, gen_preprocess_options, gen_lib_options
from distutils.errors import \
     DistutilsExecError, CompileError, LibError, LinkError
from distutils import log

if sys.platform == 'darwin':
    import _osx_support

# XXX Things not currently handled:
#   * optimization/debug/warning flags; we just use whatever's in Python's
#     Makefile and live with it.  Is this adequate?  If not, we might
#     have to have a bunch of subclasses GNUCCompiler, SGICCompiler,
#     SunCCompiler, and I suspect down that road lies madness.
#   * even if we don't know a warning flag from an optimization flag,
#     we need some way for outsiders to feed preprocessor/compiler/linker
#     flags in to us -- eg. a sysadmin might want to mandate certain flags
#     via a site config file, or a user might want to set something for
#     compiling this module distribution only via the setup.py command
#     line, whatever.  As long as these options come from something on the
#     current system, they can be as system-dependent as they like, and we
#     should just happily stuff them into the preprocessor/compiler/linker
#     options and carry on.

class UnixCCompiler(CCompiler):

    compiler_type = 'unix'

    # These are used by CCompiler in two places: the constructor sets
    # 'set_executable()' allows any of these to be set.  The defaults here
    # are pretty generic; they will probably have to be set by an outsider
    # (eg. using information discovered by the sysconfig about building
    executables = {'preprocessor' : None,
                   'compiler'     : ["cc"],
                   'compiler_so'  : ["cc"],
                   'compiler_cxx' : ["cc"],
                   'linker_so'    : ["cc", "-shared"],
                   'linker_exe'   : ["cc"],
                   'archiver'     : ["ar", "-cr"],
                   'ranlib'       : None,
                  }

    if sys.platform[:6] == "darwin":
        executables['ranlib'] = ["ranlib"]

    # Needed for the filename generation methods provided by the base
    # class, CCompiler.  NB. whoever instantiates/uses a particular
    # UnixCCompiler instance should set 'shared_lib_ext' -- we set a
    # reasonable common default here, but it's not necessarily used on all

    src_extensions = [".c",".C",".cc",".cxx",".cpp",".m"]
    obj_extension = ".o"
    static_lib_extension = ".a"
    shared_lib_extension = ".so"
    dylib_lib_extension = ".dylib"
    xcode_stub_lib_extension = ".tbd"
    static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
    xcode_stub_lib_format = dylib_lib_format
    if sys.platform == "cygwin":
        exe_extension = ".exe"

    def preprocess(self, source, output_file=None, macros=None,
                   include_dirs=None, extra_preargs=None, extra_postargs=None):
        fixed_args = self._fix_compile_args(None, macros, include_dirs)
        ignore, macros, include_dirs = fixed_args
        pp_opts = gen_preprocess_options(macros, include_dirs)
        pp_args = self.preprocessor + pp_opts
        if output_file:
            pp_args.extend(['-o', output_file])
        if extra_preargs:
            pp_args[:0] = extra_preargs
        if extra_postargs:
            pp_args.extend(extra_postargs)
        pp_args.append(source)

        # We need to preprocess: either we're being forced to, or we're
        # generating output to stdout, or there's a target output file and
        # the source file is newer than the target (or the target doesn't
        if self.force or output_file is None or newer(source, output_file):
            if output_file:
                self.mkpath(os.path.dirname(output_file))
            try:
                self.spawn(pp_args)
            except DistutilsExecError as msg:
                raise CompileError(msg)

compiler_so = self.compiler_so
        if sys.platform == 'darwin':
            compiler_so = _osx_support.compiler_fixup(compiler_so,
                                                    cc_args + extra_postargs)
        try:
            self.spawn(compiler_so + cc_args + [src, '-o', obj] +
                       extra_postargs)
        except DistutilsExecError as msg:
            raise CompileError(msg)

    def create_static_lib(self, objects, output_libname,
                          output_dir=None, debug=0, target_lang=None):
        objects, output_dir = self._fix_object_args(objects, output_dir)

        output_filename = \
            self.library_filename(output_libname, output_dir=output_dir)

        if self._need_link(objects, output_filename):
            self.mkpath(os.path.dirname(output_filename))
            self.spawn(self.archiver +
                       [output_filename] +
                       objects + self.objects)

            # Not many Unices required ranlib anymore -- SunOS 4.x is, I
            # think the only major Unix that does.  Maybe we need some
            # platform intelligence here to skip ranlib if it's not
            # needed -- or maybe Python's configure script took care of
            # it for us, hence the check for leading colon.
            if self.ranlib:
                try:
                    self.spawn(self.ranlib + [output_filename])
                except DistutilsExecError as msg:
                    raise LibError(msg)
        else:
            log.debug("skipping %s (up-to-date)", output_filename)

    def link(self, target_desc, objects,
             output_filename, output_dir=None, libraries=None,
             library_dirs=None, runtime_library_dirs=None,
             export_symbols=None, debug=0, extra_preargs=None,
             extra_postargs=None, build_temp=None, target_lang=None):
        objects, output_dir = self._fix_object_args(objects, output_dir)
        fixed_args = self._fix_lib_args(libraries, library_dirs,
                                        runtime_library_dirs)
        libraries, library_dirs, runtime_library_dirs = fixed_args

        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
                                   libraries)
        if not isinstance(output_dir, (str, type(None))):
            raise TypeError("'output_dir' must be a string or None")
        if output_dir is not None:
            output_filename = os.path.join(output_dir, output_filename)

        if self._need_link(objects, output_filename):
            ld_args = (objects + self.objects +
                       lib_opts + ['-o', output_filename])
            if debug:
                ld_args[:0] = ['-g']
            if extra_preargs:
                ld_args[:0] = extra_preargs
            if extra_postargs:
                ld_args.extend(extra_postargs)
            self.mkpath(os.path.dirname(output_filename))
            try:
                if target_desc == CCompiler.EXECUTABLE:
                    linker = self.linker_exe[:]
                else:
                    linker = self.linker_so[:]
                if target_lang == "c++" and self.compiler_cxx:
                    # skip over environment variable settings if /usr/bin/env
                    # is used to set up the linker's environment.
                    # This is needed on OSX. Note: this assumes that the
                    # normal and C++ compiler have the same environment
                    i = 0
                    if os.path.basename(linker[0]) == "env":
                        i = 1
                        while '=' in linker[i]:
                            i += 1
                    linker[i] = self.compiler_cxx[i]

                if sys.platform == 'darwin':
                    linker = _osx_support.compiler_fixup(linker, ld_args)

                self.spawn(linker + ld_args)
            except DistutilsExecError as msg:
                raise LinkError(msg)
        else:
            log.debug("skipping %s (up-to-date)", output_filename)

    # These are all used by the 'gen_lib_options() function, in

    def library_dir_option(self, dir):
        return "-L" + dir

    def _is_gcc(self, compiler_name):
        return "gcc" in compiler_name or "g++" in compiler_name

    def runtime_library_dir_option(self, dir):
        # XXX Hackish, at the very least.  See Python bug #445902:
        # Linkers on different platforms need different options to
        # specify that directories need to be added to the list of
        # directories searched for dependencies when a dynamic library
        # is sought.  GCC on GNU systems (Linux, FreeBSD, ...) has to
        # be told to pass the -R option through to the linker, whereas
        # other compilers and gcc on other systems just know this.
        # Other compilers may need something slightly different.  At
        # this time, there's no way to determine this information from
        # the configuration data stored in the Python installation, so
        # we use this hack.
        compiler = os.path.basename(sysconfig.get_config_var("CC"))
        if sys.platform[:6] == "darwin":
            # MacOSX's linker doesn't understand the -R flag at all
            return "-L" + dir
        elif sys.platform[:7] == "freebsd":
            return "-Wl,-rpath=" + dir
        elif sys.platform[:5] == "hp-ux":
            if self._is_gcc(compiler):
                return ["-Wl,+s", "-L" + dir]
            return ["+s", "-L" + dir]
        elif sys.platform[:7] == "irix646" or sys.platform[:6] == "osf1V5":
            return ["-rpath", dir]
        else:
            if self._is_gcc(compiler):
                # gcc on non-GNU systems does not need -Wl, but can
                # use it anyway.  Since distutils has always passed in
                # -Wl whenever gcc was used in the past it is probably
                # safest to keep doing so.
                if sysconfig.get_config_var("GNULD") == "yes":
                    # GNU ld needs an extra option to get a RUNPATH
                    # instead of just an RPATH.
                    return "-Wl,--enable-new-dtags,-R" + dir
                else:
                    return "-Wl,-R" + dir
            else:
                # No idea how --enable-new-dtags would be passed on to
                # ld if this system was using GNU ld.  Don't know if a
                # system like this even exists.
                return "-R" + dir

    def library_option(self, lib):
        return "-l" + lib

    def find_library_file(self, dirs, lib, debug=0):
        shared_f = self.library_filename(lib, lib_type='shared')
        dylib_f = self.library_filename(lib, lib_type='dylib')
        xcode_stub_f = self.library_filename(lib, lib_type='xcode_stub')
        static_f = self.library_filename(lib, lib_type='static')

        if sys.platform == 'darwin':
            # On OSX users can specify an alternate SDK using
            # '-isysroot', calculate the SDK root if it is specified
            # (and use it further on)
            # Note that, as of Xcode 7, Apple SDKs may contain textual stub
            # libraries with .tbd extensions rather than the normal .dylib
            # shared libraries installed in /.  The Apple compiler tool
            # chain handles this transparently but it can cause problems
            # for programs that are being built with an SDK and searching
            # for specific libraries.  Callers of find_library_file need to
            # keep in mind that the base filename of the returned SDK library
            # file might have a different extension from that of the library
            # file installed on the running system, for example:
            #       usr/lib/libedit.tbd
            # vs
            cflags = sysconfig.get_config_var('CFLAGS')
            m = re.search(r'-isysroot\s+(\S+)', cflags)
            if m is None:
                sysroot = '/'
            else:
                sysroot = m.group(1)

        for dir in dirs:
            shared = os.path.join(dir, shared_f)
            dylib = os.path.join(dir, dylib_f)
            static = os.path.join(dir, static_f)
            xcode_stub = os.path.join(dir, xcode_stub_f)

            if sys.platform == 'darwin' and (
                dir.startswith('/System/') or (
                dir.startswith('/usr/') and not dir.startswith('/usr/local/'))):

                shared = os.path.join(sysroot, dir[1:], shared_f)
                dylib = os.path.join(sysroot, dir[1:], dylib_f)
                static = os.path.join(sysroot, dir[1:], static_f)
                xcode_stub = os.path.join(sysroot, dir[1:], xcode_stub_f)

            # We're second-guessing the linker here, with not much hard
            # data to go on: GCC seems to prefer the shared library, so I'm
            # assuming that *all* Unix C compilers do.  And of course I'm
            # ignoring even GCC's "-static" option.  So sue me.
            if os.path.exists(dylib):
                return dylib
            elif os.path.exists(xcode_stub):
                return xcode_stub
            elif os.path.exists(shared):
                return shared
            elif os.path.exists(static):
                return static

        # Oops, didn't find it in *any* of 'dirs'
        return None


compiler_so = self.compiler_so
        if sys.platform == 'darwin':
            compiler_so = _osx_support.compiler_fixup(compiler_so,
                                                    cc_args + extra_postargs)
        try:
            self.spawn(compiler_so + cc_args + [src, '-o', obj] +
                       extra_postargs)
        except DistutilsExecError as msg:
            raise CompileError(msg)

"""distutils.unixccompiler

Contains the UnixCCompiler class, a subclass of CCompiler that handles
the "typical" Unix-style command-line C compiler:
  * macros defined with -Dname[=value]
  * macros undefined with -Uname
  * include search directories specified with -Idir
  * libraries specified with -lllib
  * library search directories specified with -Ldir
  * compile handled by 'cc' (or similar) executable with -c option:
    compiles .c to .o
  * link static library handled by 'ar' command (possibly with 'ranlib')
  * link shared library handled by 'cc -shared'
"""

import os, sys, re

from distutils import sysconfig
from distutils.dep_util import newer
from distutils.ccompiler import \
     CCompiler, gen_preprocess_options, gen_lib_options
from distutils.errors import \
     DistutilsExecError, CompileError, LibError, LinkError
from distutils import log

if sys.platform == 'darwin':
    import _osx_support

# XXX Things not currently handled:
#   * optimization/debug/warning flags; we just use whatever's in Python's
#     Makefile and live with it.  Is this adequate?  If not, we might
#     have to have a bunch of subclasses GNUCCompiler, SGICCompiler,
#     SunCCompiler, and I suspect down that road lies madness.
#   * even if we don't know a warning flag from an optimization flag,
#     we need some way for outsiders to feed preprocessor/compiler/linker
#     flags in to us -- eg. a sysadmin might want to mandate certain flags
#     via a site config file, or a user might want to set something for
#     compiling this module distribution only via the setup.py command
#     line, whatever.  As long as these options come from something on the
#     current system, they can be as system-dependent as they like, and we
#     should just happily stuff them into the preprocessor/compiler/linker
#     options and carry on.

class UnixCCompiler(CCompiler):

    compiler_type = 'unix'

    # These are used by CCompiler in two places: the constructor sets
    # 'set_executable()' allows any of these to be set.  The defaults here
    # are pretty generic; they will probably have to be set by an outsider
    # (eg. using information discovered by the sysconfig about building
    executables = {'preprocessor' : None,
                   'compiler'     : ["cc"],
                   'compiler_so'  : ["cc"],
                   'compiler_cxx' : ["cc"],
                   'linker_so'    : ["cc", "-shared"],
                   'linker_exe'   : ["cc"],
                   'archiver'     : ["ar", "-cr"],
                   'ranlib'       : None,
                  }

    if sys.platform[:6] == "darwin":
        executables['ranlib'] = ["ranlib"]

    # Needed for the filename generation methods provided by the base
    # class, CCompiler.  NB. whoever instantiates/uses a particular
    # UnixCCompiler instance should set 'shared_lib_ext' -- we set a
    # reasonable common default here, but it's not necessarily used on all

    src_extensions = [".c",".C",".cc",".cxx",".cpp",".m"]
    obj_extension = ".o"
    static_lib_extension = ".a"
    shared_lib_extension = ".so"
    dylib_lib_extension = ".dylib"
    xcode_stub_lib_extension = ".tbd"
    static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
    xcode_stub_lib_format = dylib_lib_format
    if sys.platform == "cygwin":
        exe_extension = ".exe"

    def preprocess(self, source, output_file=None, macros=None,
                   include_dirs=None, extra_preargs=None, extra_postargs=None):
        fixed_args = self._fix_compile_args(None, macros, include_dirs)
        ignore, macros, include_dirs = fixed_args
        pp_opts = gen_preprocess_options(macros, include_dirs)
        pp_args = self.preprocessor + pp_opts
        if output_file:
            pp_args.extend(['-o', output_file])
        if extra_preargs:
            pp_args[:0] = extra_preargs
        if extra_postargs:
            pp_args.extend(extra_postargs)
        pp_args.append(source)

        # We need to preprocess: either we're being forced to, or we're
        # generating output to stdout, or there's a target output file and
        # the source file is newer than the target (or the target doesn't
        if self.force or output_file is None or newer(source, output_file):
            if output_file:
                self.mkpath(os.path.dirname(output_file))
            try:
                self.spawn(pp_args)
            except DistutilsExecError as msg:
                raise CompileError(msg)

    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):

    def create_static_lib(self, objects, output_libname,
                          output_dir=None, debug=0, target_lang=None):
        objects, output_dir = self._fix_object_args(objects, output_dir)

        output_filename = \
            self.library_filename(output_libname, output_dir=output_dir)

        if self._need_link(objects, output_filename):
            self.mkpath(os.path.dirname(output_filename))
            self.spawn(self.archiver +
                       [output_filename] +
                       objects + self.objects)

            # Not many Unices required ranlib anymore -- SunOS 4.x is, I
            # think the only major Unix that does.  Maybe we need some
            # platform intelligence here to skip ranlib if it's not
            # needed -- or maybe Python's configure script took care of
            # it for us, hence the check for leading colon.
            if self.ranlib:
                try:
                    self.spawn(self.ranlib + [output_filename])
                except DistutilsExecError as msg:
                    raise LibError(msg)
        else:
            log.debug("skipping %s (up-to-date)", output_filename)

    def link(self, target_desc, objects,
             output_filename, output_dir=None, libraries=None,
             library_dirs=None, runtime_library_dirs=None,
             export_symbols=None, debug=0, extra_preargs=None,
             extra_postargs=None, build_temp=None, target_lang=None):
        objects, output_dir = self._fix_object_args(objects, output_dir)
        fixed_args = self._fix_lib_args(libraries, library_dirs,
                                        runtime_library_dirs)
        libraries, library_dirs, runtime_library_dirs = fixed_args

        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
                                   libraries)
        if not isinstance(output_dir, (str, type(None))):
            raise TypeError("'output_dir' must be a string or None")
        if output_dir is not None:
            output_filename = os.path.join(output_dir, output_filename)

        if self._need_link(objects, output_filename):
            ld_args = (objects + self.objects +
                       lib_opts + ['-o', output_filename])
            if debug:
                ld_args[:0] = ['-g']
            if extra_preargs:
                ld_args[:0] = extra_preargs
            if extra_postargs:
                ld_args.extend(extra_postargs)
            self.mkpath(os.path.dirname(output_filename))
            try:
                if target_desc == CCompiler.EXECUTABLE:
                    linker = self.linker_exe[:]
                else:
                    linker = self.linker_so[:]
                if target_lang == "c++" and self.compiler_cxx:
                    # skip over environment variable settings if /usr/bin/env
                    # is used to set up the linker's environment.
                    # This is needed on OSX. Note: this assumes that the
                    # normal and C++ compiler have the same environment
                    i = 0
                    if os.path.basename(linker[0]) == "env":
                        i = 1
                        while '=' in linker[i]:
                            i += 1
                    linker[i] = self.compiler_cxx[i]

                if sys.platform == 'darwin':
                    linker = _osx_support.compiler_fixup(linker, ld_args)

                self.spawn(linker + ld_args)
            except DistutilsExecError as msg:
                raise LinkError(msg)
        else:
            log.debug("skipping %s (up-to-date)", output_filename)

    # These are all used by the 'gen_lib_options() function, in

    def library_dir_option(self, dir):
        return "-L" + dir

    def _is_gcc(self, compiler_name):
        return "gcc" in compiler_name or "g++" in compiler_name

    def runtime_library_dir_option(self, dir):
        # XXX Hackish, at the very least.  See Python bug #445902:
        # Linkers on different platforms need different options to
        # specify that directories need to be added to the list of
        # directories searched for dependencies when a dynamic library
        # is sought.  GCC on GNU systems (Linux, FreeBSD, ...) has to
        # be told to pass the -R option through to the linker, whereas
        # other compilers and gcc on other systems just know this.
        # Other compilers may need something slightly different.  At
        # this time, there's no way to determine this information from
        # the configuration data stored in the Python installation, so
        # we use this hack.
        compiler = os.path.basename(sysconfig.get_config_var("CC"))
        if sys.platform[:6] == "darwin":
            # MacOSX's linker doesn't understand the -R flag at all
            return "-L" + dir
        elif sys.platform[:7] == "freebsd":
            return "-Wl,-rpath=" + dir
        elif sys.platform[:5] == "hp-ux":
            if self._is_gcc(compiler):
                return ["-Wl,+s", "-L" + dir]
            return ["+s", "-L" + dir]
        elif sys.platform[:7] == "irix646" or sys.platform[:6] == "osf1V5":
            return ["-rpath", dir]
        else:
            if self._is_gcc(compiler):
                # gcc on non-GNU systems does not need -Wl, but can
                # use it anyway.  Since distutils has always passed in
                # -Wl whenever gcc was used in the past it is probably
                # safest to keep doing so.
                if sysconfig.get_config_var("GNULD") == "yes":
                    # GNU ld needs an extra option to get a RUNPATH
                    # instead of just an RPATH.
                    return "-Wl,--enable-new-dtags,-R" + dir
                else:
                    return "-Wl,-R" + dir
            else:
                # No idea how --enable-new-dtags would be passed on to
                # ld if this system was using GNU ld.  Don't know if a
                # system like this even exists.
                return "-R" + dir

    def library_option(self, lib):
        return "-l" + lib

    def find_library_file(self, dirs, lib, debug=0):
        shared_f = self.library_filename(lib, lib_type='shared')
        dylib_f = self.library_filename(lib, lib_type='dylib')
        xcode_stub_f = self.library_filename(lib, lib_type='xcode_stub')
        static_f = self.library_filename(lib, lib_type='static')

        if sys.platform == 'darwin':
            # On OSX users can specify an alternate SDK using
            # '-isysroot', calculate the SDK root if it is specified
            # (and use it further on)
            # Note that, as of Xcode 7, Apple SDKs may contain textual stub
            # libraries with .tbd extensions rather than the normal .dylib
            # shared libraries installed in /.  The Apple compiler tool
            # chain handles this transparently but it can cause problems
            # for programs that are being built with an SDK and searching
            # for specific libraries.  Callers of find_library_file need to
            # keep in mind that the base filename of the returned SDK library
            # file might have a different extension from that of the library
            # file installed on the running system, for example:
            #       usr/lib/libedit.tbd
            # vs
            cflags = sysconfig.get_config_var('CFLAGS')
            m = re.search(r'-isysroot\s+(\S+)', cflags)
            if m is None:
                sysroot = '/'
            else:
                sysroot = m.group(1)

        for dir in dirs:
            shared = os.path.join(dir, shared_f)
            dylib = os.path.join(dir, dylib_f)
            static = os.path.join(dir, static_f)
            xcode_stub = os.path.join(dir, xcode_stub_f)

            if sys.platform == 'darwin' and (
                dir.startswith('/System/') or (
                dir.startswith('/usr/') and not dir.startswith('/usr/local/'))):

                shared = os.path.join(sysroot, dir[1:], shared_f)
                dylib = os.path.join(sysroot, dir[1:], dylib_f)
                static = os.path.join(sysroot, dir[1:], static_f)
                xcode_stub = os.path.join(sysroot, dir[1:], xcode_stub_f)

            # We're second-guessing the linker here, with not much hard
            # data to go on: GCC seems to prefer the shared library, so I'm
            # assuming that *all* Unix C compilers do.  And of course I'm
            # ignoring even GCC's "-static" option.  So sue me.
            if os.path.exists(dylib):
                return dylib
            elif os.path.exists(xcode_stub):
                return xcode_stub
            elif os.path.exists(shared):
                return shared
            elif os.path.exists(static):
                return static

        # Oops, didn't find it in *any* of 'dirs'
        return None