#!/usr/bin/perl
use Getopt::Std;

=head1 NAME

mactext.pl

=head1 SYNOPSIS

mactext [-m] sourcefile [destinationfile]

=head1 DESCRIPTION

This file converts "Macintized" text files with ctrl-m chars into
UNIX text files with newlines, or converts newline text into ctrl-m.
I.e. it goes back and forth between CR and LF end-of-line markers
much line the venerable dos2unix command (available for UNIX and Windows).
The default is to work like dos2unix, but this can be reversed with the -m
command switch.

Options:

	-m Convert UNIX newline chars into Macintosh ctrl-M chars

sourcefile is, of course, the name of the file you want read.
destinationfile is the name of the file you want written.

If no destination file is given, the source file is converted in place.

=cut

# fetch the command line parameters

	getopts('m');

# Test the number of arguments passed with the command line.
# If there are not the proper number of arguments, exit with
# a usage summary.

	die "Usage: mactext [-m] sourcefile [destfile]\n" if (@ARGV < 1);

# Grab the file type option (to UNIX text or to Mac text), then
# grab the source and destination file names from the command-line
# argument array.

	my $source=$ARGV[0];
	my $dest= ($#ARGV>0) ? $ARGV[1] : $ARGV[0];

# Now try to open the source file. If it fails terminate with
# an error message.

	open(IN, $source) or die "Can't open $source for reading\n";

# Suck the file in and convert the chars. Test the option switch for
# validity and exit with a reason if the switch is unrecognized.

	my @lines=<IN>;
	close IN;

# Try to create the destination file, and warn with an error.

	open(OUT, "> $dest") or die "Can't write to $dest\n";

	map {
	   ($opt_m) ? $_=~s/\n/\cM/g : $_=~s/\cM/\n/g;
	} @lines;

# We should be done now.

	print OUT @lines;

	close OUT;

# Offer a final message.

	print STDERR "$source has been converted and written to $dest\n";