re-organised the code so that each operation is handled separately, i.e., not in a big for-loop as before