% script filename: compile_pwinsp_v6b.m
% (previously: sort_power_inspect2_v6.m)
% Script for compiling one excel file from multiple Roamer Arm data files.

%{
Created by Mark Smith
Princeton Plasma Physics Laboratory 
James Forrestal Campus 
P.O. Box 451 
Princeton, NJ 08543-0451 

First version: 12/17/07, revised 1/07/08
..........................................................................
Validate Winding Coil Deviations Notes:
Two to three script files form the overall algorithm to create one excel file from 
the multiple Roamer Arm PowerInspect reports developed during the winding coil process.
After this file is created, it is used to re-calculate the current center deviations.
..........................................................................
Algorithm part 2: compile_pwinsp_v6b.m
This code sorts, merges, averages and then writes data into one excel file. 
The resulting excel file is formatted for use with current_center_deviations_v2.m.
....................................................................................
Script notes: compile_pwinsp_v6b.m
This code is used for B coils only.
INPUTS
(1) set_loc is (100,16). 
The rows of data correspond to the order in which the data sets were 
found. The row index does not necessarily match the clamp numbers.
set_loc columns reflect data for the files baseA12/B12,septumA12/B12,topA12/B12,
sideA12/B12 data.

(2) clp_sequ is (100,32). 
The data within reflects clamp label sequence as fond the power inspection reports. 
Each pair of columns in clp_sequ represent clamp label, label index. 
Each pair of columns reflects the data for baseA12/B12,septumA12/B12,topA12/B12,sideA12/B12.

OUTPUT
winding_data_B.xls
The Excel tab labels and sequence are: 
baseA,baseB, septumA, septumB,topA,topB, sideA, sideB .
Note: When processing the Roamer Arm data, only the first 4 (for base/top) and 
the first 12 (for septum/side) rows of data for each data set were used.
The columns correspond to the following information.
column A:    clamp labels AND/OR sequence
columns B-D: X,Y,Z coordinate data
columns E-G: dx,dy,dz
column H:    3D deviation

%}

clc
clear

% Capture Current Matlab Directory.
working_matlab_dir=pwd;

% Load the string s1 (filenames) mat file.
[fname fpath]=uigetfile('*.mat','Select string s1 .mat (filenames) file.');
s1 = struct2cell(open(fname));
% Load the data set location mat file.
[fname fpath]=uigetfile('*.mat','Select data set location mat file.');
dset =cell2mat(struct2cell(open(fname)));
% Load the clamp sequence mat file.
[fname fpath]=uigetfile('*.mat','Select clamp sequence mat file.');
clps =cell2mat(struct2cell(open(fname)));

% Load Excel tab labels.
tabs = struct2cell(open('Icenter_tabs.mat'));

% Set current directory for loading excel files.
excel_dir = uigetdir(pwd,'Select Directory Location of Excel Files.');
cd(excel_dir);

% Start program execution timer to keep track of algorithm duration.
tic;


dbc1=16; % "debugging" loop limiter for developing code max is 16.

% *********************************************************************
% Section 1
% Combine clamp sequence and data set locations into one correlated array.
% *********************************************************************
clp_dset=zeros(96,16);  % Initializing.
n3 = zeros(1,2,16);     % Initializing.

for fcc=1:dbc1    % Increments by 1, overall loop is for each 2 columns of clps(i.e. clp_sequ.mat). 
% NOTE: clps size = [100, 32]. Every 2 columns correlates to (1 of 16) bs/tp/sep/sd files.
    clps1=clps(:,((fcc*2)-1));  % use only 1 column at a time.
    dset1=dset(:,fcc);    % use only 1 column at a time.
    indcl=find(clps1>0);  % find indices of data elements.
    indds=find(dset1>0);  % find indices of data elements.
    nclp=length(indcl);  % nclp represents the number of nonzero elements of clps.
    ndset=length(indds); % ndset represents the number of nonzero elements of dset.
    %n3=0;   %Initializing.
    for cc1=1:min(nclp,ndset)
% test for Non-integer index, due to Non-standard labels,(i.e.: n.3 condition)
          
        if clps1(indcl(cc1))==floor(clps1(indcl(cc1))) % currently NOT n.3 condition.
           clp_dset(clps1(indcl(cc1)),fcc)=dset1(cc1); % stores dset value. 
        else    % n.3 condition is present. Store relative index for use later.
            if size(n3,1)==1 && n3(1,1,fcc)==0
               n3(1,1,fcc)=floor(clps1(indcl(cc1)));    % relative clamp #
               n3(1,2,fcc)=dset1(cc1);                  % data set index.
            else
                n3(size(n3,1)+1,1,fcc)=floor(clps1(indcl(cc1)));% relative clamp #
                n3(size(n3,1)+1,2,fcc)=dset1(cc1);              % data set index.
            end
        end
    end
end

if size(n3,1)>1
     msgbox('n.3 condition > 1. Check Input Data');
     return
end

df1=0;% Initializing.
df2=0;% Initializing.
df3=0;% Initializing.

for fcc=1:2:15
    temp=0;% Initializing.
    % Condition when only the 1st data set has n.3 condition and needs data
    % shift/insert. Must still shift 2nd data set.
    if n3(1,1,fcc)>0 & n3(1,1,fcc+1)==0
        df1=df1+1;
        rcn=(n3(1,1,fcc));  % Relative Clamp #, correlates to clp_dset row index.
        % Shift/Insert data for 1st set of clp_dset data pair.
        last=find(clp_dset(:,fcc)>0,1,'last');
        temp=clp_dset((rcn+1:last),fcc); % copies (n+1:last) for data shift.
        clp_dset(rcn+1,fcc)=n3(1,2,fcc); % insert n3 condition dset value.
        clp_dset((rcn+2:last+1),fcc)=temp;  % complete shifting of data.
        % Only data shift, all data, for 2nd set of clp_dset data pair.
        temp=0;
        first=find(clp_dset(:,fcc+1)>0,1,'first');
        last=find(clp_dset(:,fcc+1)>0,1,'last');
        temp=clp_dset((first:last),fcc+1);
        clp_dset(:,fcc+1)=0;
        clp_dset((first+1:last+1),fcc+1)=temp;
    % Condition when only the 2nd data set has n.3 condition and needs data
    % shift/insert. Must still shift 1st data set.       
    elseif n3(1,1,fcc)==0 & n3(1,1,fcc+1)>0
        df2=df2+1;
        rcn=(n3(1,1,fcc+1));  % Relative Clamp #, correlates to clp_dset row index.
        % Shift/Insert data for 2nd set of clp_dset data pair.
        last=find(clp_dset(:,fcc+1)>0,1,'last');
        temp=clp_dset((rcn+1:last),fcc+1); % copies (n+1:last) for data shift.
        clp_dset(rcn+1,fcc+1)=n3(1,2,fcc+1); % insert n3 condition dset value.
        clp_dset((rcn+2:last+1),fcc+1)=temp;  % complete shifting of data.
        % Only data shift, all data, for 1st set of clp_dset data pair.
        temp=0;
        first=find(clp_dset(:,fcc)>0,1,'first');
        last=find(clp_dset(:,fcc)>0,1,'last');
        temp=clp_dset((first:last),fcc);
        clp_dset(:,fcc)=0;
        clp_dset((first+1:last+1),fcc)=temp;
    % Condition when both data sets have n.3 condition.
    elseif n3(1,1,fcc)>0 &  n3(1,1,fcc+1)>0
% Check to ensure relative clamp #'s are equal. If NOT so, abort/report error.
        if n3(1,1,fcc)~= n3(1,1,fcc+1)
            msgbox('n.3 conditions are not the same.');
            return
        else
            df3=df3+1;
            rcn=(n3(1,1,fcc));  % Relative Clamp #, correlates to clp_dset row index.
            % Shift/Insert data for 1st set of clp_dset data pair.
            last=find(clp_dset(:,fcc)>0,1,'last');
            temp=clp_dset((rcn+1:last),fcc); % copies (n+1:last) for data shift.
            clp_dset(rcn+1,fcc)=n3(1,2,fcc); % insert n3 condition dset value.
            clp_dset((rcn+2:last+1),fcc)=temp;  % complete shifting of data.
            % Shift/Insert data for 2nd set of clp_dset data pair.
            % Relative Clamp #, is the same for 1st and 2nd data sets.
            temp=0;
            last=find(clp_dset(:,fcc+1)>0,1,'last');
            temp=clp_dset((rcn+1:last),fcc+1); % copies (n+1:last) for data shift.
            clp_dset(rcn+1,fcc+1)=n3(1,2,fcc+1); % insert n3 condition dset value.
            clp_dset((rcn+2:last+1),fcc+1)=temp;  % complete shifting of data.
        end
    end
end

% *********************************************************************
% Section 2
% Simutaneously: determine overlap point condition, calculate average if
% required, and store data into excel.
% string s1 filename sequence: baseA12/B12,septumA12/B12,topA12/B12,sideA12/B12.
% *********************************************************************

% Create storage row (start/end) indices for base/top data.
rwend_bt=(1:1:96)*5;
rwst_bt=zeros(size(rwend_bt));
rwst_bt(1,1)=1;
rwst_bt(1,(2:end))=rwend_bt(1,(1:95))+1; 

% Create storage row (start/end) indices for septum/side data.
rwend_ss=(1:1:96)*12;
rwst_ss=zeros(size(rwend_ss));
rwst_ss(1,1)=1;
rwst_ss(1,(2:end))=rwend_ss(1,(1:95))+1; 

dbc2=96; % "debugging" loop limiter for developing code max is 96.
n_bt=0;
n_ss=0;
for fcc=1:2:dbc1
  % Load pairs of Excel files per s1 cell array of filenames.
    dt1 = xlsread(strcat(excel_dir,'\',s1{1}{fcc}),'A1:N4000');
    dt2 = xlsread(strcat(excel_dir,'\',s1{1}{fcc+1}),'A1:N4000');  

    switch num2str(fcc)     % toggle code between base/top & septum/side
        % Code for base/top data processing.
        case  {'1', '3', '9', '11'}
             n_bt=n_bt+1;
             vals=zeros(4,7);   % initialize array.
            for blcc=1:dbc2
               % Determiine if overlapping points. If so, calculate the
               % average values.
               if clp_dset(blcc,fcc)>0 && clp_dset(blcc,fcc+1)>0
                   rwn = clp_dset(blcc,fcc);
                   temp1 = dt1((rwn:rwn+3),(4:10));
                   rwn = clp_dset(blcc,fcc+1);
                   temp2 = dt2((rwn:rwn+3),(4:10));
                   vals =(temp1+temp2)/2;
               else         % NOT an overlapping condition.
                   if  clp_dset(blcc,fcc)>0
                       rwn = clp_dset(blcc,fcc);
                       vals = dt1((rwn:rwn+3),(4:10));
                   end
                   if clp_dset(blcc,fcc+1)>0
                       rwn = clp_dset(blcc,fcc+1);
                       vals = dt2((rwn:rwn+3),(4:10));
                   end
               end
               excel_data_bt(rwst_bt(blcc),1,n_bt)=blcc;
               excel_data_bt((rwst_bt(blcc)+1:rwend_bt(blcc)),(2:8),n_bt)= vals;
            end
            
        % Code for septum/side data processing.
        case  {'5', '7', '13', '15'}
            n_ss=n_ss+1;
            vals=zeros(11,7);   % initialize array.
            for blcc=1:dbc2
               if clp_dset(blcc,fcc)>0 && clp_dset(blcc,fcc+1)>0
                   rwn = clp_dset(blcc,fcc);
                   temp1 = dt1((rwn:rwn+10),(4:10));
                   rwn = clp_dset(blcc,fcc+1);
                   temp2 = dt2((rwn:rwn+10),(4:10));
                   vals =(temp1+temp2)/2;
               else      % NOT an overlapping condition.
                   if  clp_dset(blcc,fcc)>0
                       rwn = clp_dset(blcc,fcc);
                       vals = dt1((rwn:rwn+10),(4:10));
                   end
                   if clp_dset(blcc,fcc+1)>0
                       rwn = clp_dset(blcc,fcc+1);
                       vals = dt2((rwn:rwn+10),(4:10));
                   end
               end
               excel_data_ss(rwst_ss(blcc),1,n_ss)=blcc;
               excel_data_ss((rwst_ss(blcc)+1:rwend_ss(blcc)),(2:8),n_ss)= vals;
           end 
            
    end
 end

% Reset Directory to Initial Matlab Directory
cd(working_matlab_dir);
   
% ***********************************************************************
% Write Compiled information to Excel data file.
% Excel tab sequence is: baseA/B,septumA/B,topA/B,sideA/B with correspondence to 
% this algorithm is as follows:
% excel_data_bt(:,:,X) for X = 1 to 4 with baseA/B, topA/B.
% excel_data_ss(:,:,X) for X = 1 to 4 with septumA/B, sideA/B.
% ***********************************************************************

for wrtc1=1:8
    sheet=tabs{1}(1,wrtc1);
    switch num2str(wrtc1)
        case {'1'}
        xlswrite('winding_data_B',excel_data_bt(:,:,1),sheet{1})
        case {'2'}
        xlswrite('winding_data_B',excel_data_bt(:,:,2),sheet{1})
        case {'3'}       
        xlswrite('winding_data_B',excel_data_ss(:,:,1),sheet{1})
        case {'4'}
        xlswrite('winding_data_B',excel_data_ss(:,:,2),sheet{1})
        case {'5'}
        xlswrite('winding_data_B',excel_data_bt(:,:,3),sheet{1})
        case {'6'}
        xlswrite('winding_data_B',excel_data_bt(:,:,4),sheet{1})
        case {'7'}       
        xlswrite('winding_data_B',excel_data_ss(:,:,3),sheet{1})
        case {'8'}
        xlswrite('winding_data_B',excel_data_ss(:,:,4),sheet{1})
    end
end

% Display algorithm run time.
msgbox(strcat(num2str(toc/60),' minutes'),'Duration')      

