A working version with major bugs fixed.