Initial working version. Tested only with basic cases