Major refactor. Work in progress. Old version available in /backup/