#!/usr/bin/perl -wT -I.
#
# TWiki WikiClone (see $wikiversion in wiki.pm for version)
#
# Based on parts of Ward Cunninghams original Wiki and JosWiki.
# Copyright (C) 1998 Markus Peter - SPiN GmbH (warpi@spin.de)
# Some changes by Dave Harris (drh@bhresearch.co.uk) incorporated
# Copyright (C) 1999 Peter Thoeny, peter.thoeny@takefive.com , 
# TakeFive Software Inc.
#
# 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, published at 
# http://www.gnu.ai.mit.edu/copyleft/gpl.html 

use CGI;
use wiki;


$query= new CGI;

&main();

sub main
{
    my $thePathInfo = $query->path_info(); 
    my $theRemoteUser = $query->remote_user();
    my $theTopic = $query->param( 'topic' );
    my $theUrl = $query->url;

    ( $topic, $webName) = 
	&wiki::initialize( $thePathInfo, $theRemoteUser, $theTopic, $theUrl );

    my $text = "", $tmp = "", $atext = "", $before = "", $after = "";

    if( ! &wiki::webExists( $webName ) ) {
	$tmpl= &wiki::readTemplate( "noweb" );
	$tmpl = &wiki::handleCommonTags( $tmpl, $topic );
	print $tmpl;
	return;
    }
    $saveCmd = $query->param( "cmd" );

    if( $saveCmd ne "repRev" ) {
        # normal case: Get latest attachment from file for preview
        $text= &wiki::readTopic( $topic );
        ( $before, $atext, $after) = split( /<!--TWikiAttachment-->/, $text);
        # get the edited text and combine text and attachment
        $text = $query->param( "text" );
        ( $before, $tmp, $after) = split( /<!--TWikiAttachment-->/, $text);
        if( ! $after ) { $after = ""; }
        if( ! $atext ) {
            $text = "$before$after";
        } else {
            $text = "$before$after<!--TWikiAttachment-->$atext<!--TWikiAttachment-->";
        }

    } else {
        # for debug: Use edited text that possibly contains attachment
        $text = $query->param( "text" );
    }

    $text =~ s/%_L_%/</go;
    $text =~ s/%_G_%/>/go;
    $text =~ s/%_Q_%/\"/go;
    $text =~ s/%_A_%/&/go;
    $text =~ s/ {3}/\t/go;

    &wiki::saveTopic( $topic, $text, $saveCmd );
    print $query->redirect( &wiki::viewUrl( $topic ) );
}
