Fixes and improvements.

Fix encoding issue when run as CGI.
Reorganize some code.
Improve error handling (close sqlite db in case of sql errors).