Script Search replace - complicated

I have a text file for which i need a script which does some fancy search and replace.
Basically i want to loop through each line, if i find an occurance of certain string format then i want to carry on search on replace another line, once i replaced this line i will contine to search for the previous string format once i find it i will again replace the next line with a specific format.
Eg

CODE A_123
TEXT
TEXT
VAL 1,2,3
TEXT
CODE A_321
TEXT
TEXT
VAL 1,2,3XT
In this example i want to say find CODE A*, if i find this look for VAL* and replace with X. Continue doing this for the whole file

Please give an example of desired output

CODE A_123
TEXT
TEXT
VAL 1,2,3
TEXT
CODE A_321
TEXT
TEXT
VAL 1,2,3
would become:

CODE A_123
TEXT
TEXT
VAL 1,5,2
TEXT
CODE A_321
TEXT
TEXT
VAL 5,6,7

Basically i only replace the VAL values if i have previously encountered a CODE A_*

bash

while read -r line
do
    case "$line" in 
        "CODE A"*)  flag=1;;
    esac
    if [ "$flag" -eq 1 ];then
        case "$line" in
            VAL* ) echo "VAL 5,6,7";flag=0;continue;;
            * ) echo $line;;
        esac    
    fi
    [ "$flag" -eq 0 ] && echo $line
done <"file"

output

$ more file
CODE A_123                        
TEXT
TEXT
VAL 1,2,3
TEXT
CODE A_321
TEXT
TEXT
VAL 1,2,3
TEXT
TEXT
VAL 1,2,3
TEXT
END
CODE A_321
TEXT
TEXT
VAL 1,2,3

$ ./shell.sh
CODE A_123
TEXT
TEXT
VAL 5,6,7
TEXT
CODE A_321
TEXT
TEXT
VAL 5,6,7
TEXT
TEXT
VAL 1,2,3
TEXT
END
CODE A_321
TEXT
TEXT
VAL 5,6,7

Thanks that works perfectly. Instead of echoing how can i write all the contents to a file.

Use output redirection.

If the input becomes large that may become slow. If so, post again here and we can talk about using sed, awk, or perl to accomplish this instead. (All three can do it and in less lines of code in most cases.)

perl -pe '$ON = 1 if /CODE A.+/; $ON = 0 if ( $ON && s/VAL 1,2,3/VAL 4,5,6/ )' datafile > replaced

There is the less line of Perl

while(<DATA>){
	$flag=1 if /^CODE.*/;
	if(/^VAL.*/){
	  $flag=0;
	  $_="X\n";
	}
	print;
}
__DATA__
CODE A_123
TEXT
TEXT
VAL 1,2,3
TEXT
CODE A_321
TEXT
TEXT
VAL 1,2,3XT