Add comments and improve some efficiency

The code now contains comments, please inform me if anything is not
clear.

Efficiency is improved for earlier error detection.
If the request fails, the error response is generated directly and not
after doing some more assignments and defines and stuff.