#include <stdio.h>
#include <memory.h>
#include "md5.h"

static char *file2md5(FILE *fp) {
	static char *s = NULL;
	MD5_CTX mdContext;
	int bytes, i;
	unsigned char data[BUFSIZ];

	/* Initialize file and md5 buffer */
	if ((s = (char *) malloc(32 + 1)) == NULL)
		exit(1);

	/* Compute the MD5 value */
	MD5Init(&mdContext);
	while ((bytes = fread(data, 1, BUFSIZ, fp)) > 0) {
		MD5Update(&mdContext, data, bytes);
	}
	MD5Final(&mdContext);

	/* Write the MD5 as a hexadecimal number */
	for (i = 0; i < 16; i++)
		sprintf(&s[i * 2], "%02x", mdContext.digest[i]);
	s[32] = '\0';
	return (s);
}

int main(int argc, char *argv[])
{
	char *s;
	if(argc > 1) {
		int i;
		for(i = 1; i < argc; i++) {
			FILE *fp;
			if ((fp = fopen(argv[i], "rb")) == NULL) {
				exit(1);
			}
			s=file2md5(fp);
			printf("%s: %s\n",argv[i], s);
			free(s);
			fclose(fp);
		}
	} else {
		s=file2md5(stdin);
		printf("%s\n", s);
		free(s);
	}
	exit(0);
}
