Other that the issue that contents are not written\read, the algorithm is OK (number_of_instances is started at NIL then get the actauall number of instances and become as a counter to zero. When reach 0 the if else edvances..)
Problem is the it is a bit not human readable..