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

const char *sofname = "adda";
const char *syoumei = "Amiga/MacOS 9 to DOS, DOS to Amiga/MacOS 9";

void amiga_to_dos(FILE *in, FILE *out) {
  int c;

  while ((c = fgetc(in)) != EOF) {
    if (c != '\r') {
      fputc(c, out);
    }
    if ((c = fgetc(in)) != '\n') {
      fputc('\r', out);
      fputc('\n', out);
      ungetc(c, in);
    } else {
      fputc('\r', out);
      fputc('\n', out);
    }
  }
}

void dos_to_amiga(FILE *in, FILE *out) {
  int c;
  int last_char = '\0';

  while ((c = fgetc(in)) != EOF) {
    if (last_char == '\r' && c == '\n') continue;
    if (last_char != '\r' && c == '\n') fputc('\r', out);
    else fputc(c, out);
    last_char = c;
  }
}

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; // DOS
  return 0; // Amiga
}

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) { // AMIGA
    amiga_to_dos(in, tmp);
  } else { // DOS
    dos_to_amiga(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;
}