#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <unistd.h>

/* program to format a text in traditional cipher format
   suppress all non-char
   burt rosenberg, 25 aug 2004
*/

#define LINE 49

int usage(char * s) {
    printf("usage: %s [-u|-U][-m group|-o offset]\n", s ) ;
    printf("       certain formatting for ciphertext\n") ;
    printf("       -u/U force upper/lower case output\n") ;
    printf("       -o   select and print only letters at offset mod group\n") ;
    printf("       -m   without -o option, number of letters between space\n") ;
    printf("            (use 0 to suppress spaces)\n") ;
    printf("            with -o option, select letters at offset mod group\n") ;
    exit(0) ;
}

int
main( int argc, char * argv[] )
{
  int ch ;
  int ch_indx ; 
  int offset = -1 ;
  int grouping = 5 ;
  int uppercase = 1 ;

  
  while ((ch=getopt( argc, argv, "uUo:m:" ))!=-1 )  
    switch( ch ) {
    case 'U':
       uppercase = 0 ;
       break ;
    case 'u':
       uppercase = 1 ;
       break ;
    case 'm':
       grouping = atoi(optarg) ;
       break ;
    case 'o':
       offset = atoi(optarg) ;
       break ;
    case '?':
    default:
       usage(argv[0]) ;
  }
  argc -= optind ;
  argv += optind ;

  if ( grouping<0 ) grouping = 0 ;
  if ( offset>=0 ) offset %= grouping ; /* bug fix 27 jan 06 */

/* DEBUG */ printf("offset=%d grouping=%d\n", offset, grouping ) ;
  ch_indx = 0 ;

  ch = getc(stdin) ;
  while (ch!=EOF) {
    if ( isalpha(ch) ) {
      ch_indx++ ;
      if ( offset>=0 ) {
         /* select char offset mod grouping */
         if ( ch_indx%grouping==offset )
            printf("%c",(uppercase) ? toupper(ch) : tolower(ch) ) ;
      } else {
         /* negative offset, print every char */
         printf("%c",(uppercase) ? toupper(ch) : tolower(ch) ) ;
         if ( grouping && ch_indx%grouping==0 ) {
           if ( ch_indx>LINE ) {
              printf("\n") ; 
              ch_indx = 0 ;
           }
           else printf(" ") ;
         }
       }
      }
    ch = getc(stdin) ;
  }
  printf("\n") ;
               
}
