#include "cgic.h"

/* Change this to point to a reasonable location on your system */
#define COMMENT_FILE "/CHANGE/THIS/PATH/comments.txt"

int cgiMain() {
	/* Large enough buffers for any reasonable real name
		and email address. */
	char name[256];
	char email[256];

	/* The comments themselves may be quite large, so we'll
		allocate space once we know how large they are. */
	char *comments;

	/* Space needed for the comments string. */
	int needed;

	/* Keep the results so we can complain if fields are missing. */
	int rName, rEmail, rComments;

	FILE *out;

	/* Output the usual MIME header. */
	cgiHeaderContentType("text/html");

	/* Start the HTML document. */
	fprintf(cgiOut,
		"<HTML>\n<HEAD>\n");

	/* cgiFormStringNoNewlines()
		will never overflow buffers or write a
		non-terminated string. Also, even if
		the user's browser is defective, it will
		not return any carriage returns or line feeds. */

	rName = cgiFormStringNoNewlines("name", name, sizeof(name));
	rEmail = cgiFormStringNoNewlines("email", email, sizeof(email));
	
	/* cgiFormStringSpaceNeeded the number of bytes of
		space guaranteed to be adequate for the
		string in question, including the terminating null. */
	
	rComments = cgiFormStringSpaceNeeded("comments", &needed);	

	/* Now check for missing fields. */
	if ((rName == cgiFormNotFound) || (rEmail == cgiFormNotFound) ||
		(rComments == cgiFormNotFound)) 
	{
		/* If any field is missing, complain! */
		fprintf(cgiOut,
			"<title>Please fill out all the fields</title>\n");
		fprintf(cgiOut,
			"</head>\n");
		fprintf(cgiOut,
			"<h1>Please fill out all the fields</h1>\n");
		fprintf(cgiOut,
			"Please fill out the name, email address, AND\n");
		fprintf(cgiOut,
			"comment fields. Back up to the previous page\n");
		fprintf(cgiOut,
			"to try again.\n");
		fprintf(cgiOut, "</body></html>\n");
		return 0;
	}

	/* So far, so good. Allocate space for the comments. Since
		we are dynamically allocating the space, we will
		need to free the space later. */
	comments = (char *) malloc(needed);	

	/* In this case, we do want to allow new lines,
		so we call cgiFormString. cgiFormString
		will guarantee that line breaks are always
		represented simply by line feeds, even if
		the user's browser does something creative. */

	cgiFormString("comments", comments, needed);		
	
	/* OK, write the comments to disk. */

        out = fopen(COMMENT_FILE, "a");
        fprintf(out, "From: %s <%s>\n", name, email);
        fprintf(out, "%s\n", comments);

	/* Say thanks. */
        fprintf(cgiOut, "<title>Thank you, %s</title>\n", name);
        fprintf(cgiOut, "</head>\n");
        fprintf(cgiOut, "<h1>Thank you, %s</h1>\n", name);
        fprintf(cgiOut, "Thank you for your comments.\n");
        fprintf(cgiOut, "</body></html>\n");

	/* Free the memory we used for the comments. */
	free(comments);
	
	/* We're done. */
	return 0;
}
