Improved code from thesis repository