%**************************************************************************
%This file initializes the simulation program.
%
%Input:
%param, parameter structure
%
%Output:
%block, structure containing permanent magnet block information
%
%Zachary Wolf, 9/14/10

function [block] = magic_fingers_block_init(param)

%Global
global mu_0;

%Parameters
br = param.pm_br;
dim = param.pm_dim;
num_x_pos = param.pm_num_x_pos;
x_dis = param.pm_x_dis;
y_dis = param.pm_y_dis;
z_pos = param.pm_z_pos;
m_dir_up = param.pm_m_dir_up;
m_dir_lo = param.pm_m_dir_lo;
div_size = param.pm_div_size;

%Determine the block x positions
x_pos = zeros(1, num_x_pos);
x_pos(1) = -((num_x_pos - 1) / 2) * x_dis;  %Works with even or odd number of blocks
for ii = 2 : num_x_pos
    x_pos(ii) =  x_pos(ii - 1) + x_dis;
end
x_pos_up = x_pos;
x_pos_lo = x_pos;

%Determine the block y positions
y_pos_up = zeros(1, num_x_pos);
y_pos_lo = zeros(1, num_x_pos);
for ii = 1 : num_x_pos
    y_pos_up(ii) =  y_dis(ii) + dim(2) / 2;
    y_pos_lo(ii) =  -y_dis(ii) - dim(2) / 2;
end

%Determine the block z positions
z_pos = z_pos * ones(1, num_x_pos);
z_pos_up = z_pos;
z_pos_lo = z_pos;

%Determine the block remnant fields
br = br * ones(1, num_x_pos);
br_up = br;
br_lo = br;

%Set up magnetization constants
%Convention: +x = 1, -x = 2, +y = 3, -y = 4
m_vec(1, :) = [1, 0, 0];   %+x
m_vec(2, :) = [-1, 0, 0];  %-x
m_vec(3, :) = [0, 1, 0];   %+y
m_vec(4, :) = [0, -1, 0];  %-y

%Determine the block magnetization vectors
m_up = zeros(num_x_pos, 3);
m_lo = zeros(num_x_pos, 3);
for ii = 1 : num_x_pos
    m_up(ii, :) = (br_up(ii) / mu_0) * m_vec(m_dir_up(ii), :);
    m_lo(ii, :) = (br_lo(ii) / mu_0) * m_vec(m_dir_lo(ii), :);
end

%Store the block dimensions
dim_up = zeros(num_x_pos, 3);
dim_lo = zeros(num_x_pos, 3);
for ii = 1 : num_x_pos
    dim_up(ii, :) = dim;
    dim_lo(ii, :) = dim;
end

%Fill the block structure
block(2 * num_x_pos) = struct('num', 0, 'div_size', 0, 'br', 0, 'm', [0, 0, 0,], 'dim', [0, 0, 0], 'rot', [0, 0, 0; 0, 0, 0; 0, 0, 0], 'trans', [0, 0, 0]);
nn = 0;
for ii = 1 : num_x_pos  %Upper blocks
    nn = nn + 1;
    block(nn).num = nn;
    block(nn).div_size = div_size;
    block(nn).br = br_up(ii);
    block(nn).m = m_up(ii, :);
    block(nn).dim = dim_up(ii, :);
    block(nn).rot = [1, 0, 0; 0, 1, 0; 0, 0, 1];
    block(nn).trans = [x_pos_up(ii), y_pos_up(ii), z_pos_up(ii)];
end
for ii = 1 : num_x_pos  %Lower blocks
    nn = nn + 1;
    block(nn).num = nn;
    block(nn).div_size = div_size;
    block(nn).br = br_lo(ii);
    block(nn).m = m_lo(ii, :);
    block(nn).dim = dim_lo(ii, :);
    block(nn).rot = [1, 0, 0; 0, 1, 0; 0, 0, 1];
    block(nn).trans = [x_pos_lo(ii), y_pos_lo(ii), z_pos_lo(ii)];
end

%Done
end
