#include ../data/case14.txt
#include ../lib/idx_gen.txt
#include ../lib/idx_bus.txt
#include ../lib/idx_brch.txt
#include ../lib/make_y_bus.txt
#include ../lib/dsbus_dv.txt
#include ../lib/make_jac.txt
#include ../lib/make_sdzip.txt
#include ../lib/make_sbus.txt

// get bus index lists of each type of bus
// get generator status
// bus_gen_status = zeros(size(bus, 1), 1);
// bus_gen_status(gen(:, GEN_BUS)) = gen(:, GEN_STATUS) > 0;
nb = size(bus, 1);
ng = size(gen, 1);
Cg = sparse(slice(gen, [0], [GEN_BUS-1,GEN_BUS]), (1:ng)', slice(gen, [0], [GEN_STATUS-1,GEN_STATUS]) > 0, nb, ng);  // gen connection matrix
                                        // element i, j is 1 if, generator j at bus i is ON
bus_gen_status = Cg * ones(ng, 1);      // number of generators at each bus that are ON

// form index lists for slack, PV, and PQ buses
bus_type = slice(bus, [0], [BUS_TYPE-1,BUS_TYPE]); // bus type column
ref = find(bus_type == REF && bus_gen_status);   // reference bus index
pv  = find(bus_type == PV  && bus_gen_status);   // PV bus indices
pq  = find(bus_type == PQ || ~~bus_gen_status);   // PQ bus indices


// initial state
// V0    = ones(size(bus, 1), 1);            // flat start
V0  = slice(bus, [0], [VM-1,VM]) .* exp(c(0,1) * pi/180 * slice(bus, [0], [VA-1,VA]));
vcb = ones(size(V0));           // create mask of voltage-controlled buses
vcb(pq) = 0;                    // exclude PQ buses
k = find(vcb(gbus));            // in-service gens at v-c buses
V0(gbus(k)) = gen(on(k), VG) ./ abs(V0(gbus(k))).* V0(gbus(k));

Ybus = make_y_bus(baseMVA, bus, branch);
r = make_sbus(baseMVA, bus, gen, 1, 1, 1);
return r;