#include <sys/cdefs.h>
__COPYRIGHT("@(#) Copyright (c) 1989, 1993\
The Regents of the University of California. All rights reserved.");
__RCSID("$NetBSD: caesar.c,v 1.25 2025/09/18 22:25:04 rillig Exp $");
#include <err.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NCHARS (1 << CHAR_BIT)
#define LETTERS (26)
static const unsigned char upper[LETTERS] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const unsigned char lower[LETTERS] = "abcdefghijklmnopqrstuvwxyz";
static double stdf[LETTERS] = {
7.97, 1.35, 3.61, 4.78, 12.37, 2.01, 1.46, 4.49, 6.39, 0.04,
0.42, 3.81, 2.69, 5.92, 6.96, 2.91, 0.08, 6.63, 8.77, 9.68,
2.62, 0.81, 1.88, 0.23, 2.07, 0.06
};
static unsigned char rottbl[NCHARS];
static void
init_rottbl(unsigned int rot)
{
rot %= LETTERS;
for (size_t i = 0; i < NCHARS; i++)
rottbl[i] = (unsigned char)i;
for (size_t i = 0; i < LETTERS; i++)
rottbl[upper[i]] = upper[(i + rot) % LETTERS];
for (size_t i = 0; i < LETTERS; i++)
rottbl[lower[i]] = lower[(i + rot) % LETTERS];
}
static void
print_file(void)
{
int ch;
while ((ch = getchar()) != EOF)
if (putchar(rottbl[ch]) == EOF)
err(EXIT_FAILURE, "<stdout>");
}
static void
print_array(const unsigned char *a, size_t len)
{
for (size_t i = 0; i < len; i++)
if (putchar(rottbl[a[i]]) == EOF)
err(EXIT_FAILURE, "<stdout>");
}
static unsigned int
get_rotation(const char *arg)
{
long rot;
char *endp;
errno = 0;
rot = strtol(arg, &endp, 10);
if (errno == 0 && (arg[0] == '\0' || *endp != '\0'))
errno = EINVAL;
if (errno == 0 && (rot < 0 || rot > INT_MAX))
errno = ERANGE;
if (errno)
err(EXIT_FAILURE, "Bad rotation value `%s'", arg);
return (unsigned int)rot;
}
static void
guess_and_rotate(void)
{
unsigned char inbuf[2048];
unsigned int obs[NCHARS];
size_t i, nread;
double dot, winnerdot;
unsigned int try, winner;
int ch;
for (i = 0; i < LETTERS; i++)
stdf[i] = log(stdf[i]) + log(LETTERS / 100.0);
(void)memset(obs, 0, sizeof(obs));
for (nread = 0; nread < sizeof(inbuf); nread++) {
if ((ch = getchar()) == EOF)
break;
inbuf[nread] = (unsigned char)ch;
}
for (i = 0; i < nread; i++)
obs[inbuf[i]]++;
winner = 0;
winnerdot = 0.0;
for (try = 0; try < LETTERS; try++) {
dot = 0.0;
for (i = 0; i < LETTERS; i++)
dot += (obs[upper[i]] + obs[lower[i]])
* stdf[(i + try) % LETTERS];
if (try == 0 || dot > winnerdot) {
winner = try;
winnerdot = dot;
}
}
init_rottbl(winner);
print_array(inbuf, nread);
print_file();
}
int
main(int argc, char **argv)
{
if (argc == 1)
guess_and_rotate();
else if (argc == 2) {
init_rottbl(get_rotation(argv[1]));
print_file();
} else {
(void)fprintf(stderr, "usage: caesar [rotation]\n");
exit(EXIT_FAILURE);
}
if (ferror(stdin) != 0)
errx(EXIT_FAILURE, "<stdin>: read error");
(void)fflush(stdout);
if (ferror(stdout) != 0)
errx(EXIT_FAILURE, "<stdout>: write error");
return 0;
}