#!/bin/bash

shopt -s extglob # ensure extended globbing (pattern matching) is enabled

# for each defect, in the directory where your top-level defect folders are
for defect_name in *{_,_-}[0-9]/; # matches each subdirectory with a name ending in "_" + a number (charge state)
    do cd "${defect_name}" || exit;
    filename=${defect_name%?}.txt
    if [[ -f ${filename} ]];
        then
        echo "Moving old ${filename} to ${defect_name%?}_$(date +%H_%M_%Son%d_%m_%y).txt to avoid overwriting"
        mv "${filename}" "${defect_name%?}_$(date +%H_%M_%Son%d_%m_%y).txt"
        fi

    for i in ?(*Bond_Distortion*|*Unperturbed|*Rattled)/; # for each distortion tested
        do
        if grep -q "required accuracy" "${i}"/OUTCAR; # check calculation fully relaxed and finished
            then echo "${i%?}" >> "${filename}"; # add BDM distortion to txt file, "%?" cuts slash at end of string
            grep -a sigma "${i}"/OUTCAR | tail -1 | awk '{print $NF}' >> "${filename}"; #and its energy
            else echo "${defect_name%?} ${i%?} not fully relaxed"
        fi;
        done;
    cd ..;
    done
