finally implemented a fast solution (~5 seconds) using ideas suggested by Vadim Pidonenko