Borrowed some tricks from friend's 'tilde' project at https://github.com/banzera/tilde/