Ugly but functional implementation,