% Index-finding routine for a finite difference model of electrical
% impedance tomography (EIT) in a square. We assume that the square is
% divided into NxN pixels with N an odd integer.
%
% Outside edges of boundary pixels, understood as electrodes used in EIT
% measurements are numbered counterclockwise, starting from the middle
% pixel on the right ("Eastern") side of the square. Note that corner
% pixels have only one electrode.
%
% Given an input index, or electrode number, "b_ind" in the range
% 1,2,3,...,4*(N-1), this routine finds the row and column indices of the
% corresponding boundary pixel in the NxN grid.
%
% See also: gind2bind.m
%
% Arguments:
% N       grid size parameter: NxN pixels
% b_ind   electrode number, in the range from 1 to 4*(N-1)
%
% Returns:
% row   row index in the NxN grid
% col   column index in the NxN grid
% side  which side the electrode is located ('E','N','W','S')
%
% Samuli Siltanen March 2025

function [row,col,side] = bind2gind(N,b_ind)

% Record number of electrodes
Ne = 4*(N-1);

% Check that N is odd
if mod(N,2)==0
    error('N should be an odd integer')
end
% Check that b_ind has reasonable value
if (b_ind<1)|(b_ind>Ne)
    error('Index b_ind should be in the range 1,2,3,...,4*(N-1)')
end

% Define halfN so that N = 2*halfN+1
halfN = floor(N/2);

% Perform all possible cases of electrode numbers
if b_ind <= halfN+1 % upper half of the right (Eastern) edge
    row = halfN+2-b_ind;
    col = N;
    side = 'E'; 
elseif (b_ind>halfN+1)&(b_ind<=(halfN+1+(N-1))) % top (Northern) edge
    row = 1;
    col = N-(b_ind-halfN-1);
    side = 'N'; 
elseif (b_ind>(halfN+1+(N-1)))&(b_ind<=(halfN+1+2*(N-1))) % left (Western) edge
    row = b_ind-N-halfN+1;
    col = 1;
    side = 'W'; % Western side = left side
elseif (b_ind>(halfN+1+2*(N-1)))&(b_ind<=(halfN+1+3*(N-1))) % bottom (Southern) edge
    row = N;
    col = b_ind-2*N-halfN+2;
    side = 'S'; 
else % Remaining electrodes in the right (Eastern) edge
    row = N-(b_ind-3*(N-1)-halfN-1);
    col = N;
    side = 'E'; 
end






