#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"

const char *sofname = "uaau";
const char *syoumei =
  "Unix/BeOS/Plan9 to Amiga/MacOS 9, Amiga/MacOS 9 to Unix/BeOS/Plan9";

void unix_to_amiga(FILE *in, FILE *out) {
  int c;
  while ((c = fgetc(in)) != EOF) {
    if (c == '\n') fputc('\r', out);
    else fputc(c, out);
  }
}

void amiga_to_unix(FILE *in, FILE *out) {
  int c;
  while ((c = fgetc(in)) != EOF) {
    if (c == '\r') fputc('\n', out);
    else fputc(c, out);
  }
}

int detect_line_ending(FILE *in) {
  int c;
  int islf = 0;
  int iscr = 0;
  while ((c = fgetc(in)) != EOF) {
    if (c == '\r') iscr = 1;
    if (c == '\n') islf = 1;
  }
  if (iscr && !islf) return 1; // Amiga
  return 0; // Unix
}

void usage() {
  fprintf(stderr, "%s-%s\n%s\n", sofname, version, syoumei);
  fprintf(stderr, "usage: %s <ファイル.txt>\n", sofname);
}

int main(int argc, char *argv[]) {
  if (argc != 2) {
    usage();
    return 1;
  }

  FILE *in = fopen(argv[1], "r");
  if (in == NULL) {
    perror("fopen input");
    usage();
    return 1;
  }

  FILE *tmp = fopen("tmp.txt", "w");
  if (tmp == NULL) {
    perror("fopen tmp");
    fclose(in);
    usage();
    return 1;
  }

  int line_ending_style = detect_line_ending(in);
  rewind(in);

  if (line_ending_style == 0) { // UNIX
    unix_to_amiga(in, tmp);
  } else { // AMIGA
    amiga_to_unix(in, tmp);
  }

  fclose(in);
  fclose(tmp);

  if (remove(argv[1]) != 0) {
    perror("元のファイルの削除");
    usage();
    return 1;
  }
  
  if (rename("tmp.txt", argv[1]) != 0) {
    perror("tmpファイル名の変更");
    usage();
    return 1;
  }

  return 0;
}