changes to optimization

I tried to make the code cleaner and improve the result with better functions to filter the output