Merged with Alexander's code And fixed bugs