Fixed JSON output

Also tidied some things and added more comments