#!/usr/bin/perl -w
#
# Copyright (c) 2002 Mike Fabian <mfabian@suse.de>
#
# 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, 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.

use English;
use Getopt::Long;

sub usage {
  print "Usage: lyx-cjk-upgrade [-debug|d] < old-file.lyx > new-file.lyx \n";
  print "\n";
  print "If you have used multibyte characters within ERT (Evil Red Text)\n";
  print "with older versions of CJK-LyX, CJK-LyX 1.2.0 will probably not\n";
  print "be able to correctly read your old files anymore. All multibyte\n";
  print "characters within ERT will probably vanish\n";
  print "\n";
  print "This script tries to convert such files in a format which is\n";
  print "correctly readable by CJK-LyX 1.2.0\n";
  exit 1;
}

# Process command line options
my %opt;
unless (GetOptions(\%opt,
	'-debug|d' , \$OPT_DEBUG
       )) {
    &usage();
    exit 1;
}

if($OPT_DEBUG) {
}

open (NEW, ">&STDOUT");
open (OLD, "<&STDIN");

while (<OLD>) {
  
  if ( ! ($ARG =~ /^[[:space:]]*\#/)) { # skip comment lines

    if ( $ARG =~ /\\latex[[:space:]]*latex[[:space:]]*/ ) {
      print NEW "\\begin_inset ERT\n";
      print NEW "status Collapsed\n";
      print NEW "\n";
      print NEW "\\layout Standard\n";
      INSET: while (<OLD>) {
	if ( $ARG =~ /\\.+/ && $ARG !~ /\\backslash[[:space:]]*/ ) {
	  print NEW "\\end_inset\n";
	  print NEW $ARG;
	  last INSET;
	}
	else {
	  print NEW $ARG;
	}
      }
    }
    else {
      print NEW $ARG;
    }
  }
}
