% script filename: locate_pwinsp_v4b.m 
% (previously: sort_power_inspect1_v4.m)
% This script establishes clamp label sequence and locates the data sets.

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

Initial creation: 12/17/07
..........................................................................
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 1: locate_pwinsp_v4b.m 
This code establishes the clamp label sequence while locating the groups/blocks 
of data. This information is used in Algorithm part 2:compile_pwinsp_v6b.m 
which reads the Roamer Arm PowerInspection files and sorts, merges, averages 
and then writes the results into one excel file.  
The new Excel file is formatted for use with current_center_deviations_v2.m.
...........................................................................
Script notes: locate_pwinsp_v4b.m 
This script is used for B coils.
OUTPUTS
(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.
(3) errors is (3, 16).
Overall the errors variable is used to evaluate the data processing and for 
troubleshooting Algorithm results issues.
Row 1 reflects missing labels, (no lables should be missed).
Row 2 reflects the number of labels found vs data sets found, (should be equal).
Row 3 reflects spacing between data sets found (spacing should be consistent).
%}

clc
clear

% Capture Current Matlab Directory.
matlab_file_dir =pwd;

% Open matlab .mat file to obtain string variables for Excel tab labels.
messages1 = struct2cell(open('Icenter_messages1.mat'));

%
% **********************************************************************
% If s1 string file exists use this code.
% Load the string s1 (filenames) .mat file.
% NOTE: it will be necessary EDIT the xlsread commands, lines 54 & 108, similar to: 
% s2,'\'s1{1}{mcc} were the '\' and {1} are the edits.
[fname fpath]=uigetfile('*.mat','Select string s1 .mat (filenames) file.');
s1 = struct2cell(open(fname));
s2 = uigetdir(pwd,'Select Directory Location of Excel Files.');
cd(s2);
%{
%**********************************************************************
% If s1 string file is NOT created, use this code.
% Select excel files.
for mcc=1:16
    [s1{mcc} s2]=uigetfile('*.*',messages1{1}{mcc,1});
    % set directory for easy access to excel files.
    if mcc == 1; cd(s2); end
end    
%}
% **********************************************************************
% Start algorithm timer at this line (current time).
tic;
fn=16; % Set number of loops (files to read/process). This is for code development.

% ***********************************************************************
% Determine the clamp label sequences.
% ***********************************************************************

clp_sequ=zeros(100,32); % Initializing.
er1=ones(100,16);       % Initializing.
er1((97:100),:)=0;      % Initializing.
redunlabel=zeros(100,16);   % Initializing.

for mcc=1:fn
     %Read excel data col B.
    [dm1 colB]= xlsread(strcat(s2,'\',s1{1}{mcc}),'B1:B4000');

    temp_loc=zeros(100,2);  % Initializing.
    endind=(mcc*2);         % ending index variable for results storage.
    stind=endind-1;         % starting index variable for results storage.
    pt=0;
    % Create Strings for clamp/block labels and search through excel files.
    for Bcc=1:96
        m1=0;m2=0;m3=0;
        label1 = strcat('N',num2str(Bcc),'L0'); % string for block #.
        label2 =['Inspection Group ',num2str(Bcc)]; % alternate label.
        label3 =['Inspection Group ',num2str(Bcc),'A']; % alternate label.
        m1 = strmatch(label1,colB,'exact'); % search and compare colB data.
        m2 = strmatch(label2,colB,'exact'); % search and compare colB data.
        m3 = strmatch(label3,colB,'exact'); % search and compare colB data.
        if m1>0             % Evaluate for label match 1.
            pt=pt+1;
            temp_loc(pt,1)=Bcc;
            temp_loc(pt,2)=m1;
        elseif m2>0         % Evaluate for label match 2.
            pt=pt+1;
            temp_loc(pt,1)=Bcc;
            temp_loc(pt,2)=m2;
        end
        if m3>0             % Evaluate for label match 3.
            pt=pt+1;
            temp_loc(pt,1)=Bcc+0.3;
            temp_loc(pt,2)=m3;
        end
        if m2>0 & m3>0
            redunlabel(Bcc,mcc)=1;
        end
 % ----------------------------------------------------------------------
 % Pre-Process for Error Check (1): Check for clamp labels not found.
  % ----------------------------------------------------------------------
        if isempty(m1) & isempty(m2) & isempty(m3)
                er1(Bcc,mcc)=0;
        end
 % ----------------------------------------------------------------------
    end
    temp1 = sortrows(temp_loc,2);       % Sort clamp labels via data indices.
    clp_sequ(:,(stind:endind))=temp1;
end

% *******************************************************************
% Search and sort col2 data for starting locations of data sets.
% *******************************************************************

set_loc=zeros(100,16);          % Initializing.
allcol2=zeros(4000,16);            % Initializing.

% Conditionals to locate starting row of base/top data sets.
cond1=[1;1;1;1;1;1;NaN([6,1])];
cond2=[1;1;1;NaN;1;1;NaN;1;1;NaN([5,1])];

for mcc=1:fn
[all dm2]= xlsread(strcat(s2,'\',s1{1}{mcc}),'A1:N4000');
     allcol2((1:size(all,1)),mcc)=all(:,2);
end

for mcc=1:fn
     col2=allcol2(:,mcc);
     % Convert col2 data into format for conditionals. This data is used
     % with the conditionals to locate the start of the data sets.
     for Ccc=1:length(col2)
         if isfinite(col2(Ccc))
             col2(Ccc)=1;
         end
     end
        cflg=1;
        locn=1;
        for Ccc=1:(length(col2)-14)
            switch num2str(cflg)
% Find condition #1 which locates the 1st data set after the conical seat information.
                case '1'
                    if isequalwithequalnans(col2((Ccc:Ccc+11),1),cond1)
                        cflg=2;
                        set_loc(locn,mcc)=Ccc+12;
                        locn=2;
                    end
% Find condition #2, starting location of all data sets except the 1st.
                case '2'
                    if isequalwithequalnans(col2((Ccc:Ccc+13),1),cond2)
                        set_loc(locn,mcc)=Ccc+14;
                        locn=locn+1;
                    end
            end
        end
end
% ************************************************************************
% Check & Process Errors.
% ************************************************************************
errors=zeros(3,16);   % Initializing.

% Check (1): Total missed labels per each of the 16 files.
for ec1=1:2:fn
    etp1 = er1(:,ec1)+er1(:,ec1+1);
    etp2 = length(find(etp1==2));
    ner1a = nnz(er1(:,ec1));
    ner1b = nnz(er1(:,ec1+1));
    errors(1,ec1)  = 96-(ner1a+ner1b-etp2)-sum(redunlabel(:,ec1));
    errors(1,ec1+1)= 96-(ner1a+ner1b-etp2)-sum(redunlabel(:,ec1+1));
end

er2=zeros(2,16);      % Initializing.
% Check (2): Compare # of located clamp labels vs data sets found.
for ec1=1:fn
    endcol=(ec1*2);
    stcol=endcol-1;
    er2(1,ec1)=nnz(set_loc(:,ec1));
    er2(2,ec1)=nnz(clp_sequ(:,stcol));
    errors(2,ec1)=abs(er2(1,ec1)-er2(2,ec1));
end

% Check (3): Check for abnormal spacing between data sets.
spchk=zeros(length(set_loc),16);    % Initializing.   
er3=spchk;                          % Initializing.
for ec1=1:fn
    last=find((set_loc(:,ec1)>0),1,'last');
    spchk((1:last-2),ec1)=set_loc((2:last-1),ec1)-set_loc((1:last-2),ec1);
    dlen = nnz(spchk(:,ec1));
    er3(1,ec1)=round(sum(spchk(:,ec1))/dlen);   % Calculate average spacing.
    [er3(2,ec1) er3(3,ec1)]=max(spchk(:,ec1));  % Find maximums.
    if er3(2,ec1)>(er3(1,ec1)+3)
        errors(3,ec1)=er3(3,ec1)+1;
    end
end
% ************************************************************************

% Reset Directory to Initial Matlab Directory
cd(matlab_file_dir);

msgbox(strcat(num2str(toc/60),' minutes'),'Duration')


    



    


