text:
@testset "SpectrumArray" begin
    function cmparrays(a, b;
        rate_=rate(a), domain_=domain(a), nchannels_=nchannels(a),
        nframes_=nframes(a), names_=names(a), eltype_=eltype(a), typeof_=typeof(a), data_=data(a))
        isnothing(rate_) || rate(b) == rate_ || error("rate $(rate(b)) != $(rate_)")
        isnothing(domain_) || domain(b) == domain_ || error("domain $(domain(b)) != $(domain_)")
        isnothing(nchannels_) || nchannels(b) == nchannels_ || error("nchannels $(nchannels(b)) != $(nchannels_)")
        isnothing(nframes_) || nframes(b) == nframes_ || error("nframes $(nframes(b)) != $(nframes_)")
        isnothing(names_) || names(b) == names_ || error("names $(names(b)) != $(names_)")
        isnothing(eltype_) || eltype(b) == eltype_ || error("eltype $(eltype(b)) != $(eltype_)")
        isnothing(typeof_) || typeof(b) == typeof_ || error("typeof $(typeof(b)) != $(typeof_)")
        isnothing(data_) || data(b) == data_ || error("data not same!")
        true
    end

    sa = SpectrumArray(rand(6, 1), 10, 0Hz:1Hz:5Hz)
    sb = SpectrumArray(rand(6, 2), 10Hz, [0Hz, 1Hz, 2Hz, 3Hz, 4Hz, 5Hz])
    sc = SpectrumArray(rand(Float32, 6, 2), 32Hz, [0Hz, 1Hz, 2Hz, 4Hz, 8Hz, 16Hz])
    sd = SpectrumArray(rand(Complex{Float64}, 6, 2), 32Hz, [0Hz, 1Hz, 2Hz, 4Hz, 8Hz, 16Hz])
    se = SpectrumArray([float(j) for i in 1:16, j in 1:8], 44100Hz,
        [0Hz, ((2^i)Hz for i in 0:14)...],
        [:front_left, :front_right, :rear_left, :rear_right,
            :front_center, :lfe, :side_left, :side_right])
    sf = copy(se)
    sg = SpectrumArray(rand(6, 2), 32Hz, [0.5Hz, 1.5Hz, 2.5Hz, 4.5Hz, 7.5Hz, 15.5Hz])

    @test se == sf
    @test se !== sf
    @test cmparrays(se, sf)
    @test_throws ArgumentError SpectrumArray(rand(6, 1), 10, [0Hz, 1Hz, 2Hz, 3Hz, 4Hz, 2Hz]) # non-unique freqs

    @test_throws DimensionMismatch SpectrumArray(rand(6, 2), 10Hz, [0Hz, 1Hz, 2Hz, 3Hz, 4Hz, 5Hz], [:left, :right, :onemore])

    @testset "basic functions" begin
        @test domain(sa) == collect(0.0:1:5)
        @test domain_no0(sa) == collect(1.0:1:5)
        @test data_no0(sa) == data(sa)[2:end, :]
        @test nchannels(sa) == 1
        @test nframes(sa) == 6
        @test rate(sa) == 10.0
        @test rate(sc) == 32.0
        @test eltype(sa) == Float64
        @test cmparrays(sa, sb, nchannels_=2, names_=[Symbol(1), Symbol(2)], data_=nothing, typeof_=SpectrumArray{Float64,Vector{Float64}})
        @test names(se) == [:front_left, :front_right, :rear_left, :rear_right,
            :front_center, :lfe, :side_left, :side_right]

        sb2 = copy(sb)
        names!(sb2, :Right, 2)
        @test_throws ArgumentError names!(sb2, :Right, 1) # non unique name
        names!(sb2, :Left, 1)
        @test cmparrays(sb, sb2; names_=[:Left, :Right])
        names!(sb2, [:L, :R], 1:2)
        @test cmparrays(sb, sb2; names_=[:L, :R])
        names!(sb2, [:left, :right])
        @test_throws ArgumentError names!(sb2, [:same, :same]) # non unique name
        @test cmparrays(sb, sb2; names_=[:left, :right])
        names!(sc, [:left, :right])
        @test cmparrays(sb2, sc; rate_=32.0, domain_=nothing, data_=nothing, eltype_=Float32, typeof_=SpectrumArray{Float32,Vector{Float64}})
        names!(sb2, [:RIGHT, :LEFT], [:right, :left])
        @test cmparrays(sb, sb2; names_=[:LEFT, :RIGHT])
    end

    @testset "indexing" begin
        # linear index
        @test se[1] == data(se)[1]
        @test typeof(se[1]) == eltype(se)

        # frame addressing, select all channels
        @test cmparrays(se, se[1:10]; domain_=nothing, nframes_=10, data_=data(se)[1:10, :])

        # channel addressing
        @test cmparrays(se[1:10, :], se[1:10])

        @test cmparrays(se, se[:, 2]; nchannels_=1, names_=[:front_right], data_=data(se)[:, 2:2])
        @test cmparrays(se[:, 2], se[:, 2:2])
        @test cmparrays(se[:, [3, 4, 5, 6, 7]], se[:, 3:7])
        @test cmparrays(se[:, 2], se[:, [2]])
        @test cmparrays(se[:, 2], se[:, :front_right])
        @test cmparrays(se[:, :front_right], se[:, [:front_right]])
        @test_throws ArgumentError se[:, :wrong_channel_name]
        @test cmparrays(se[:, :front_right], se[:, [:front_right]])
        @test cmparrays(se[:, :rear_left..:side_left], se[:, 3:7])
        @test cmparrays(se[:, [name for name in names(se) if occursin("left", String(name))]], se[:, [1, 3, 7]])

        # getting integer indices
        @test [SampleArrays.toindex(sa, t) for t in [0Hz, 0.8Hz, 1Hz, 10Hz]] == [1, 2, 2, 6]
        @test [SampleArrays.toindex(sa, t) for t in [0, 0.8, 1, 10]] == [1, 2, 2, 6]

        @test_throws ArgumentError SampleArrays.toframeidx(sa, 0s..1s)
        @test SampleArrays.toframeidx(sa, 0Hz..1.4Hz) == 1:2
        @test SampleArrays.toframeidx(sa, 0Hz..1.6Hz) == 1:3

        # frame adressing by time
        @test cmparrays(sa[0Hz..1.4Hz, 1:1], sa[SampleArrays.toframeidx(sa, 0Hz..1.4Hz), 1:1])
        @test cmparrays(sa[0Hz..2.6Hz, 1], sa[0Hz..2.6Hz, 1:1])
        @test cmparrays(sb[0Hz..2.6Hz], sb[0Hz..2.6Hz, :])

        # Array indexing
        sb2 = sb[[1,3,5], [1]]
        @test data(sb2) == data(sb)[[1,3,5], [1]]

        # Bool[] and BitArray indexing
        sb2 = sb[data(sa)[:] .> 0, [true, false]]
        @test data(sb2) == data(sb)[data(sa)[:] .> 0, [true, false]]

        # zero channels
        sb2 = sb[:, []]
        @test nchannels(sb2) == 0
        sb3 = sb[:, [false, false]]
        @test nchannels(sb3) == 0
        @test cmparrays(sb2, sb3)

        # setindex!
        sc[1] = -2
        @test data(sc)[1] == -2

        @test_throws ArgumentError sc[1:5] = -2
        sc[1:5] .= -2
        @test all(data(sc)[1:5, :] .== -2)

        sc[1:3,:] .= -5
        @test all(data(sc)[1:3, 1:2] .== -5)

        @test_throws ArgumentError sc[0s..0.75s, 1:2] # seconds instead of Hz

        sc[0Hz..1.75Hz, 1:2] .= -13
        @test all(data(sc[0Hz..1.75Hz, 1:2]) .== -13)

        sc[0Hz..1.75Hz, :left] .= -14
        @test all(data(sc[0Hz..1.75Hz, 1]) .== -14)

        sc[0Hz..1.75Hz, [:left, :right]] .= -15
        @test all(data(sc[0Hz..1.75Hz, 1:2]) .== -15)

        sc[[1,3,5], [1]] .= -20
        @test all(data(sc)[[1,3,5], [1]] .== -20)

        mask = data(sc)[:, 1] .> 0
        sc[mask, [false, true]] .= -50
        @test all(data(sc)[mask, [false, true]] .== -50)
    end

    @testset "similar" begin
        @test cmparrays(sb, similar(sb); data_=nothing)
        @test cmparrays(sb, similar(sb, Float32); data_=nothing, eltype_=Float32, typeof_=SpectrumArray{Float32,Vector{Float64}})
        @test cmparrays(sb, similar(sb, eltype(sb), (10, 2), collect(1:1:10)); domain_=nothing, nframes_=10, data_=nothing)
        @test cmparrays(sb, similar(sb, Float32, (10, 2), collect(1:1:10)); domain_=nothing, nframes_=10,
            data_=nothing, eltype_=Float32, typeof_=SpectrumArray{Float32,Vector{Float64}})
        names!(sb, [:left, :right])
        @test cmparrays(sb, similar(sb, Float64, (10, 1), collect(1:1:10)); domain_=nothing, nframes_=10, data_=nothing, nchannels_=1, names_=[:left])
        @test cmparrays(sb, similar(sb, Float64, (10, 3), collect(1:1:10)); domain_=nothing, nframes_=10, data_=nothing,
            nchannels_=3, names_=SampleArrays._default_channel_names(3))
    end

    @testset "view" begin
        sb2 = copy(sb)
        vsb2 = view(sb2, 1:3, 1:1)
        typeof(vsb2) <: SubArray

        vsb2[:] .= -5
        @test all(sb2[1:3, 1:1] .== -5)
    end

    @testset "broadcasting" begin
        @test sa + sa == 2 * sa
        @test data(sa .+ 5) == data(sa) .+ 5

        sa32 = Float32.(sa)
        ssum = sa + sa32
        @test ssum ≈ 2sa

        @test cmparrays(ssum, sa32 .+ sb; nchannels_=2, names_=nothing, data_=nothing)
    end

    @testset "concatenation" begin
        @test data(hcat(sa, sb)) == hcat(data(sa), data(sb))
        sc2 = hcat(sc, sc)
        @test cmparrays(sc, sc2[:, 1:2])
        @test cmparrays(sc, sc2[:, 3:4]; names_=[:left_2, :right_2])
        sc2 = hcat(sc, Float32.(sc))
        @test cmparrays(sc, sc2[:, 1:2])
        @test cmparrays(sc, sc2[:, 3:4]; names_=[:left_2, :right_2], data_=nothing)
        @test_throws ArgumentError hcat(sa, sc) # different rate

        @test_throws ArgumentError vcat(sc, sc)

        names!(sg, names(sc))
        sg2 = vcat(sc, sg)
        @test cmparrays(sc, sg2[1:6, :], eltype_=Float64, typeof_=SpectrumArray{Float64,Vector{Float64}})
        @test cmparrays(sg, sg2[7:end, :])
        names!(sg, [:L, :R])
        @test_throws ArgumentError vcat(sc, sg) # non-unique channel names
        @test_throws ArgumentError vcat(sa, sc) # non-unique rates
        @test_throws ArgumentError vcat(sc, sc) # non-unique freqs

        @test_throws ErrorException cat(sa, sa; dims=1)
    end

    @testset "phase" begin
        sdz = zerophase(sd)
        @test sdz !== sd
        @test all(imag.(sdz) .== 0)
        sdz2 = copy(sd)
        zerophase!(sdz2)
        @test sdz == sdz2
        @test sdz !== sdz2
    end
end


text:
n = 10 # rand(2:10)
@test matrixdepot("neumann", 1) == reshape([4.0], 1, 1)
@test matrixdepot("neumann", n) == matrixdepot("neumann", Float64, n)

n_mesh, n = n, n^2

B = zeros(Float64, n, n)

i = 0

for i_mesh in 1:n_mesh, j_mesh in 1:n_mesh
    global i = i + 1
    if i_mesh > 1
        j = i - n_mesh
    else
        j = i + n_mesh
    end

    B[i,j] = B[i,j] - 1

    if j_mesh > 1
        j = i - 1
    else
        j = i + 1
    end

    B[i,j] = B[i,j] - 1

    j = i
    B[i,j] = 4

    if j_mesh < n_mesh
        j = i + 1
    else
        j = i - 1
    end

    B[i,j] = B[i,j] - 1

    if i_mesh < n_mesh
        j = i + n_mesh
    else
        j = i - n_mesh
    end

    B[i,j] = B[i,j] - 1
end

A = matrixdepot("neumann", n_mesh)

@test Matrix(A) ≈ B

println("'neumann' passed test...")

ext: jl


text:
using Crux
using Flux
using POMDPs
using Distributions

using Plots

function DeepGMM()
    base = Chain(Dense(2, 32, relu))
    mu1 = ContinuousNetwork(Chain(base..., Dense(32, 1)))
    logΣ1 = ContinuousNetwork(Chain(base..., Dense(32, 1)))
    # mu1 = ContinuousNetwork(ConstantLayer([1f0]), 1)
    # logΣ1 = ContinuousNetwork(ConstantLayer([log(1f0)]), 1)

    mu2 = ContinuousNetwork(Chain(base..., Dense(32, 1)))
    logΣ2 = ContinuousNetwork(Chain(base..., Dense(32, 1)))

    # mu2 = ContinuousNetwork(ConstantLayer([-1f0]), 1)
    # logΣ2 = ContinuousNetwork(ConstantLayer([log(1f0)]), 1)

    αs = ContinuousNetwork(Chain(base..., Dense(32, 2), softmax), 2)
    # αs = ContinuousNetwork(Chain(ConstantLayer([1f0, 1f0]), softmax), 2)
    MixtureNetwork([GaussianPolicy(mu1, logΣ1), GaussianPolicy(mu2, logΣ2)], αs)
end

function G()
    base = Chain(Dense(2, 32, relu))
    mu1 = ContinuousNetwork(Chain(base..., Dense(32, 1)))
    logΣ1 = ContinuousNetwork(Chain(base..., Dense(32, 1)))

    GaussianPolicy(mu1, logΣ1)
end

function plot_gmm(model, s, Npts=100)
    rd(v) = round(v, digits=2)
    αs = rd.(model.weights(s))
    m1 = rd(model.networks[1].μ(s)[1])
    σ1 = rd(exp(model.networks[1].logΣ(s)[1]))
    m2 = rd(model.networks[2].μ(s)[1])
    σ2 = rd(exp(model.networks[2].logΣ(s)[1]))

    lb = min(m1 - 3*σ1, m2 - 3*σ2)
    ub = max(m1 + 3*σ1, m2 + 3*σ2)

    yrange = range(lb, ub, length=Npts)
    py = [exp(logpdf(model, s, [y])[1]) for y in yrange]

    plot(yrange, py, title="$(αs[1]) ⋅ N($m1, $σ1) + $(αs[2]) ⋅ N($m2, $σ2) ")
end

target_dist = MixtureModel([Normal(1,0.2), Normal(-1, 1)], [0.5, 0.5])
plot(-3:0.1:3, x -> pdf(target_dist, x))

y = reshape(Float32.(rand(target_dist, 100_000)), 1, :)
x = 0.1f0 * ones(Float32, 2, 100_000)
d = Flux.Data.DataLoader((x, y), batchsize=1024)

n = DeepGMM()
loss(x,y) = -mean(logpdf(n, x, y))

loss(x, y)
plot_gmm(n, [0.1, 0.1])
plot!(-3:0.1:3, x -> pdf(target_dist, x))

logpdf(n, x, y)

opt = ADAM()

evalcb() = @show(loss(x, y))
throttled_cb = Flux.throttle(evalcb, 1)
Flux.@epochs 100 Flux.train!(loss, Flux.params(n), d, opt, cb = throttled_cb)
loss(x, y)
plot_gmm(n, x[:, 1])
plot!(-3:0.1:3, x -> pdf(target_dist, x))
histogram!(y[:], normalize=true)

max_stars_repo_name: ancorso/ContinualLearning

max_issues_repo_name: ancorso/ContinualLearning

max_forks_repo_name: ancorso/ContinualLearning


text:
using Conda
using PyCall
using Pkg
root = Symbol(Conda.ROOTENV)
if !Conda.exists("torch", root) || !Conda.exists("torchvision", root)
    println("either pytorch not found, installing in '$root'")
    Conda.runconda(`install pytorch torchvision -c pytorch -p "$root"`)
end
println("torchvision installed")

currentDirectory = pwd()
if Sys.iswindows()
    pipPath = joinpath(String(root), "Scripts", "pip")
else
    pipPath = joinpath(String(root), "bin", "pip")
end
println("using pip $(pipPath)")
run(`$(pipPath) install kymatio`)

try
    Conda.parseconda(`search kymatio`)
catch
    run(`$(pipPath) install kymatio`)
end

cd(currentDirectory)


text:
###################################################################################################
# SIMULATION FUNCTIONS
###################################################################################################
"""
    `gen_x_mc(N,α,β)`

    Function that generates a methylation vector from an Ising model with `[N1,...,NK]`, and parameters
    `[α1,...,αK]` and `β`.

    # Examples
    ```julia-repl
    julia> using Random; Random.seed!(1234);
    julia> CpelTdm.gen_x_mc([5],[0.0,0.0])
    5-element Array{Int64,1}:
     1
     1
     1
     -1
     1
    ```
"""
function gen_x_mc(n::Vector{Int64},θ::Vector{Float64})::Vector{Int64}

    # Ge parameters
    α = θ[1:(end-1)]
    β = θ[end]

    # Find subregion label for each CpG site
    subid = vcat([i*ones(Int64,n[i]) for i in 1:length(n)]...)

    # Sample first CpG site
    x = Vector{Int64}()
    p = comp_lkhd(pushfirst!(zeros(Int64,sum(n)-1),1),n,α,β)
    push!(x,sample([-1,1],Distributions.Weights([1-p,p])))
    sum(n)>1 || return x

    # Sequentially sample from Markov chain
    @inbounds for i=2:sum(n)

        # Add boundary function g() if necessary
        expaux = exp(α[subid[i]]+β*x[i-1])
        if i < sum(n)
            ap1p = 2.0*β + α[subid[i]]
            ap1m = -2.0*β + α[subid[i]]
            n_miss = [count(x->x==sr,subid[(i+1):sum(n)]) for sr in unique(subid[(i+1):sum(n)])]
            gp = comp_g(n_miss,α[unique(subid[(i+1):sum(n)])],β,ap1p,α[end])
            gm = comp_g(n_miss,α[unique(subid[(i+1):sum(n)])],β,ap1m,α[end])
            p = gp*expaux/(gp*expaux+gm/expaux)
        else
            p = expaux/(expaux+1.0/expaux)
        end

        # Add i-th CpG site
        push!(x,sample([-1,1],Distributions.Weights([1-p,p])))

    end

    # Return methylation vector
    return x

end # end gen_x_mc
"""
    `unmatched_sim(m,n,θ1,θ2)`

    Function that simulates hypothesis testing in a (balanced) unmatched group comparison.

    # Examples
    ```julia-repl
    julia> m=5; n=[5]; θ1=[0.5,0.5,0.25]; θ2=[0.5,0.5,0.25];
    julia> tmml,tnme,tpdm = CpelTdm.unmatched_sim(m,n,θ1,θ2)
    ```
"""
function unmatched_sim(m::Int64,n::Vector{Int64},θ1::Vector{Float64},θ2::Vector{Float64})::NTuple{3,Vector{NTuple{2,Float64}}}

    # Generate 1k data-sets
    tmml = Vector{NTuple{2,Float64}}()
    tnme = Vector{NTuple{2,Float64}}()
    tpdm = Vector{NTuple{2,Float64}}()
    while length(tmml)<1000

        ## Generate data

        # g1
        g1_samples = []
        for i=1:m
            push!(g1_samples,[gen_x_mc(n,θ1) for j=1:rand(10:30)])
        end

        # g2
        g2_samples = []
        for i=1:m
            push!(g2_samples,[gen_x_mc(n,θ2) for j=1:rand(10:30)])
        end

        ## Estimate vectors

        # g1
        g1_θs = Vector{Vector{Float64}}()
        for xobs in g1_samples
            push!(g1_θs,est_theta_sa(n,xobs))
        end

        # g2
        g2_θs = Vector{Vector{Float64}}()
        for xobs in g2_samples
            push!(g2_θs,est_theta_sa(n,xobs))
        end

        ## Compute unmatched pvals
        tmml_data,tnme_data,tpdm_data = unmat_tests(n,g1_θs,g2_θs)

        # Append
        push!(tmml,tmml_data)
        push!(tnme,tnme_data)
        push!(tpdm,tpdm_data)

    end

    # Return p-values
    return tmml,tnme,tpdm

end
"""
    `matched_sim(m,n,θ1,θ2)`

    Function that simulates hypothesis testing in a matched group comparison.

    # Examples
    ```julia-repl
    julia> m=5; n=[5]; θ1=[0.5,0.5,0.25]; θ2=[0.5,0.5,0.25];
    julia> tmml,tnme,tpdm = CpelTdm.matched_sim(m,n,θ1,θ2)
    ```
"""
function matched_sim(m::Int64,n::Vector{Int64},θ1s::Vector{Vector{Float64}},θ2s::Vector{Vector{Float64}})::NTuple{3,Vector{NTuple{2,Float64}}}

    # Generate 1k data-sets
    tmml = Vector{NTuple{2,Float64}}()
    tnme = Vector{NTuple{2,Float64}}()
    tpdm = Vector{NTuple{2,Float64}}()
    while length(tmml)<1000

        ## Generate data

        # g1
        g1_samples = []
        for i=1:m
            push!(g1_samples,[gen_x_mc(n,θ1s[i]) for j=1:rand(10:30)])
        end

        # g2
        g2_samples = []
        for i=1:m
            push!(g2_samples,[gen_x_mc(n,θ2s[i]) for j=1:rand(10:30)])
        end

        ## Estimate vectors

        # g1
        g1_θs = Vector{Vector{Float64}}()
        for xobs in g1_samples
            push!(g1_θs,est_theta_sa(n,xobs))
        end

        # g2
        g2_θs = Vector{Vector{Float64}}()
        for xobs in g2_samples
            push!(g2_θs,est_theta_sa(n,xobs))
        end

        ## Compute unmatched pvals
        tmml_data,tnme_data,tpdm_data = mat_tests(n,g1_θs,g2_θs)

        # Append
        push!(tmml,tmml_data)
        push!(tnme,tnme_data)
        push!(tpdm,tpdm_data)

    end

    # Return p-values
    return tmml,tnme,tpdm

end


text:
#
# Protein - Water
#

include("../../src/MDDF.jl")
using PDBTools

atoms = PDBTools.readPDB("./structure.pdb")
solute_indexes = PDBTools.select(atoms,"protein")
solute = MDDF.Selection( solute_indexes, nmols=1 )
solvent_indexes = PDBTools.select(atoms,"resname TIP3")
solvent = MDDF.Selection( solvent_indexes, natomspermol=3 )
trajectory = MDDF.Trajectory("../NAMD/trajectory.dcd",solute,solvent)
options = MDDF.Options(binstep=0.2,n_random_samples=10)
@time R = MDDF.mddf(trajectory,options)


text:
using Test
using PyCall

haslib = pyimport("haslib")

mel = 1.6021766208000002e-22
A = 1e-10
a = 4.3*A
Ei = 4.196*mel
theta = 45.75

D = 5*mel
h = 0.1
xi = 0.38/A

crystal=haslib.Crystal(a, a, 120)
crystal.calc_reciprocals()
grid = HASlib.HexGrid(a)

@test grid.l.a1 ≈ crystal.a1[1:2]
@test grid.l.a2 ≈ crystal.a2[1:2]
@test grid.l.b1 ≈ crystal.b1_orig[1:2]
@test grid.l.b2 ≈ crystal.b2_orig[1:2]

function test_rotation(dir)
	crystal=haslib.Crystal(a, a, 120)
	grid = HASlib.HexGrid(a)
	crystal.rotate_crystal(dir...)
	b1,b2 = HASlib.rotate_reciprocal(grid.l,dir)
	(b1 ≈ crystal.b1[1:2]) && (b2 ≈ crystal.b2[1:2])
end

@test test_rotation([2,0])
@test test_rotation([0,2])
@test test_rotation([2,1])
@test test_rotation([2,-1])

b1,b2 = HASlib.rotate_reciprocal(grid.l,[2,-1])
mb1,mb2 = HASlib.rotate_reciprocal(grid.l,[-2,1])
@test b1 ≈ -mb1
@test b2 ≈ -mb2

b1,b2 = HASlib.rotate_reciprocal(grid.l,[1,0])
ERG = haslib.icc_2d_2.iCC_2D_2(h,1.0,a,D,xi,Ei,theta,b1,b2,floq=0,Gope=-1,Gclo=50,maxrad=20,sta_z=-1*A,end_z=6*A,st_p_wl=150)

m_He3 = 5.0082343984338715e-27
ki = sqrt(Ei/HASlib.h2m(m_He3))

channels = HASlib.get_channels(b1,b2,ki,theta*pi/180,5)
channels = HASlib.sort_and_cut(channels,-1,50)
result = cc(channels,a,h,D,xi,theta,m_He3,(-1*A,6*A),st_p_wl=150)

@test sort(result[:,1]) ≈ sort(ERG[:,7])

using BenchmarkTools
display(@benchmark cc(channels,a,h,D,xi,theta,m_He3,(-1*A,6*A),st_p_wl=150))
display(@benchmark haslib.CC_2D_old(h,a,D,xi,Ei,theta,b1,b2,G_ope=-1,G_clo=50,maxrad=20,sta_z=-1*A,end_z=6*A,st_p_wl=150))
display(@benchmark haslib.icc_2d_2.iCC_2D_2(h,1,a,D,xi,Ei,theta,b1,b2,Gope=-1,Gclo=50,floq=1,maxrad=20,sta_z=-1*A,end_z=6*A,st_p_wl=150))


text:
const MO_MOVE_SENTE = Int(0x80) # 先手駒台（着手の表現時に使われる）
const MO_MOVE_GOTE  = Int(0xa0) # 後手駒台（着手の表現時に使われる）

# movable squares

const movableNoSliding = [(1,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (2,-1) (2,1) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (1,-1) (1,0) (1,1) (-1,-1) (-1,1) (0,0) (0,0) (0,0);
                          (1,-1) (1,0) (1,1) (0,-1) (0,1) (-1,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (1,-1) (1,0) (1,1) (0,-1) (0,1) (-1,-1) (-1,0) (-1,1);
                          (1,-1) (1,0) (1,1) (0,-1) (0,1) (-1,0) (0,0) (0,0);
                          (1,-1) (1,0) (1,1) (0,-1) (0,1) (-1,0) (0,0) (0,0);
                          (1,-1) (1,0) (1,1) (0,-1) (0,1) (-1,0) (0,0) (0,0);
                          (1,-1) (1,0) (1,1) (0,-1) (0,1) (-1,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (1,0) (0,1) (0,-1) (-1,0) (0,0) (0,0) (0,0) (0,0);
                          (1,-1) (1,1) (-1,-1) (-1,1) (0,0) (0,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (-1,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (-2,-1) (-2,1) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (-1,-1) (-1,0) (-1,1) (1,-1) (1,1) (0,0) (0,0) (0,0);
                          (-1,-1) (-1,0) (-1,1) (0,-1) (0,1) (1,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
                          (1,-1) (1,0) (1,1) (0,-1) (0,1) (-1,-1) (-1,0) (-1,1);
                          (-1,-1) (-1,0) (-1,1) (0,-1) (0,1) (1,0) (0,0) (0,0);
                          (-1,-1) (-1,0) (-1,1) (0,-1) (0,1) (1,0) (0,0) (0,0);
                          (-1,-1) (-1,0) (-1,1) (0,-1) (0,1) (1,0) (0,0) (0,0);
                          (-1,-1) (-1,0) (-1,1) (0,-1) (0,1) (1,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0);
            #original UM #(1,0) (0,1) (0,-1) (-1,0) (0,0) (0,0) (0,0) (0,0);
            #original RY #(1,-1) (1,1) (-1,-1) (-1,1) (0,0) (0,0) (0,0) (0,0);
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0); # new UM
                          (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0) (0,0); # new RY
                          ]

const isSlidePiece = [ 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,  0, 1, 1]::Array{Int,1}
                    # FU,KY,KE,GI,KI,KA,HI,OU,TO,NY,NK,NG,NKI,UM,RY

#for x = 1:size(movableNoSliding,1)
#    y = movableNoSliding[x,1:size(movableNoSliding,2)]
#end

function InitTables(gs::GameStatus)
    for sq = A9:I1
        for piece = MJFU:MJGORY
            z = UInt128(0)
            y = movableNoSliding[piece,1:8]
            for p = 1:8
                dr, df = movableNoSliding[piece,p]
                r = RANKS[sq]
                f = FILES[sq]
                if (dr == 0)&&(df == 0)
                else
                    z |= setAttack( r+dr, f+df, UInt128(0))
                end
            end
            gs.AttackTableNonSlide[piece,sq] = z
        end
    end

    #for piece = MJFU:MJGORY
    #    for sq = A9:I1
    #        teban::Int = (piece & 0x10)>>>4
    #        koma::Int  = piece & 0x0f

    #        if koma != 0
    #            println(TEBANSTR[teban+1],KOMASTR[koma],SQUARENAME[sq])
    #        end

    #       DisplayBitBoard(gs.AttackTableNonSlide[piece,sq],false)
    #    end
    #end

    gs.FillRank = [UInt128(0) for r=1:9]::Array{BitBoard,1}
    gs.FillFile = [UInt128(0) for f=1:9]::Array{BitBoard,1}

    for i = A9:I1
        r = RANKS[i]
        f = FILES[i]
        gs.FillRank[r] |= BitSet[i]
        gs.FillFile[f] |= BitSet[i]
    end

    gs.fukyBitsW = UInt128(0)
    for r = 1:8
        gs.fukyBitsW |= gs.FillRank[r]
    end
    gs.fukyBitsB = UInt128(0)
    for r = 2:9
        gs.fukyBitsB |= gs.FillRank[r]
    end
    gs.keBitsW = UInt128(0)
    for r = 1:7
        gs.keBitsW |= gs.FillRank[r]
    end
    gs.keBitsB = UInt128(0)
    for r = 3:9
        gs.keBitsB |= gs.FillRank[r]
    end

    #zeros = UInt128(0)

    gs.MovableKoma = [gs.fukyBitsW gs.fukyBitsW gs.keBitsW;
                      gs.fukyBitsB gs.fukyBitsB gs.keBitsB]::Array{BitBoard,2}
    #for sengo = 1:2
    #    for koma = MJFU:MJKE
    #        println("movable[",sengo,koma,"] = ")
    #        DisplayBitBoard(MovableKoma[sengo,koma],false)
    #    end
    #end

    gs.SenteJin    = gs.FillRank[1]|gs.FillRank[2]|gs.FillRank[3]
    gs.GoteJin     = gs.FillRank[7]|gs.FillRank[8]|gs.FillRank[9]
    gs.SenteOthers = gs.FillRank[4]|gs.FillRank[5]|gs.FillRank[6]|gs.GoteJin
    gs.GoteOthers  = gs.FillRank[4]|gs.FillRank[5]|gs.FillRank[6]|gs.SenteJin

    # DisplayBitBoard(SenteJin,false)
    # DisplayBitBoard(GoteJin,false)
    # DisplayBitBoard(SenteOthers,false)
    # DisplayBitBoard(GoteOthers,false)

end

function InsertMove(idx::Int64, out::Array{Move,1}, gs::GameStatus)
    i2::Int = 0
    ban::Int = -1
    m::Move = out[idx]

    for i2 = gs.MoveBeginIndex+1:idx-1
        if m.value < out[i2].value
            # continue
        else
            ban = i2
            break
        end
    end

    if ban == -1
        # do nothing
    else
        tmpM     = out[idx]
        out[idx] = out[ban]
        out[ban] = tmpM
    end
end
function InsertMove(idx::Int32, out::Array{Move,1}, gs::GameStatus)
    InsertMove(Int64(idx), out, gs)
end

function InsertMoveAB(idx::Int64, out::Array{Move,1}, gs::GameStatus)
    InsertMove(Int64(idx), out, gs)
end

function InsertMoveAB(idx::Int32, out::Array{Move,1}, gs::GameStatus)
    InsertMoveAB(Int64(idx), out, gs)
end

function genBB(p::Board,           #     /* IN:盤面 */
	       out::Array{Move,1}, #     /* IN/OUT: 可能手を格納する配列*/
	       teban::Int,         #     /* 可能手を生成する手番 */
               co::Int,
	       gs::GameStatus)
    count::Int32 = Int32(co)
    target::BitBoard = UInt128(0)
    bbp::BitBoard    = UInt128(0)

    if teban == SENTE
        target = (~p.WhitePieces) & MaskOfBoard
        # println("target")
        # DisplayBitBoard( target, false)

        # FU

        bbp = p.bb[MJFU]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJFU,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if (to+1) < A6
                    # promotion
                    count += 1

                    out[count] = Move(MJTO,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
                # normal move
                if (to+1) >= A8
                    count += 1
                    out[count] = Move(MJFU,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
            end
        end

        # MJKYはsliding pieceなので割愛

        # KE

        bbp = p.bb[MJKE]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJKE,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if (to+1) < A6
                    # promotion
                    count += 1

                    out[count] = Move(MJNK,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
                # normal move
                if (to+1) >= A7
                    count += 1
                    out[count] = Move(MJKE,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
            end
        end

        # GI

        bbp = p.bb[MJGI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGI,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if ((to+1) < A6 )||((from+1) < A6)
                    # promotion
                    count += 1

                    out[count] = Move(MJNG,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
                # normal move
                count += 1
                out[count] = Move(MJGI,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KI

        bbp = p.bb[MJKI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJKI,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJKI,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # OU

        bbp = p.bb[MJOU]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJOU,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJOU,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # TO

        bbp = p.bb[MJTO]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJTO,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJTO,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # NY

        bbp = p.bb[MJNY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJNY,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJNY,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # NK

        bbp = p.bb[MJNK]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJNK,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJNK,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # NG

        bbp = p.bb[MJNG]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJNG,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJNG,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end
    else
        target = (~p.BlackPieces) & MaskOfBoard
        # println("target")
        # DisplayBitBoard( target, false)

        # GOFU

        bbp = p.bb[MJGOFU]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOFU,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if (to+1) >= A3
                    # promotion
                    count += 1

                    out[count] = Move(MJGOTO,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
                # normal move
                if (to+1) < A1
                    count += 1
                    out[count] = Move(MJGOFU,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
            end
        end

        # MJKYはsliding pieceなので割愛

        # GOKE

        bbp = p.bb[MJGOKE]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOKE,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if (to+1) >= A3
                    # promotion
                    count += 1

                    out[count] = Move(MJGONK,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
                # normal move
                if (to+1) < A2
                    count += 1
                    out[count] = Move(MJGOKE,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
            end
        end

        # GOGI

        bbp = p.bb[MJGOGI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOGI,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if ((to+1) >= A3 )||((from+1) >= A3)
                    # promotion
                    count += 1

                    out[count] = Move(MJGONG,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMoveAB(count,out,gs)
                end
                # normal move
                count += 1
                out[count] = Move(MJGOGI,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # GOKI

        bbp = p.bb[MJGOKI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOKI,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJGOKI,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # GOOU

        bbp = p.bb[MJGOOU]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOOU,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJGOOU,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # GOTO

        bbp = p.bb[MJGOTO]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOTO,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJGOTO,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # GONY

        bbp = p.bb[MJGONY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGONY,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJGONY,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # GONK

        bbp = p.bb[MJGONK]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGONK,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJGONK,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # GONG

        bbp = p.bb[MJGONG]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGONG,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                count += 1
                out[count] = Move(MJGONG,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end
    end
    count
end

function genQBB(p::Board,           #     /* IN:盤面 */
	        out::Array{Move,1}, #     /* IN/OUT: 可能手を格納する配列*/
	        teban::Int,         #     /* 可能手を生成する手番 */
                co::Int,
	        gs::GameStatus)
    count::Int32 = Int32(co)
    target::BitBoard = UInt128(0)
    bbp::BitBoard    = UInt128(0)

    if teban == SENTE
        target = (~p.WhitePieces) & MaskOfBoard
        # println("target")
        # DisplayBitBoard( target, false)

        # FU

        bbp = p.bb[MJFU]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJFU,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if (to+1) < A6
                    # promotion
                    count += 1

                    out[count] = Move(MJTO,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
                # normal move
                if ((to+1) >= A8)&&(toriflag == FLAG_TORI)
                    count += 1
                    out[count] = Move(MJFU,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # MJKYはsliding pieceなので割愛

        # KE

        bbp = p.bb[MJKE]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJKE,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if (to+1) < A6
                    # promotion
                    count += 1

                    out[count] = Move(MJNK,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
                # normal move
                if ((to+1) >= A7)&&(toriflag == FLAG_TORI)
                    count += 1
                    out[count] = Move(MJKE,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # GI

        bbp = p.bb[MJGI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGI,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if ((to+1) < A6 )||((from+1) < A6)
                    # promotion
                    count += 1

                    out[count] = Move(MJNG,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJGI,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # KI

        bbp = p.bb[MJKI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJKI,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJKI,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # OU

        bbp = p.bb[MJOU]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJOU,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJOU,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # TO

        bbp = p.bb[MJTO]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJTO,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJTO,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # NY

        bbp = p.bb[MJNY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJNY,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJNY,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # NK

        bbp = p.bb[MJNK]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJNK,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJNK,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # NG

        bbp = p.bb[MJNG]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJNG,from+1]
            toru::BitBoard = dest & p.BlackPieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJNG,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end
    else
        target = (~p.BlackPieces) & MaskOfBoard
        # println("target")
        # DisplayBitBoard( target, false)

        # GOFU

        bbp = p.bb[MJGOFU]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOFU,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if (to+1) >= A3
                    # promotion
                    count += 1

                    out[count] = Move(MJGOTO,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
                # normal move
                if ((to+1) < A1)&&(toriflag == FLAG_TORI)
                    count += 1
                    out[count] = Move(MJGOFU,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # MJKYはsliding pieceなので割愛

        # GOKE

        bbp = p.bb[MJGOKE]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOKE,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if (to+1) >= A3
                    # promotion
                    count += 1

                    out[count] = Move(MJGONK,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
                # normal move
                if ((to+1) < A2)&&(toriflag == FLAG_TORI)
                    count += 1
                    out[count] = Move(MJGOKE,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # GOGI

        bbp = p.bb[MJGOGI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOGI,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                if ((to+1) >= A3 )||((from+1) >= A3)
                    # promotion
                    count += 1

                    out[count] = Move(MJGONG,from,to,FLAG_NARI|toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJGOGI,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # GOKI

        bbp = p.bb[MJGOKI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOKI,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJGOKI,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # GOOU

        bbp = p.bb[MJGOOU]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOOU,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJGOOU,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # GOTO

        bbp = p.bb[MJGOTO]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGOTO,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJGOTO,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # GONY

        bbp = p.bb[MJGONY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGONY,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJGONY,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # GONK

        bbp = p.bb[MJGONK]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGONK,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJGONK,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end

        # GONG

        bbp = p.bb[MJGONG]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            # println("bbp")
            # DisplayBitBoard(bbp,false)
            bbp ⊻= BitSet[from+1]
            dest::BitBoard = target & gs.AttackTableNonSlide[MJGONG,from+1]
            toru::BitBoard = dest & p.WhitePieces
            while dest > UInt128(0)
                to = trailing_zeros(dest)
                # println("dest")
                # DisplayBitBoard( dest, false)
                dest ⊻= BitSet[to+1]
                toriflag = ((toru & BitSet[to+1]) > 0) ? FLAG_TORI : 0
                # normal move
                if toriflag == FLAG_TORI
                    count += 1
                    out[count] = Move(MJGONG,from,to,toriflag,p.square[to+1]&0x0f,0)::Move
                    InsertMove(count,out,gs)
                end
            end
        end
    end
    count
end

function genBBDrop(p::Board,           #     /* IN:盤面 */
	           out::Array{Move,1}, #     /* IN/OUT: 可能手を格納する配列*/
	           teban::Int,         #     /* 可能手を生成する手番 */
                   co::Int,
	           gs::GameStatus)
    count::Int32 = Int32(co)
    target::BitBoard = UInt128(0)
    bbp::BitBoard    = UInt128(0)

    if teban == SENTE
        target = (~(p.WhitePieces|p.BlackPieces)) & MaskOfBoard
        # println("target")
        # DisplayBitBoard( target, false)

        # FU

        bbp = p.bb[MJFU]
        if p.WhitePiecesInHands[MJFU] > 0
            nifu = UInt128(0)
            for ra = rank1:rank9
                nifu |= (bbp >>> ((ra-1)*9)& 0x01ff)
            end
            nifu = UInt16((~nifu) & 0x1ff)
            fuuchi = UInt128(0)
            for fi = file1:file9
                if (nifu & (0x0001 << (fi-1))) > 0
                    fuuchi |= gs.FillFile[fi]
                end
            end

            secondTarget = target & fuuchi & gs.fukyBitsW

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJFU,MO_MOVE_SENTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KY

        bbp = p.bb[MJKY]
        if p.WhitePiecesInHands[MJKY] > 0
            secondTarget = target & gs.fukyBitsW

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJKY,MO_MOVE_SENTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KE

        bbp = p.bb[MJKE]
        if p.WhitePiecesInHands[MJKE] > 0
            secondTarget = target & gs.keBitsW

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJKE,MO_MOVE_SENTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # GI

        bbp = p.bb[MJGI]
        if p.WhitePiecesInHands[MJGI] > 0
            secondTarget = target

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                #println("move=",count) # for debug purpose
                out[count] = Move(MJGI,MO_MOVE_SENTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KI

        bbp = p.bb[MJKI]
        if p.WhitePiecesInHands[MJKI] > 0
            secondTarget = target

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJKI,MO_MOVE_SENTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KA

        bbp = p.bb[MJKA]
        if p.WhitePiecesInHands[MJKA] > 0
            secondTarget = target

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJKA,MO_MOVE_SENTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # HI

        bbp = p.bb[MJHI]
        if p.WhitePiecesInHands[MJHI] > 0
            secondTarget = target

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJHI,MO_MOVE_SENTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end
    else
        target = (~(p.WhitePieces|p.BlackPieces)) & MaskOfBoard
        # println("target")
        # DisplayBitBoard( target, false)

        # GOFU

        bbp = p.bb[MJGOFU]
        if p.BlackPiecesInHands[MJFU] > 0
            nifu = UInt128(0)
            for ra = rank1:rank9
                nifu |= (bbp >>> ((ra-1)*9)& 0x01ff)
            end
            nifu = UInt16((~nifu)&0x1ff)
            fuuchi = UInt128(0)
            for fi = file1:file9
                if (nifu & (0x0001 << (fi-1))) > 0
                    fuuchi |= gs.FillFile[fi]
                end
            end

            secondTarget = target & fuuchi & gs.fukyBitsB

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJGOFU,MO_MOVE_GOTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KY

        bbp = p.bb[MJGOKY]
        if p.BlackPiecesInHands[MJKY] > 0
            secondTarget = target & gs.fukyBitsB

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJGOKY,MO_MOVE_GOTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KE

        bbp = p.bb[MJGOKE]
        if p.BlackPiecesInHands[MJKE] > 0
            secondTarget = target & gs.keBitsB

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJGOKE,MO_MOVE_GOTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # GI

        bbp = p.bb[MJGOGI]
        if p.BlackPiecesInHands[MJGI] > 0
            secondTarget = target

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJGOGI,MO_MOVE_GOTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KI

        bbp = p.bb[MJGOKI]
        if p.BlackPiecesInHands[MJKI] > 0
            secondTarget = target

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJGOKI,MO_MOVE_GOTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # KA

        bbp = p.bb[MJGOKA]
        if p.BlackPiecesInHands[MJKA] > 0
            secondTarget = target

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJGOKA,MO_MOVE_GOTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end

        # HI

        bbp = p.bb[MJGOHI]
        if p.BlackPiecesInHands[MJHI] > 0
            secondTarget = target

            while secondTarget > UInt128(0)
                from = trailing_zeros(secondTarget)
                secondTarget ⊻= BitSet[from+1]
                count += 1
                out[count] = Move(MJGOHI,MO_MOVE_GOTE,from,FLAG_UCHI,0,0)::Move
                InsertMoveAB(count,out,gs)
            end
        end
    end

    count
end

function genSlideMailbox(teban::Int,
                         p::Board,
                         out::Array{Move,1},
                         co::Int32,
                         gs::GameStatus)
    count::Int32 = co
    bbp::BitBoard    = UInt128(0)

    if teban == SENTE
        # KY
        bbp = p.bb[MJKY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end

        # KA
        bbp = p.bb[MJKA]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end

        # HI

        bbp = p.bb[MJHI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end

        # UM

        bbp = p.bb[MJUM]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end

        # RY

        bbp = p.bb[MJRY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end
    else
        # KY
        bbp = p.bb[MJGOKY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end

        # KA
        bbp = p.bb[MJGOKA]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end

        # HI

        bbp = p.bb[MJGOHI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end

        # UM

        bbp = p.bb[MJGOUM]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end

        # RY

        bbp = p.bb[MJGORY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailbox0x88(teban, from, p, out, count, gs)
        end
    end
    count
end

function genSlideMailboxQ(teban::Int,
                          p::Board,
                          out::Array{Move,1},
                          co::Int32,
                          gs::GameStatus)
    count::Int32 = co
    bbp::BitBoard    = UInt128(0)

    if teban == SENTE
        # KY
        bbp = p.bb[MJKY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end

        # KA
        bbp = p.bb[MJKA]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end

        # HI

        bbp = p.bb[MJHI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end

        # UM

        bbp = p.bb[MJUM]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end

        # RY

        bbp = p.bb[MJRY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end
    else
        # KY
        bbp = p.bb[MJGOKY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end

        # KA
        bbp = p.bb[MJGOKA]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end

        # HI

        bbp = p.bb[MJGOHI]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end

        # UM

        bbp = p.bb[MJGOUM]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end

        # RY

        bbp = p.bb[MJGORY]
        while bbp > UInt128(0)
            from = trailing_zeros(bbp)
            bbp ⊻= BitSet[from+1]
            count = mailboxQ0x88(teban, from, p, out, count, gs)
        end
    end
    count
end

#@iprofile begin
function generateBB(p::Board,           #     /* IN:盤面 */
	            out::Array{Move,1}, #     /* IN/OUT: 可能手を格納する配列*/
	            teban::Int,         #     /* 可能手を生成する手番 */
                    co::Int,
	            gs::GameStatus)

    count = Int(co) # 64bits

    count = genBB(p,out,teban,count,gs) # 32bits
    count = genSlideMailbox(teban,p,out,count,gs)
    count = genBBDrop(p,out,teban,Int(count),gs) # 32bits

    count # 32bits
end
#end # @iprofile

#@iprofile begin
function generateQBB(p::Board,           #     /* IN:盤面 */
	             out::Array{Move,1}, #     /* IN/OUT: 可能手を格納する配列*/
	             teban::Int,         #     /* 可能手を生成する手番 */
                     co::Int,
	             gs::GameStatus)

    count = Int(co) # 64bits
    count = genQBB(p,out,teban,count,gs) # 32bits
    count = genSlideMailboxQ(teban,p,out,count,gs)
    count # 32bits
end
#end # @iprofile

function consistencyBoard( q::Board)
    for i = A9:I1
        sq = q.square[i]
        if sq == MJNONE
            if (q.WhitePieces & BitSet[i]) == BitSet[i]
                println("A)break board(Index=", i, ", sq=",sq,")")
            elseif (q.BlackPieces & BitSet[i]) == BitSet[i]
                println("B)break board(Index=", i, ", sq=",sq,")")
            end
            continue
        end
        if (q.bb[sq] & BitSet[i]) == BitSet[i]
        else
            println("C)break board!(Index=", i, ", sq=",sq,")")
            DisplayBoard(q)
        end
    end
end

function validateMoves(o1::Array{Move,1},o2::Array{Move,1},n1::Int32,n2::Int32)
    # m1 and m2
    M1andM2::Int = 0
    for m1 = 1:n1
        move1 = o1[m1].move
        for m2 = 1:n2
            move2 = o2[m2].move
            if move1 == move2
                println("[A&B]:",Move2String(o1[m1]))
                M1andM2 += 1
            end
        end
    end

    # only m1
    onlyM1::Int = 0
    for m1 = 1:n1
        move1 = o1[m1].move
        fl = false
        for m2 = 1:n2
            move2 = o2[m2].move
            if move1 == move2
                fl = true
                break
            end
        end
        if fl == false
            println("[ A ]:",Move2String(o1[m1]))
            onlyM1 += 1
        end
    end

    # only m2
    onlyM2::Int = 0
    for m2 = 1:n2
        move2 = o2[m2].move
        fl = false
        for m1 = 1:n1
            move1 = o1[m1].move
            if move1 == move2
                fl = true
                break
            end
        end
        if fl == false
            println("[ B ]:",Move2String(o1[m1]))
            onlyM2 += 1
        end
    end

    println("validate information:")
    println("[A and B]:", M1andM2)
    println("[only in A]:", onlyM1)
    println("[only in B]:", onlyM2)
    if M1andM2 == n1 == n2
        println("Report: valid.")
    else
        println("Report: invalidate!")
    end
end

function makeMove(q::Board,
		  moveIdx::Int,
		  out::Array{Move,1},
		  teban::Int)
    m::Move      = out[moveIdx]
    from::Int    = seeMoveFrom(m)
    to::Int      = seeMoveTo(m)
    koma::Int    = seeMovePiece(m) & 0x0f
    komadai::Int = (teban == SENTE) ? MO_MOVE_SENTE : MO_MOVE_GOTE
    komavalTo::Int = q.square[to+1]
    captured::Int  = seeMoveCapt(m)
    flag::Int      = seeMoveFlag(m)
    omote::Int     = MJNONE

    # flagに何が入っているかで処理を分ける。

    if (flag & FLAG_UCHI) > 0
        # 打ち
        # ・打ち＝駒台から一つ取り出して、toの位置に駒を置く
        # 　同時に対象の駒のbitboardを更新する

        # 1.駒台から駒を取り除く
        if from == komadai
            if teban == SENTE
                q.WhitePiecesInHands[koma] -= 1
                if q.WhitePiecesInHands[koma] < 0
                    println("insufficient koma(White,",koma,")")
                end
            else
                q.BlackPiecesInHands[koma] -= 1
                if q.BlackPiecesInHands[koma] < 0
                    println("insufficient koma(Black,",koma,")")
                end
            end
        end
        # 2.toの位置に駒を置く
        q.square[to+1] = (teban << 4)|Int(koma)
        # 3.toの駒のbitboardに駒を置く
        q.bb[q.square[to+1]] |= BitSet[to+1]
    elseif (flag & FLAG_TORI) > 0
        # 取り
        if (flag & FLAG_NARI) > 0
            # 取りかつ成り
            # ・取り、なおかつ成り＝toの駒を駒台に置き、toにfromの駒の成った駒を置く。
            # 　fromは空っぽに。
            # 　同時にtoの駒のbitboardからtoの駒を削除し、fromのbitboardから駒を削除する。
            # 　またfromの成った駒のbitboardのtoの位置に成った駒を置く

            q.bb[q.square[to+1]]    ⊻= BitSet[to+1]
            q.bb[q.square[from+1]]  ⊻= BitSet[from+1]
            q.bb[q.square[from+1]+MJNARI] |= BitSet[to+1]
            tmpkoma = komavalTo & 0x0f
            omote = (tmpkoma > MJOU) ? tmpkoma - MJNARI : tmpkoma
            if teban == SENTE
                q.WhitePiecesInHands[omote] += 1
            else
                q.BlackPiecesInHands[omote] += 1
            end
            q.square[to+1]     = q.square[from+1] + MJNARI
            q.square[from+1]   = MJNONE
        else
            # ・取り＝toの駒を駒台に置き、toにfromの駒を置く。fromは空っぽに
            # 　同時に、toの駒のbitboardからtoの駒を削除し、さらにfromの駒の
            # 　bitboard内でfromからtoに駒を移動。
            # 普通の取り
            q.bb[q.square[to+1]]    ⊻= BitSet[to+1]
            q.bb[q.square[from+1]]  ⊻= BitSet[from+1]
            q.bb[q.square[from+1]]  |= BitSet[to+1]
            tmpkoma = komavalTo & 0x0f
            omote = (tmpkoma > MJOU) ? tmpkoma - MJNARI : tmpkoma
            if teban == SENTE
                q.WhitePiecesInHands[omote] += 1
            else
                q.BlackPiecesInHands[omote] += 1
            end
            q.square[to+1]     = q.square[from+1]
            q.square[from+1]   = MJNONE
        end
    elseif (flag & FLAG_NARI) > 0
        # 普通の成り
        # ・成り＝toにfromの駒を成って置く。fromは空っぽに。
        # 　同時に、fromの駒のbitboardから駒を削除する。またtoの駒のbitboard
        # 　に成った駒を置く
        q.bb[q.square[from+1]]        ⊻= BitSet[from+1]
        q.bb[q.square[from+1]+MJNARI] |= BitSet[to+1]
        q.square[to+1]                 = q.square[from+1] + MJNARI
        q.square[from+1]               = MJNONE
    else
        # 普通の指し手
        # ・それ以外（フラグなし）＝toにfromの駒を置く。fromは空っぽに。
        # 　同時にtoの駒のbitboard内でfromからtoに駒を移動
        q.square[to+1]        = q.square[from+1]
        q.square[from+1]      = MJNONE
        q.bb[q.square[to+1]] |= BitSet[to+1]
        q.bb[q.square[to+1]] ⊻= BitSet[from+1]
    end

    if q.square[to+1] == MJOU
        #println("move OU:kingposW=",to+1)
        q.kingposW = to+1
    elseif q.square[to+1] == MJGOOU
        #println("move OU:kingposB=",to+1)
        q.kingposB = to+1
    end

    q.WhitePieces = UInt128(0)
    q.BlackPieces = UInt128(0)
    for piece = MJFU:MJRY
        q.WhitePieces |=q.bb[piece]
        q.BlackPieces |=q.bb[piece+MJGOTE]
    end
    q.nextMove ⊻= 1

    #consistencyBoard(q)
end

function takeBack(q::Board,
		  moveIdx::Int,
		  out::Array{Move,1},
		  teban::Int)
    m::Move      = out[moveIdx]
    from::Int    = seeMoveFrom(m)
    to::Int      = seeMoveTo(m)
    koma::Int    = seeMovePiece(m) & 0x0f
    komadai::Int = (teban == SENTE) ? MO_MOVE_SENTE : MO_MOVE_GOTE
    removed::Int = seeMoveCapt(m)
    removedOmote = (removed > MJOU) ? removed - MJNARI : removed
    flag::Int    = seeMoveFlag(m)
    nari::Int    = flag & FLAG_NARI
    tori::Int    = flag & FLAG_TORI
    uchi::Int    = flag & FLAG_UCHI
    komatmp::Int = MJNONE

    # flag別に処理を行う

    if uchi == FLAG_UCHI
        # 打ち
        # ・打ち＝toを空っぽにし、toにあった駒を駒台に載せる
        # 　同時にtoの駒のbitboardを空にする
        uchiGoma::Int = q.square[to+1] & 0x0f
        if teban == SENTE
            q.WhitePiecesInHands[uchiGoma] += 1
        else
            q.BlackPiecesInHands[uchiGoma] += 1
        end
        q.bb[q.square[to+1]] ⊻= BitSet[to+1]
        q.square[to+1] = MJNONE
    elseif tori == FLAG_TORI
        # 取り
        if teban == SENTE
            q.WhitePiecesInHands[removedOmote] -= 1
            if q.WhitePiecesInHands[removedOmote] < 0
                println("insufficient pieces in komadai(White,",removedOmote,")")
            end
        else
            q.BlackPiecesInHands[removedOmote] -= 1
            if q.BlackPiecesInHands[removedOmote] < 0
                println("insufficient pieces in komadai(Black,",removedOmote,")")
            end
        end

        aiteGoma::Int = ((teban⊻1) << 4)|removed

        if nari == FLAG_NARI
            # 取りかつ成り
            # ・取りかつ成り＝駒台（removedOmote）から駒を一つ減らし、
            # 　toの位置にremovedを相手駒にして置く。fromの位置にtoの駒を表にして移動
            # 　させる
            # 　同時に、removedの相手駒のbitboardのtoの位置に駒を置き、
            # 　toの位置の駒のbitboard内からtoの位置の駒を除くと一緒に
            #   toの位置の駒の表の駒のbitboardのfromの位置に表にした駒を置く
            q.bb[aiteGoma] |= BitSet[to+1]
            q.bb[q.square[to+1]] ⊻= BitSet[to+1]
            q.bb[q.square[to+1] - MJNARI] |= BitSet[from+1]

            q.square[from+1] = q.square[to+1] -MJNARI
            q.square[to+1] = aiteGoma

        else
            # 普通の取り
            # ・取り＝駒台（removedOmote）から駒を一つ減らし、
            # 　toの位置にremovedを相手駒にして置く。fromの位置にtoの駒を移動
            # 　させる
            # 　同時に、removedの相手駒のbitboardのtoの位置に駒を置き、
            # 　toの位置の駒のbitboard内でtoからfromに駒を移動する

            q.bb[aiteGoma] |= BitSet[to+1]
            q.bb[q.square[to+1]] ⊻= BitSet[to+1]
            q.bb[q.square[to+1]] |= BitSet[from+1]

            q.square[from+1] = q.square[to+1]
            q.square[to+1] = aiteGoma
        end
    elseif nari == FLAG_NARI
        # 普通の成り
        # ・成り＝toの位置を空っぽにする。toにあった駒を表にして、fromに置く。
        # 　同時にtoにあった駒のbitboardからtoの位置の駒を削除する
        # 　toの位置にあった駒の表の駒のbitboardの、fromの位置に表の駒を置く
        q.bb[q.square[to+1]] ⊻= BitSet[to+1]
        q.bb[q.square[to+1] - MJNARI] |= BitSet[from+1]

        q.square[from+1] = q.square[to+1] - MJNARI
        q.square[to+1] = MJNONE

    else
        # 普通の指し手
        # ・普通の手＝toの位置を空っぽにする。toの位置の駒をfromに移動する。
        # 　同時に、toの位置の駒のbitboard内でtoからfromに駒を移動する
        q.bb[q.square[to+1]] ⊻= BitSet[to+1]
        q.bb[q.square[to+1]] |= BitSet[from+1]

        q.square[from+1] = q.square[to+1]
        q.square[to+1] = MJNONE
    end

    if uchi == 0
        if q.square[from+1] == MJOU
            q.kingposW = from+1
            #println("undo OU: kingposW = ⊻(from+1)")
        elseif q.square[from+1] == MJGOOU
            q.kingposB = from+1
            #println("undo OU: kingposB = ⊻(from+1)")
        end
    end

    q.WhitePieces = UInt128(0)
    q.BlackPieces = UInt128(0)
    for piece = MJFU:MJRY
        q.WhitePieces |=q.bb[piece]
        q.BlackPieces |=q.bb[piece+MJGOTE]
    end
    q.nextMove ⊻= 1
    # consistencyBoard(q)
end

function islessA(a::Move, b::Move)
    if a.move > b.move
        return true
    else
        return false
    end
end

function BBTest2(gs::GameStatus)
    bo = Board()
    sfenHirate = "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"
    sfen = "8l/1l+R2P3/p2pBG1pp/kps1p4/Nn1P2G2/P1P1P2PP/1PS6/1KSG3+r1/LN2+p3L w Sbgn3p 124"::String
    board = InitSFEN(sfen, bo)
    DisplayBoard(board)
    out = [Move(0,0,0,0,0,0) for n = 1:10000]
    out2 = [Move(0,0,0,0,0,0) for n = 1:10000]
    println("generate moves!")
    num = generateBB(board,out,GOTE,0,gs)
    num2 = generateMoves(board,out2,GOTE,0,gs)
    if num != num2
        println("different moves!")
    else
        validateMoves(out,out2,num,num2)
    end
end

function BBTestForMoveGeneration(gs::GameStatus)
    bo = Board()
    sfenHirate = "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"
    board = InitSFEN(sfenHirate, bo)
    #DisplayBoard(board)
    sfen = "8l/1l+R2P3/p2pBG1pp/kps1p4/Nn1P2G2/P1P1P2PP/1PS6/1KSG3+r1/LN2+p3L w Sbgn3p 124"::String
    bo2 = Board()
    board2 = InitSFEN(sfen, bo2)
    DisplayBoard(board2)
    out = [Move(0,0,0,0,0,0) for n = 1:10000]
    out2 = [Move(0,0,0,0,0,0) for n = 1:10000]
    println("generate moves!")
    num::Int32 = 0
    tic()
    for x = 1:1000000 # 10000
        num = generateBB(board2,#board,
	                 out,                    #     /* IN/OUT: 可能手を格納する配列*/
	                 SENTE, #board.nextMove,         #     /* 可能手を生成する手番 */
                         0,
	                 gs)
    end
    toc()
    sort( out, islessA)

    println("return value of generate move = ", num)
    for i = 1:num
        ####println(hex(out[i].move),":",Move2String(out[i]))
        #println("1")
        #DisplayBoard(board2)
        makeMove(board2,
		 i,
		 out,
		 SENTE)
        #println("2")
        #DisplayBoard(board2)
        takeBack(board2,
		 i,
		 out,
		 SENTE)
        #println("3")
        #DisplayBoard(board2)
    end
    tic()
    for x = 1:1000000 # 10000
        num = generateMoves(board2,#board,
	                    out2,                    #     /* IN/OUT: 可能手を格納する配列*/
	                    SENTE, #board.nextMove,         #     /* 可能手を生成する手番 */
                            0,
	                    gs)
    end
    toc()
    println("return value of generate move = ", num)

    sort( out2, islessA)
    for i = 1:num
        #println(hex(out2[i].move),":",Move2String(out[i]))
        if out[i].move != out2[i].move
            #println("DIFF:  ", Move2String(out[i]),"<>",Move2String(out2[i]))
        else
            #println("MATCH: ", Move2String(out[i]),"<>",Move2String(out2[i]))
        end
    end

    tic()
    for x = 1:1000000 # 10000
        num = generateBB(board2,#board,
	                 out,                    #     /* IN/OUT: 可能手を格納する配列*/
	                 GOTE, #board.nextMove,         #     /* 可能手を生成する手番 */
                         0,
	                 gs)
    end
    toc()
    sort( out, islessA)
    println("return value of generate move = ", num)
    for i = 1:num
        #println(hex(out[i].move),":",Move2String(out[i]))
        #println("1")
        #DisplayBoard(board2)
        makeMove(board2,
		 i,
		 out,
		 GOTE)
        #println("2")
        #DisplayBoard(board2)
        takeBack(board2,
		 i,
		 out,
		 GOTE)
        #println("3")
        #DisplayBoard(board2)
    end
    tic()
    for x = 1:1000000 # 10000
        num = generateMoves(board2,#board,
	                    out2,                    #     /* IN/OUT: 可能手を格納する配列*/
	                    GOTE, #board.nextMove,         #     /* 可能手を生成する手番 */
                            0,
	                    gs)
    end
    toc()
    sort( out2, islessA)
    println("return value of generate move = ", num)
    for i = 1:num
        #println(hex(out2[i].move),":",Move2String(out[i]))
        if out[i].move != out2[i].move
            #println("DIFF:  ", Move2String(out[i]),"<>",Move2String(out2[i]))
        else
            #println("MATCH: ", Move2String(out[i]),"<>",Move2String(out2[i]))
        end
    end

    #@iprofile report

    v::Int = Eval( SENTE, board2)
    println("eval = ",v)
end

max_stars_repo_name: kimrin/MechajyoForWindows

max_issues_repo_name: kimrin/MechajyoForWindows

max_forks_repo_name: kimrin/MechajyoForWindows


text:
A = matrixdepot("hankel", [1:5;])
@test A == matrixdepot("hankel", 5)

r1 = rand(5)
r2 = rand(5)
B = matrixdepot("hankel", r1, r2)
@test issymmetric(B)

C = matrixdepot("hankel", Int, [1,2,3], [3, 4, 5, 6])
@test C[3,4] == 6
@test C[2,4] == C[3,3]
println("'hankel' passed test...")


text:
# ==========
# TSF
# ==========
using BenchmarkTools, MLJTime

datasets = [
    #"ACSF1",
    "Adiac",
    #"AllGestureWiimoteX",
    #"AllGestureWiimoteY",
    #"AllGestureWiimoteZ",
    "ArrowHead",
    "Coffee",
    "Beef",
    "BeetleFly",
    "BirdChicken",
    "BME",
    "Car",
    "CBF",
    "Chinatown",
    #"ChlorineConcentration",
    #"CinCECGTorso",
    "Computers",
    "CricketX",
    "CricketY",
    "CricketZ",
    #"Crop",
    "DiatomSizeReduction",
    "DistalPhalanxOutlineCorrect",
    "DistalPhalanxOutlineAgeGroup",
    "DistalPhalanxTW",
    # "DodgerLoopDay",
    # "DodgerLoopGame",
    # "DodgerLoopWeekend",
    "Earthquakes",
    "ECG200",
    #"ECG5000",
    "ECGFiveDays",
    #"ElectricDevices",
    "EOGHorizontalSignal",
    "EOGVerticalSignal",
    #"EthanolLevel",
    #"FaceAll",
    "FaceFour",
    #"FacesUCR",
    "FiftyWords",
    "Fish",
    #"FordA",
    #"FordB",
    #"FreezerRegularTrain",
    "FreezerSmallTrain",
    "Fungi",
    # "GestureMidAirD1",
    # "GestureMidAirD2",
    # "GestureMidAirD3",
    # "GesturePebbleZ1",
    # "GesturePebbleZ2",
    "Ham",
    #"HandOutlines",
    "Haptics",
    "Herring",
    "InlineSkate",
    "InsectEPGRegularTrain",
    "InsectEPGSmallTrain",
    #"InsectWingbeatSound",
    "ItalyPowerDemand",
    "LargeKitchenAppliances",
    "Lightning2",
    "Lightning7",
    "Mallat",
    "Meat",
    #"MedicalImages",
    # "MelbournePedestrian",
    "MiddlePhalanxOutlineCorrect",
    "MiddlePhalanxOutlineAgeGroup",
    "MiddlePhalanxTW",
    #"MixedShapesRegularTrain",
    #"MixedShapesSmallTrain",
    "MoteStrain",
    #"NonInvasiveFetalECGThorax1",
    #"NonInvasiveFetalECGThorax2",
    "OliveOil",
    "OSULeaf",
    #"PhalangesOutlinesCorrect",
    #"Phoneme",
    # "PickupGestureWiimoteZ",
    "PigAirwayPressure",
    "PigArtPressure",
    "PigCVP",
    # "PLAID",
    "Plane",
    "PowerCons",
    "ProximalPhalanxOutlineCorrect",
    "ProximalPhalanxOutlineAgeGroup",
    "ProximalPhalanxTW",
    "RefrigerationDevices",
    #"Rock",
    "ScreenType",
    #"SemgHandGenderCh2",
    #"SemgHandMovementCh2",
    #"SemgHandSubjectCh2",
    # "ShakeGestureWiimoteZ",
    "ShapeletSim",
    #"ShapesAll",
    "SmallKitchenAppliances",
    "SmoothSubspace",
    "SonyAIBORobotSurface1",
    "SonyAIBORobotSurface2",
    # "StarlightCurves",
    #"Strawberry",
    #"SwedishLeaf",
    "Symbols",
    "SyntheticControl",
    "ToeSegmentation1",
    "ToeSegmentation2",
    "Trace",
    "TwoLeadECG",
    #"TwoPatterns",
    "UMD",
    #"UWaveGestureLibraryAll",
    #"UWaveGestureLibraryX",
    #"UWaveGestureLibraryY",
    #"UWaveGestureLibraryZ",
    #"Wafer",
    "Wine",
    "WordSynonyms",
    "Worms",
    "WormsTwoClass"
    #"Yoga"
]

DATA_DIR_BENCH = "/Users/aa25desh/Univariate_ts"

@assert DATA_DIR_BENCH != false  "path to the dataset is missing"

io =  open("results_knn.txt", "w")
write(io, "dataset,Accuracy\n")

for dataset in datasets

   Path_train = joinpath(DATA_DIR_BENCH, dataset, string(dataset, "_", uppercase("TRAIN"), ".ts" ))
   Path_test = joinpath(DATA_DIR_BENCH, dataset, string(dataset, "_", uppercase("TEST"), ".ts" ))

   test, train =  load_ts_file.([Path_test, Path_train])
   X_test, X_train, y_test, y_train = test[1], train[1], test[2], train[2]
   X_test, X_train = matrix(X_test), matrix(X_train)
   for n_trees in [200]
       model = TimeSeriesKNNClassifier()
       mach = machine(model, X_train, y_train)
       fit!(mach)
       print(dataset)
       @time fit!(mach)
       #fit_bench = ( fit_bench.times |> mean )*10^-9   #As fit_bench.times is in nano seconds
       y_pred = predict_mode(mach, X_test)
       @time predict(mach, X_test)
       #predict_bench = ( predict_bench.times |> mean )*10^-9
       Accuracy = accuracy(y_pred, y_test)
       write(io, "$dataset, $Accuracy\n")
       print("$dataset, $Accuracy\n")
   end
end
close(io)


text:
module apfamet

using DataFrames
using GLM
using Gadfly
using Compose
using MultivariateStats

#using FTPClient
#using GZip

#Using a PyCall/Biopython solution to translation and sequencing reading/writing for the time being due to apparent bugs in BioJulia's translate function (see https://github.com/BioJulia/Bio.jl/issues/133) and lack of stop codons in amino acids (https://github.com/BioJulia/Bio.jl/issues/134)

include(joinpath(Pkg.dir("apfamet"),"src","pycall_translation_function.jl"))
include(joinpath(Pkg.dir("apfamet"),"src","hmmer_function.jl"))
include(joinpath(Pkg.dir("apfamet"),"src","pycall_extract_seqs.jl"))
include(joinpath(Pkg.dir("apfamet"),"src","plotting.jl"))
include(joinpath(Pkg.dir("apfamet"),"src","sub_project.jl"))
include(joinpath(Pkg.dir("apfamet"),"src","statistics.jl"))
include(joinpath(Pkg.dir("apfamet"),"src","newproject.jl"))
include(joinpath(Pkg.dir("apfamet"),"src","database.jl"))

function locate_default_database()
	print(joinpath(Pkg.dir("apfamet"),"db"))
end

end

max_stars_repo_name: ianpgm/apfamet

max_issues_repo_name: ianpgm/apfamet

max_forks_repo_name: ianpgm/apfamet


text:
using Test
using SumOfSquares
using DynamicPolynomials

function univariate_sum_test(optimizer,
                   config::MOIT.Config,
                   cone::SumOfSquares.PolyJuMP.PolynomialSet)
    atol = config.atol
    rtol = config.rtol

    model = _model(optimizer)

    @polyvar x y
    # (x - 1)^2 + (y + 1)^2
    cref = @constraint(model, x^2 + y^2 + 2(y - x) + 2 in cone, sparsity=Sparsity.Variable())

    optimize!(model)

    @test termination_status(model) == MOI.OPTIMAL

    @test primal_status(model) == MOI.FEASIBLE_POINT

    p = gram_matrix(cref)
    @test p isa SumOfSquares.SparseGramMatrix
    @test length(p.sub_gram_matrices) == 2
    @test getmat(p.sub_gram_matrices[1]) ≈ ones(2, 2) atol=atol rtol=rtol
    @test p.sub_gram_matrices[1].basis.monomials == [y, 1]
    @test getmat(p.sub_gram_matrices[2]) ≈ [1 -1; -1 1] atol=atol rtol=rtol
    @test p.sub_gram_matrices[2].basis.monomials == [x, 1]

    S = SumOfSquares.SOSPolynomialSet{
        SumOfSquares.FullSpace, Monomial{true}, MonomialVector{true}, SumOfSquares.Certificate.Sparsity.Ideal{Sparsity.Variable, SumOfSquares.Certificate.MaxDegree{typeof(cone), MonomialBasis}}
    }
    @test list_of_constraint_types(model) == [(Vector{AffExpr}, S)]
    test_delete_bridge(
        model, cref, 0,
        ((MOI.VectorOfVariables, MOI.Nonnegatives, 0),
         (MOI.VectorOfVariables, MOI.PositiveSemidefiniteConeTriangle, 0)
        ))
end
sos_univariate_sum_test(optimizer, config)   = univariate_sum_test(optimizer, config, SOSCone())
sd_tests["sos_univariate_sum"] = sos_univariate_sum_test
sdsos_univariate_sum_test(optimizer, config) = univariate_sum_test(optimizer, config, SDSOSCone())
soc_tests["sdsos_univariate_sum"] = sdsos_univariate_sum_test
dsos_univariate_sum_test(optimizer, config)  = univariate_sum_test(optimizer, config, DSOSCone())
linear_tests["dsos_univariate_sum"] = dsos_univariate_sum_test

max_stars_repo_name: blegat/SumOfSquares

max_issues_repo_name: blegat/SumOfSquares

max_forks_repo_name: blegat/SumOfSquares


text:
## Barycentric formula

export bary,barysum

function bary(v::Vector{Float64},pts::Vector{Float64},x::Float64)
  n=length(v)
  @assert n == length(pts)

  retd = .5/(x-pts[1])
  retn = v[1]*retd

  for i = 2:2:n-1
    @inbounds cd = 1./(x-pts[i])
    retd -= cd
    @inbounds retn -= v[i]*cd
  end

  for i = 3:2:n-1
    @inbounds cd = 1./(x-pts[i])
    retd += cd
    @inbounds retn += v[i]*cd
  end

  cd = .5*(-1.)^(n-1)/(x-pts[n])
  retd += cd
  retn += v[n]*cd

  retn/retd
end

bary(v::Vector{Float64},x::Float64)=bary(v,chebyshevpoints(length(v);kind=2),x)

function randomadaptivebary(f::Function)
  r=rand()
  fr=f(r)
  err=1.
  logn=1

  tol=200eps()

  vals=Float64[]

  while err > tol
      n=2^logn + 1
      pts=chebyshevpoints(n;kind=2)
      vals=f(pts)
      err=abs(bary(vals,pts,r)-fr)/n
      logn+=1
  end

  vals
end