Cleaned the mess and added some tests