possibly too complex solution
simplified version works locally