function [Index,A0]=CheckSignsA0_2(A0,IRF_cand,SIGNS,per_SIGNS,Nshocks,pos,N)
Index=1; % this switches to 0 if you don't have a rotation
ll=1; % index of columns/shocks

while ll<=Nshocks
    check_periods    = per_SIGNS(:,ll);
    max_check_periods= max(check_periods);
    
    % construct a matrix of signs and IRFs consistent with the constraints on
    % the desired horizons. This is done repeating the IRF for cases where the
    % horizon is fixed
    IRF_check_temp = NaN(N,max_check_periods+1);
    
    for nn=1:N
        % now extend for the remaining periods
        %         mat_check(nn,1:per_SIGNS(nn)) = 1:per_SIGNS(nn);
        IRF_check_temp(nn,1:per_SIGNS(nn,ll)) = IRF_cand(nn,ll,1:per_SIGNS(nn,ll));
        % now extend for the remaining periods
        %         mat_check(nn,per_SIGNS(nn)+1:end) = mat_check(nn,per_SIGNS(nn));
        IRF_check_temp(nn,per_SIGNS(nn,ll)+1:end) = IRF_check_temp(nn,per_SIGNS(nn,ll));
    end
    % trim last column
    IRF_check       = IRF_check_temp(:,1:end-1);
    
    right_sign      = sign(SIGNS(pos(:,ll)==1,ll));
    right_sign_mat  = repmat(right_sign,1,max_check_periods);   
    
    check_shock_1 = sign(IRF_check(pos(:,ll)==1,:))==right_sign_mat;
    check_shock_2 = sign(IRF_check(pos(:,ll)==1,:))==-right_sign_mat;
    
    if sum(all(check_shock_1))==max_check_periods;
        ll=ll+1; % ok, go to the next column
    elseif sum(all(check_shock_2))==max_check_periods;
        A0(:,ll)=-A0(:,ll); % ok but switch sign to column ll        
        ll=ll+1;% ok, go to the next column but change column sign
    else
        Index=0; % you don't have a rotation, stop checking and go back to the main program for a different draw/permutation
        ll=Nshocks+1; % this breaks out of the loop
    end
end
