Shell Script required for the below script

please solve my problem

i have a sample input file as
A
A
A
A
B
B
B
B
B
C
C
C
C
C

i want the output such that if the count of A or B or C is greater than 3
A
A
A
B
B
B
C
C
C

if the count of A is less than 3 i.e if the input file is like
A
A
B
B
B
B
C
C
C

then A should append B and the output file should be
A
A
B
B
B
B
C
C
C

the above output should repeat for both B and C too if the count of B and C is also less than 3

thanks in advance
sai

What have you tried so far? Where are you stuck?