#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/*
 *                            COPYRIGHT
 *
 *  revfilt.c
 *  Copyright (C) 2016 Exstrom Laboratories LLC
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  A copy of the GNU General Public License is available on the internet at:
 *  http://www.gnu.org/copyleft/gpl.html
 *
 *  or you can write to:
 *
 *  The Free Software Foundation, Inc.
 *  675 Mass Ave
 *  Cambridge, MA 02139, USA
 *
 *  Exstrom Laboratories LLC contact:
 *  stefan(AT)exstrom.com
 *
 *  Exstrom Laboratories LLC
 *  Longmont, CO 80503, USA
 *
 */

// Compile: gcc -lm -o revfilt revfilt.c

int main(int argc, char **argv)
{
  if(argc < 2)
  {
    printf("Usage: %s n\n", argv[0]);
    printf("Filters strings of length n that are unique under reversal.\n");
    printf("Strings should be in dictionary order\n");
    return(0);
  }

  int n = atoi(argv[1]);
  char *pstr = (char *)malloc(2*n*sizeof(char));
  char *qstr = (char *)malloc(2*n*sizeof(char));
  int i;

  scanf("%s", pstr);
  printf("%s\n", pstr);
  while(scanf("%s", qstr)!=EOF){
    for(i=0; i<n && qstr[n-1-i] == pstr[i]; ++i);
    if(qstr[n-1-i] > pstr[i]){
      printf("%s\n", qstr);
      strcpy(pstr, qstr);}}

  free(pstr);
  free(qstr);
  return(0);
}
