clear all
close all
clc

fraga=[1:16  33:42]; % the atom nmbers of the pyrene fragment
fragb=[17:32 43];% the atom nmbers of the dimethylaniline fragment


for i=0:39
    
    folder=sprintf("C:/ADF_DATA/scan2/angle(%d)",i);
    
    filename1 = sprintf("C:/ADF_DATA/scan2/angle(%d)/coordfrag.txt",i);
    fid=fopen(filename1,'r');
    
    j=1;
    l=1;
    while true
        line=fgetl(fid);
        
        if line==-1
            break;
        end
        
        if (j>7 && j<52)
            str(l)= extractBefore(string(line),"region");
            l=l+1;
        end
        
        
        j=j+1;
    end
    
    fclose all;
    facoord=str(fraga);
    fbcoord=str(fragb);
    
    %%
    filename2 = sprintf("PyrDMA-Fragment-a.txt");
    fid=fopen(filename2,'r');
    
    j=1;
    l=1;
    
    while true
        line=fgetl(fid);
        if line==-1
            break;
        end
        
        if (j>8 && j<8+1+length(fraga))
            strna{j}= facoord(l);
            l=l+1;
        else
            strna{j}=string(line);
        end
        
        j=j+1;
    end
    fclose all;
    
    
    %%
    
    filename2 = sprintf("PyrDMA-Fragment-b.txt");
    fid=fopen(filename2,'r');
    
    j=1;
    l=1;
    while true
        line=fgetl(fid);
        if line==-1
            break;
        end
        
        if (j>8 && j<8+1+length(fragb))
            strnb{j}= fbcoord(l);
            l=l+1;
        else
            strnb{j}=string(line);
        end
        
        j=j+1;
    end
    fclose all;
    
    
    %%
    
    filename3=sprintf("C:/ADF_DATA/scan2/angle(%d)/PyrDMA-Fragment-a.txt",i);
    fid=fopen(filename3,'w');
    
    for m = 1:numel(strna)
        fprintf(fid,'%s\n', strna{m});
    end
    
    fclose all;
    
    
    filename3=sprintf("C:/ADF_DATA/scan2/angle(%d)/PyrDMA-Fragment-b.txt",i);
    fid=fopen(filename3,'w');
    
    for m = 1:numel(strnb)
        fprintf(fid,'%s\n', strnb{m});
    end
    
    fclose all;
    
    
    %% 
    
    facoord=facoord+"f=a";
    fbcoord=fbcoord+"f=b";
    coordmain=[facoord fbcoord];
    
    filename4 = sprintf("PyrDMA-vab.txt");
    fid=fopen(filename4,'r');
    
    j=1;
    l=1;
    while true
        line=fgetl(fid);
        if line==-1
            break;
        end
        
        if (j>8 && j<8+1+length(fragb)+length(fraga))
            strnmain{j}= coordmain(l);
            l=l+1;
        else
            strnmain{j}=string(line);
        end
        
        j=j+1;
    end
    fclose all;
    
    
    %%
    
    filename4=sprintf("C:/ADF_DATA/scan2/angle(%d)/PyrDMA-vab.txt",i);
    fid=fopen(filename4,'w');
    
    for m = 1:numel(strnmain)
        fprintf(fid,'%s\n',strnmain{m});
    end
    
    fclose all;
    
    
    
end