fix a tiny bug where imageName would've been assigned to the last file in dir even if it was not on the extension list.

also rewrite a bit (and fix braces)