Fix errors detected during live testing. Make the core logic code more compact and readable.