Initial code. Needs debugging and testing.