function eegquerymain
%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk. All Rights Reserved.                     
%                                                                                          
%   THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE        
%   NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO,    
%   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE    
%   OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
%   TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT,       
%   INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE      
%   OR DOCUMENTATION.                                                                      

global ifilemat appfilemat logfilemat intervallstatus...
    intervall lookfor speciallogfilestatus handles...
    baselinestatus baselineintervall baselinetotintervallstatus...
    paramat paravec eegdata gpdata anzahldifftrials anzahltottrials...
    stimulinames appmode imode logmode anzahlvp repeatstatus...
    reihenfolgematcell channelweightmat channelweightingstatus...
    subtractpotentialstatus subtractpotential

%variablen 
intervallradio = findobj('tag','intervallradio');
starttimeedit = findobj('tag','starttimeedit');
endtimeedit = findobj('tag','endtimeedit');
lookforpopup = findobj('tag','lookforpopup');
normalizationpopup = findobj('tag','normalizationpopup');
baselinestarttimeedit=handles.baselinestarttimeedit;
baselineendtimeedit=handles.baselineendtimeedit;
baselinestatus = 1;
baselinetotintervallstatus = 1;
samplingrate = 0.25;
pointrange = 1/samplingrate;
subtractpotentialstatus=0;
    
if get(intervallradio,'Value')==1 & ~isempty(get(starttimeedit,'String')) & ~isempty(get(endtimeedit,'String'))
    %sampling rate = 250/1000 = 0.25
    starttime=round(str2num(get(starttimeedit,'String'))/pointrange);
    endtime=round(str2num(get(endtimeedit,'String'))/pointrange);
    intervall = [starttime endtime];
    intervallstatus = 1;
elseif get(intervallradio,'Value')==1
    uiwait(errordlg('Bitte definieren Sie starttime und endtime des Intervalls!','Fehler:'));
    intervallstatus = 0;
    intervall = [];
    return
end


  
%mode
if isempty(appmode) | isempty(logmode) | isempty(imode); modefehler; return;end
if appmode==12 & imode ==12 & logmode==12; mode = 12;elseif appmode==12 & imode ==12 & logmode==2
    speciallogfilestatus=1; mode = 12; elseif  appmode==2 & imode ==2 & logmode==2;mode = 2;end
if mode==0; modefehler;return
    
    
%lookfor
lookfor = get(lookforpopup,'Value');
if isempty(lookfor); lookfor=1; end

% batchfile mode   
elseif mode==12
    
    if ~(size(appfilemat,1)==size(ifilemat,1))
        errorcell={'Fileanzahl in den Batchfiles stimmt nicht überein!';['app-batch: ',num2str(length(appfilemat)),' files <> ','i-batch: ',num2str(length(ifilemat)),' files.']}; 
        uiwait(errordlg(errorcell,'Fehler:'));
        return
    end
    
    %Variablen
    anzahlvp = size(appfilemat,2);
    anzahltottrials=zeros(1,anzahlvp);
    anzahldifftrials=zeros(1,anzahlvp);
    reihenfolgematcell=cell(1,anzahlvp);
    stimulinames=cell(1,anzahlvp);
    trialpercondveccell=cell(1,anzahlvp);
    repeatstatus=zeros(1,anzahlvp);
    appmatcell=cell(1,anzahlvp);
    testdata=ReadAppData(appfilemat{1},1);
    NChan=size(testdata,1);
    NPoints=size(testdata,2);
    normalization=get(handles.normalizationpopup,'Value');
    if baselinestatus==1 & baselinetotintervallstatus==1
        baselineintervall(1)=1; 
        baselineintervall(2)=NPoints;
    elseif baselinestatus ==1  & (isempty(get(baselinestarttimeedit,'String')) | ~isempty(get(baselineendtimeedit,'String')))
        uiwait(errordlg('Bitte machen Sie Angaben zu Beginn und Ende des Baselineintervalls!','Fehler:'));
        return
    end
    if intervallstatus == 0
        starttime = 1;
        endtime  = NPoints;
        intervall = [starttime endtime];
    end
    
    %sampling rate = 250/1000 = 0.25
     
    %log-files einlesen
    for vpzaehler=1:anzahlvp
        if speciallogfilestatus==1
            [stimulinames{vpzaehler},reihenfolgematcell{vpzaehler},anzahltottrials(vpzaehler),anzahldifftrials(vpzaehler),repeatstatus(vpzaehler)]=readlogfile(logfilemat{1}); 
        else
            [stimulinames{vpzaehler},reihenfolgematcell{vpzaehler},anzahltottrials(vpzaehler),anzahldifftrials(vpzaehler),repeatstatus(vpzaehler)]=readlogfile(logfilemat{vpzaehler}); 
        end
    end
   
    %i-files einlesen
    for vpzaehler=1:anzahlvp
        trialpercondveccell{vpzaehler}=readascii(ifilemat{vpzaehler});
    end
    
    %Trialanzahl 
    trialanzahl = max(anzahltottrials);
    answer = questdlg({'Überprüfen Sie bitte die Trialanzahl:';'';['            ',num2str(max(anzahltottrials))];''},'Trialanzahl:',...
                        'korrekt','ändern','korrekt');
    if strcmp(answer,'ändern')
        trialanzahlcell = inputdlg('Bitte legen Sie die erzwungen Anzahl von Trials fest:','Erzwungene Trialanzahl:');
        if isstring(trialanzahl{1})
            trialanzahl=str2num(trialanzahlcell{1});
        else
            trialanzahl=trialanzahlcell{1};
        end
    end
    
    pause(0.3);
    
    
     
    
    %------------------------------------------------
    %Paramat berechen
    %------------------------------------------------
    
    paramat=zeros(trialanzahl,anzahlvp);
    eegdata=zeros(NChan,NPoints); 
    if subtractpotentialstatus == 1 & baselinestatus == 1
        if baselinetotintervallstatus == 1
            subtractpotential=CalcBaseline(subtractpotential,1,NPoints,1);
        else
            subtractpotential=CalcBaseline(subtractpotential,baselineintervall(1),baselineintervall(2),1);
        end
    end   
    
    %Global Power
    %------------------------------------------------
    
    if lookfor == 1  
        recalculate = 'yes';
        if ~isempty(gpdata)
            recalculate = questdlg('Recalculate Global-Power-Mat?','Repeated Calculation:','yes','no','yes');
        end
        
        if strcmp(recalculate,'yes') | isempty(gpdata)
          fprintf('Calculating global power for all trials and VPs...\n\n');
          gpdata=zeros(NPoints,trialanzahl,anzahlvp);   
            for vpzaehler=1:anzahlvp
                for j=1:trialanzahl
                    if ~isempty(find(trialpercondveccell{vpzaehler}==j))
                        app_pos=find(trialpercondveccell{vpzaehler}==j);
                        %app-file einlesen
                        if baselinestatus == 1
                            if baselinetotintervallstatus == 1
                                eegdata=CalcBaseline(ReadAppData(appfilemat{vpzaehler},app_pos),1,NPoints,1);
                            else
                                eegdata=CalcBaseline(ReadAppData(appfilemat{vpzaehler},app_pos),baselineintervall(1),baselineintervall(2),1);
                            end
                        else
                           eegdata(:,:)=ReadAppData(appfilemat{vpzaehler},app_pos);
                        end
                        
                        if subtractpotentialstatus == 1
                            eegdata=eegdata-subtractpotential;
                        end
                        
                        if channelweightingstatus==1
                            if subtractpotentialstatus==1
                               gpdata(:,j,vpzaehler)=CalcGlobalPowerpp(eegdata,channelweightmat,0,0,1,0.001); 
                            else
                               gpdata(:,j,vpzaehler)=CalcGlobalPowerpp(eegdata,channelweightmat,0,0,1,0.001);
                            end
                                %CalcGlobalPower(Data,ChanWeightVec,ENames,ch_DispChanWeight,ch_TakeWeightVec,MinWeightVal);
                        else
                            gpdata(:,j,vpzaehler)=CalcGlobalPowerpp(eegdata);
                        end
                        
                    end
                    if mod(j,10)==0
                        fprintf('.');
                    end
                end
                fprintf('\n');
            end
        end
        fprintf('\n\n');
        pause(0.3);
        fprintf('Calculating parameter for chosen time range...\n\n\n');
        
        for vpzaehler=1:anzahlvp
            calcmeangpstatus=0;
            for j=1:trialanzahl
                if ~isempty(find(trialpercondveccell{vpzaehler}==j))
                    switch normalization
                        %no normalization    
                        case 1
					        paramat(j,vpzaehler)=sum(gpdata(intervall(1):intervall(2),j,vpzaehler));
                        %current-trial-normalization    
                        case 2
                            paramat(j,vpzaehler)=sum(gpdata(intervall(1):intervall(2),j,vpzaehler))/sum(gpdata(:,j,vpzaehler));
                        %all-trial(mean)-normalization
                        case 3
                            if  calcmeangpstatus == 0
                                trialzaehler=0;
                                gpalltrials=zeros(1,NPoints);
                                meangp=zeros(1,NPoints);
                                for k=1:trialanzahl
                                    if ~isempty(find(trialpercondveccell{vpzaehler}==k))
                                        gpalltrials=gpalltrials+gpdata(:,k,vpzaehler)';
                                        trialzaehler=trialzaehler+1;
                                    end
                                end
                                meangp=gpalltrials./trialzaehler;
                                calcmeangpstatus = 1;
                            end
                            paramat(j,vpzaehler)=sum(gpdata(intervall(1):intervall(2),j,vpzaehler))/sum(meangp);         
                    end
                else
                    paramat(j,vpzaehler)=-1;
                end
                if mod(j,10)==0
                    fprintf('.');
                end
                
            end
            fprintf('\n');
        end
        
    %Scalp potential
    %------------------------------------------------
    
    elseif lookfor == 2  
    
        for vpzaehler=1:anzahlvp
            calcmeanspsstatus = 0;
            eegdata=zeros(NChan,NPoints); 
            eegdata_mean=zeros(NChan,NPoints); 
            for j=1:trialanzahl
                if ~isempty(find(trialpercondveccell{vpzaehler}==j))
                    
                    if baselinestatus == 1
                        if baselinetotintervallstatus == 1
                            eegdata=CalcBaseline(ReadAppData(appfilemat{vpzaehler},app_pos),1,NPoints,1);
                        else
                            eegdata=CalcBaseline(ReadAppData(appfilemat{vpzaehler},app_pos),baselineintervall(1),baselineintervall(2),1);
                        end
                    else
                       eegdata(:,:)=ReadAppData(appfilemat{vpzaehler},app_pos);
                    end
                    
                    switch normalization
                        %no normalization    
                        case 1                           
					        paramat(j,vpzaehler)=sum(mean(eegdata(:,intervall(1):intervall(2)),1));
                        %current-trial-normalization    
                        case 2
                            paramat(j,vpzaehler)=sum(mean(eegdata(:,intervall(1):intervall(2)),1));
                        %all-trial(mean)-normalization
                        case 3
                            if  calcmeanspsstatus == 0
                                trialzaehler=0;
                                spalltrials=zeros(1,NPoints);
                                meansp=zeros(1,NPoints);
                                for k=1:trialanzahl
                                    app_pos_mean=find(trialpercondveccell{vpzaehler}==k);
                                    if baselinestatus == 1
                                        if baselinetotintervallstatus == 1
                                            eegdata_mean=CalcBaseline(ReadAppData(appfilemat{vpzaehler},app_pos_mean),1,NPoints,1);
                                        else
                                            eegdata_mean=CalcBaseline(ReadAppData(appfilemat{vpzaehler},app_pos_mean),baselineintervall(1),baselineintervall(2),1);
                                        end
                                    else
                                       eegdata_mean(:,:)=ReadAppData(appfilemat{vpzaehler},app_pos_mean);
                                    end
                                    
                                    if ~isempty(find(trialpercondveccell{vpzaehler}==k))
                                        spalltrials=spalltrials+mean(eegdata_mean(:,:),1);
                                        trialzaehler=trialzaehler+1;
                                    end
                                end
                                meansp=spalltrials./trialzaehler;
                                calcmeanspstatus = 1;
                            end
                            paramat(j,vpzaehler)=sum(mean(eegdata(:,intervall(1):intervall(2)),1))/sum(meansp);         
                    end
                else
                    paramat(j,vpzaehler)=-1;
                end
            end
        end   
    
    %Source strength
    %------------------------------------------------
    
    elseif lookfor == 3  
    
       uiwait(errordlg('Nice try! --> No Script for source strengths!','Error:'));
       return
    end
    
    %Mitteln
    fprintf('\n\nAveraging trialparameters over subjects...\n\n');
    paravec=zeros(trialanzahl,1);
    weightvec=zeros(trialanzahl,1);
	for s=1:trialanzahl
        for t=1:anzahlvp
            if paramat(s,t)~=-1
                paravec(s)=paravec(s)+paramat(s,t);
                weightvec(s)=weightvec(s)+1;
            end
        end
        if weightvec(s)~=0
            paravec(s)=paravec(s)./weightvec(s);
        else 
            paravec(s)=-1;
        end
        if mod(s,5)==0
            fprintf('.');
        end
        if mod(s,100)==0
            fprintf('\n');
        end
	end
    ok
      
% single file mode   
elseif mode==2
  
end

return


    
            