#include <stdbool.h>
#include <stdio.h>

int main (int argc, char* argv[])
{
  FILE* In;
  FILE* Out;
  bool PrevLineWasInstruction;
  unsigned int InstructionCounter;
  int Ch;

  if(argc != 3)
  {
    puts(
      "Comment extractor\n"
      "by Matej Horvat\n"
      "http://matejhorvat.si/en/vboy/insmouse/\n"
      "\n"
      "Extracts comments from a MNVCDIS commented disassembly listing.\n"
      "\n"
      "Usage: XC inputDisassemblyFile outputCommentFile"
    );
    return 0;
  }

  In = fopen(argv[1], "r");
  Out = fopen(argv[2], "w");
  if(!(In && Out))
  {
    fputs("Error opening one or both files\n", stderr);
    fclose(In);
    fclose(Out);
    return 1;
  }

  PrevLineWasInstruction = false;
  InstructionCounter = 0;
  for(;;)
  {
    Ch = fgetc(In);
    if(Ch == ';' || Ch == '\n')
    {
      if(PrevLineWasInstruction)
      {
        fprintf(Out, "%u\n", InstructionCounter);
        InstructionCounter = 0;
        PrevLineWasInstruction = false;
      }

      fputc(Ch, Out);
      if(Ch == ';')
      {
        for(;;)
        {
          Ch = fgetc(In);
          if(Ch == '\n' || Ch == EOF)
            break;
          fputc(Ch, Out);
        }
        fputc('\n', Out);
      }
    }
    else if(Ch == EOF)
      break;
    else
    {
      InstructionCounter++;

      for(;;)
      {
        Ch = fgetc(In);
        if(Ch == '\n' || Ch == EOF)
          break;
      }

      PrevLineWasInstruction = true;
    }
  }

  fclose(In);
  fclose(Out);

  return 0;
}
