Code cleaned-up.
Split huge functions into smaller ones.
Added errors/exceptions.