refactored a bit and fixed issue with populating output array