Adapted from QSTK tutorial 8