WeixiangYan/CodeTransOcean huggingface dataset:
Task: Parsing_Shunting-yard algorithm








VB: Module Module1
    Class SymbolType
        Public ReadOnly symbol As String
        Public ReadOnly precedence As Integer
        Public ReadOnly rightAssociative As Boolean

        Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
            Me.symbol = symbol
            Me.precedence = precedence
            Me.rightAssociative = rightAssociative
        End Sub
    End Class

    ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From
    {
        {"^", New SymbolType("^", 4, True)},
        {"*", New SymbolType("*", 3, False)},
        {"/", New SymbolType("/", 3, False)},
        {"+", New SymbolType("+", 2, False)},
        {"-", New SymbolType("-", 2, False)}
    }

    Function ToPostfix(infix As String) As String
        Dim tokens = infix.Split(" ")
        Dim stack As New Stack(Of String)
        Dim output As New List(Of String)

        Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]")

        For Each token In tokens
            Dim iv As Integer
            Dim op1 As SymbolType
            Dim op2 As SymbolType
            If Integer.TryParse(token, iv) Then
                output.Add(token)
                Print(token)
            ElseIf Operators.TryGetValue(token, op1) Then
                While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)
                    Dim c = op1.precedence.CompareTo(op2.precedence)
                    If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then
                        output.Add(stack.Pop())
                    Else
                        Exit While
                    End If
                End While
                stack.Push(token)
                Print(token)
            ElseIf token = "(" Then
                stack.Push(token)
                Print(token)
            ElseIf token = ")" Then
                Dim top = ""
                While stack.Count > 0
                    top = stack.Pop()
                    If top <> "(" Then
                        output.Add(top)
                    Else
                        Exit While
                    End If
                End While
                If top <> "(" Then
                    Throw New ArgumentException("No matching left parenthesis.")
                End If
                Print(token)
            End If
        Next
        While stack.Count > 0
            Dim top = stack.Pop()
            If Not Operators.ContainsKey(top) Then
                Throw New ArgumentException("No matching right parenthesis.")
            End If
            output.Add(top)
        End While
        Print("pop")
        Return String.Join(" ", output)
    End Function

    Sub Main()
        Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
        Console.WriteLine(ToPostfix(infix))
    End Sub

End Module
Task: Read a configuration file






PHP: <?php

$conf = file_get_contents('parse-conf-file.txt');

$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);





$conf = preg_replace_callback(
    '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
    function ($matches) {
        $r = '';
        foreach (explode(',', $matches[2]) AS $val) {
            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;
        }
        return $r;
    },
    $conf
);

$conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);

$ini = parse_ini_string($conf);

echo 'Full name       = ', $ini['FULLNAME'], PHP_EOL;
echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;
echo 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;
echo 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
Task: Case-sensitivity of identifiers






PHP: <?php



$dog = 'Benjamin';
$Dog = 'Samba';
$DOG = 'Bernie';

echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n";


function DOG() { return 'Bernie'; }

echo 'There is only 1 dog named ' . dog() . "\n";
Task: Read a specific line from a file






PHP: <?php  
  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];
  
  function fileLine ($lineNum, $file) {
    $count = 0;
    while (!feof($file)) {
      $count++;
      $line = fgets($file);
      if ($count == $lineNum) return $line;
    }
    die("Requested file has fewer than ".$lineNum." lines!");
  }
    
  @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
  if (!$fp) die("Input file not found!");
  echo fileLine(7, $fp);
?>
Task: URL encoding






PHP: <?php
$s = 'http://foo/bar/';
$s = rawurlencode($s);
?>
Task: Here document






PHP: $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
Task: FTP






PHP: $server = "speedtest.tele2.net";
$user = "anonymous";
$pass = "ftptest@example.com";

$conn = ftp_connect($server);
if (!$conn) {
    die('unable to connect to: '. $server);
}
$login = ftp_login($conn, $user, $pass);
if (!$login) {
    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;
} else{
    echo 'connected successfully'.PHP_EOL;
    $directory = ftp_nlist($conn,'');
    print_r($directory);
}
if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {
    echo "Successfully downloaded file".PHP_EOL;
} else {
    echo "failed to download file";
}
Task: Y combinator






PHP: <?php
function Y($f) {
  $g = function($w) use($f) {
    return $f(function() use($w) {
      return call_user_func_array($w($w), func_get_args());
    });
  };
  return $g($g);
}

$fibonacci = Y(function($f) {
  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});

echo $fibonacci(10), "\n";

$factorial = Y(function($f) {
  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});

echo $factorial(10), "\n";
?>
Task: Sorting algorithms_Bead sort






PHP: <?php
function columns($arr) {
    if (count($arr) == 0)
        return array();
    else if (count($arr) == 1)
        return array_chunk($arr[0], 1);

    array_unshift($arr, NULL);

    $transpose = call_user_func_array('array_map', $arr);
    return array_map('array_filter', $transpose);
}

function beadsort($arr) {
    foreach ($arr as $e)
        $poles []= array_fill(0, $e, 1);
    return array_map('count', columns(columns($poles)));
}

print_r(beadsort(array(5,3,1,7,4,1,1)));
?>
Task: Execute Brain____






PHP: <?php
function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {
   do {
     switch($s[$_s]) {
       case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;
       case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;
       case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;
       case '<': $_d--; break;
       case '.': $o .= $d[$_d]; break;
       case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;
       case '[':
         if((int)ord($d[$_d]) == 0) {
           $brackets = 1;
           while($brackets && $_s++ < strlen($s)) {
             if($s[$_s] == '[')
               $brackets++;
             else if($s[$_s] == ']')
               $brackets--;
           }
         }
         else {
             $pos = $_s++-1;
           if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))
             $_s = $pos;
         }
         break;
       case ']': return ((int)ord($d[$_d]) != 0);
    }
  } while(++$_s < strlen($s));
}

function brainfuck($source, $input='') {
  $data         = array();
  $data[0]      = chr(0);
  $data_index   = 0;
  $source_index = 0;
  $input_index  = 0;
  $output       = '';
  
  brainfuck_interpret($source, $source_index,
                      $data,   $data_index,
                      $input,  $input_index,
                      $output);
  return $output;
}

$code = "
    >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>
    >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.
";
$inp = '123';
print brainfuck( $code, $inp );
Task: Sorting algorithms_Permutation sort






PHP: function inOrder($arr){
	for($i=0;$i<count($arr);$i++){
		if(isset($arr[$i+1])){
			if($arr[$i] > $arr[$i+1]){
				return false;
			}
		}
	}
	return true;
}

function permute($items, $perms = array( )) {
    if (empty($items)) {
		if(inOrder($perms)){
			return $perms;
		}
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             $res = permute($newitems, $newperms);
			 if($res){
				return $res;
			 }		 		 
         }
    }
}

$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);
$arr = permute($arr);
echo implode(',',$arr);
Task: Modulinos






PHP: <?php
function meaning_of_life() {
	return 42;
}

function main($args) {
	echo "Main: The meaning of life is " . meaning_of_life() . "\n";
}

if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) {
	main($argv);
}
?>
Task: Find the last Sunday of each month






PHP: <?php


function printLastSundayOfAllMonth($year)
{
    $months = array(
        'January', 'February', 'March', 'April', 'June', 'July',
        'August', 'September', 'October', 'November', 'December');

    foreach ($months as $month) {
        echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month . ' ' . $year)) . "\n";
    }
}

printLastSundayOfAllMonth($argv[1]);
Task: Dynamic variable names






PHP: <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>
Task: Runtime evaluation_In an environment






PHP: <?php
function eval_with_x($code, $a, $b) {
    $x = $a;
    $first = eval($code);
    $x = $b;
    $second = eval($code);
    return $second - $first;
}
 
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
Task: Runtime evaluation






PHP: <?php
  $code = 'echo "hello world"';
  eval($code);
  $code = 'return "hello world"';
  print eval($code);
Task: Brace expansion






PHP: function getitem($s,$depth=0) {
    $out = [''];
    while ($s) {
        $c = $s[0];
        if ($depth && ($c == ',' || $c == '}')) {
            return [$out, $s];
        }
        if ($c == '{') {
            $x = getgroup(substr($s, 1), $depth + 1);
            if($x) {
                $tmp = [];
                foreach($out as $a) {
                    foreach($x[0] as $b) { 
                        $tmp[] = $a . $b;
                    }
                }
                $out = $tmp;
                $s = $x[1];
                continue;
            }
        }
        if ($c == '\\' && strlen($s) > 1) {
            list($s, $c) = [substr($s, 1), ($c . $s[1])];
        }

        $tmp = [];
        foreach($out as $a) {
            $tmp[] = $a . $c;
        }
        $out = $tmp;
        $s = substr($s, 1);
        
    }
    return [$out, $s];
}
function getgroup($s,$depth) {
    list($out, $comma) = [[], false];
    while ($s) {
        list($g, $s) = getitem($s, $depth);
        if (!$s) {
            break;
        }
        $out = array_merge($out, $g);
        if ($s[0] == '}') {
            if ($comma) {
                return [$out, substr($s, 1)];
            }

            $tmp = [];
            foreach($out as $a) {
                $tmp[] = '{' . $a . '}';
            }
            return [$tmp, substr($s, 1)];
        }
        if ($s[0] == ',') {
            list($comma, $s) = [true, substr($s, 1)];
        }
    }
    return null;
}

$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;

foreach( explode("\n", $lines) as $line ) {
    printf("\n%s\n", $line);
    foreach( getitem($line)[0] as $expansion ) {
        printf("    %s\n", $expansion);
    }
}
Task: Color of a screen pixel






PHP: $img = imagegrabscreen();
$color = imagecolorat($im, 10, 50);
imagedestroy($im);
Task: XML_XPath






PHP: <?php

$doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>');

$xpath = new DOMXPath($doc);

$nodelist = $xpath->query('//item');
$result = $nodelist->item(0);

$nodelist = $xpath->query('//price');
for($i = 0; $i < $nodelist->length; $i++)
{

  print $doc->saveXML($nodelist->item($i))."\n";
}

$nodelist = $xpath->query('//name');

$result = array(); 

foreach($nodelist as $node)
{
  $result[] = $node; 
}
Task: Respond to an unknown method call






PHP: <?php
class Example {
  function foo() {
    echo "this is foo\n";
  }
  function bar() {
    echo "this is bar\n";
  }
  function __call($name, $args) {
    echo "tried to handle unknown method $name\n";
    if ($args)
      echo "it had arguments: ", implode(', ', $args), "\n";
  }
}

$example = new Example();

$example->foo();        // prints "this is foo"
$example->bar();        // prints "this is bar"
$example->grill();      // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"

?>
Task: Hash join






PHP: <?php
function hashJoin($table1, $index1, $table2, $index2) {

    foreach ($table1 as $s)
        $h[$s[$index1]][] = $s;

    foreach ($table2 as $r)
    	foreach ($h[$r[$index2]] as $s)
	    $result[] = array($s, $r);
    return $result;
}

$table1 = array(array(27, "Jonah"),
           array(18, "Alan"),
           array(28, "Glory"),
           array(18, "Popeye"),
           array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
           array("Jonah", "Spiders"),
           array("Alan", "Ghosts"),
           array("Alan", "Zombies"),
           array("Glory", "Buffy"),
           array("Bob", "foo"));

foreach (hashJoin($table1, 1, $table2, 0) as $row)
    print_r($row);
?>
Task: Speech synthesis






PHP: <?php
<?php











$mac_use_espeak = false;





$voice = "espeak";
$statement = 'Hello World!';
$save_file_args = '-w HelloWorld.wav'; // eSpeak args


$OS = strtoupper(substr(PHP_OS, 0, 3));

elseif($OS === 'DAR' && $mac_use_espeak == false) { 
    $voice = "say -v 'Victoria'";
    $save_file_args = '-o HelloWorld.wav'; // say args
}

exec("$voice '$statement'");

exec("$voice '$statement' $save_file_args");
Task: Church numerals






PHP: <?php
$zero = function($f) { return function ($x) { return $x; }; };

$succ = function($n) { 
  return function($f) use (&$n) { 
    return function($x) use (&$n, &$f) {
      return $f( ($n($f))($x) );
    };
  };
};

$add = function($n, $m) {
  return function($f) use (&$n, &$m) {
    return function($x) use (&$f, &$n, &$m) {
      return ($m($f))(($n($f))($x));
    };
  };
};

$mult = function($n, $m) {
  return function($f) use (&$n, &$m) {
    return function($x) use (&$f, &$n, &$m) {
      return ($m($n($f)))($x);
    };
  };
};

$power = function($b,$e) {
  return $e($b);
};

$to_int = function($f) {
  $count_up = function($i) { return $i+1; };
  return ($f($count_up))(0);
};

$from_int = function($x) {
  $countdown = function($i) use (&$countdown) { 
    global $zero, $succ;
    if ( $i == 0 ) {
      return $zero;
    } else {
      return $succ($countdown($i-1));
    };
  };
  return $countdown($x);
};

$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
	       $power($three,$four), $power($four,$three)) as $ch) {
  print($to_int($ch));
  print("\n");
}
?>
Task: Reflection_List properties






PHP: <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;

var_dump(get_object_vars($obj));
?>
Task: XML validation






PHP: libxml_use_internal_errors(true);

$xml = new DOMDocument();
$xml->load('shiporder.xml');

if (!$xml->schemaValidate('shiporder.xsd')) {
    var_dump(libxml_get_errors()); exit;
} else {
    echo 'success';
}
Task: Exceptions

C: #include <setjmp.h>
 
enum { MY_EXCEPTION = 1 }; 
 
jmp_buf env;
 
void foo()
{
  longjmp(env, MY_EXCEPTION); 
}
 
void call_foo()
{
  switch (setjmp(env)) {
  case 0:                     
    foo();
    break;
  case MY_EXCEPTION:          
    
    break;
  default:
    
    
    
    
  }
}
Task: Enforced immutability

C: #define PI      3.14159265358979323
#define MINSIZE 10
#define MAXSIZE 100
Task: Hofstadter Q sequence

C: #include <stdio.h>
#include <stdlib.h>

#define N 100000
int main()
{
	int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;

	q[1] = q[2] = 1;

	for (i = 3; i <= N; i++)
		q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];
		
	for (i = 1; i <= 10; i++)
		printf("%d%c", q[i], i == 10 ? '\n' : ' ');

	printf("%d\n", q[1000]);

	for (flip = 0, i = 1; i < N; i++)
		flip += q[i] > q[i + 1];

	printf("flips: %d\n", flip);
	return 0;
}
Task: Count occurrences of a substring

C: #include <stdio.h>
#include <string.h>

int match(const char *s, const char *p, int overlap)
{
        int c = 0, l = strlen(p);

        while (*s != '\0') {
                if (strncmp(s++, p, l)) continue;
                if (!overlap) s += l - 1;
                c++;
        }
        return c;
}

int main()
{
        printf("%d\n", match("the three truths", "th", 0));
        printf("overlap:%d\n", match("abababababa", "aba", 1));
        printf("not:    %d\n", match("abababababa", "aba", 0));
        return 0;
}
Task: User input_Graphical

C: #include <gtk/gtk.h>

void ok_hit(GtkButton *o, GtkWidget **w)
{
  GtkMessageDialog *msg;

  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);
  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);

  msg = (GtkMessageDialog *)
    gtk_message_dialog_new(NULL,
			   GTK_DIALOG_MODAL,
			   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,
			   GTK_BUTTONS_OK,
			   "You wrote '%s' and selected the number %d%s",
			   c, (gint)v,
			   (v==75000) ? "" : " which is wrong (75000 expected)!");
  gtk_widget_show_all(GTK_WIDGET(msg));
  (void)gtk_dialog_run(GTK_DIALOG(msg));
  gtk_widget_destroy(GTK_WIDGET(msg));
  if ( v==75000 ) gtk_main_quit();
}

int main(int argc, char **argv)
{
  GtkWindow *win;
  GtkEntry *entry;
  GtkSpinButton *spin;
  GtkButton *okbutton;
  GtkLabel *entry_l, *spin_l;
  GtkHBox *hbox[2];
  GtkVBox *vbox;
  GtkWidget *widgs[2];

  gtk_init(&argc, &argv);
  
  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(win, "Insert values");
  
  entry_l = (GtkLabel *)gtk_label_new("Insert a string");
  spin_l =  (GtkLabel *)gtk_label_new("Insert 75000");

  entry = (GtkEntry *)gtk_entry_new();
  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);

  widgs[0] = GTK_WIDGET(entry);
  widgs[1] = GTK_WIDGET(spin);

  okbutton = (GtkButton *)gtk_button_new_with_label("Ok");
  
  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);
  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);

  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);

  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));
  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));
  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));
  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));

  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));
  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));
  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));

  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));

  g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL);
  g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs);

  gtk_widget_show_all(GTK_WIDGET(win));
  gtk_main();

  return 0;
}
Task: Carmichael 3 strong pseudoprimes

C: #include <stdio.h>


#define mod(n,m) ((((n) % (m)) + (m)) % (m))

int is_prime(unsigned int n)
{
    if (n <= 3) {
        return n > 1;
    }
    else if (!(n % 2) || !(n % 3)) {
        return 0;
    }
    else {
        unsigned int i;
        for (i = 5; i*i <= n; i += 6)
            if (!(n % i) || !(n % (i + 2)))
                return 0;
        return 1;
    }
}

void carmichael3(int p1)
{
    if (!is_prime(p1)) return;

    int h3, d, p2, p3;
    for (h3 = 1; h3 < p1; ++h3) {
        for (d = 1; d < h3 + p1; ++d) {
            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {
                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);
                if (!is_prime(p2)) continue;
                p3 = 1 + (p1 * p2 / h3);
                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;
                printf("%d %d %d\n", p1, p2, p3);
            }
        }
    }
}

int main(void)
{
    int p1;
    for (p1 = 2; p1 < 62; ++p1)
        carmichael3(p1);
    return 0;
}
Task: Fractal tree

C: #include <SDL/SDL.h>
#ifdef WITH_CAIRO
#include <cairo.h>
#else
#include <SDL/sge.h>
#endif
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#ifdef WITH_CAIRO
#define PI 3.1415926535
#endif
 
#define SIZE           800   
#define SCALE          5     
#define BRANCHES       14    
#define ROTATION_SCALE 0.75  
#define INITIAL_LENGTH 50    
 
double rand_fl(){
  return (double)rand() / (double)RAND_MAX;
}
 
void draw_tree(SDL_Surface * surface, double offsetx, double offsety,
               double directionx, double directiony, double size,
               double rotation, int depth) {
#ifdef WITH_CAIRO
  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,
                                                               CAIRO_FORMAT_RGB24,
							       surface->w, surface->h,
							       surface->pitch );
  cairo_t *ct = cairo_create(surf);

  cairo_set_line_width(ct, 1);
  cairo_set_source_rgba(ct, 0,0,0,1);
  cairo_move_to(ct, (int)offsetx, (int)offsety);
  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));
  cairo_stroke(ct);
#else
  sge_AALine(surface,
      (int)offsetx, (int)offsety,
      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),
      SDL_MapRGB(surface->format, 0, 0, 0));
#endif
  if (depth > 0){
    
    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(rotation) + directiony * sin(rotation),
        directionx * -sin(rotation) + directiony * cos(rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);
 
    
    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(-rotation) + directiony * sin(-rotation),
        directionx * -sin(-rotation) + directiony * cos(-rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);
  }
}
 
void render(SDL_Surface * surface){
  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));
  draw_tree(surface,
      surface->w / 2.0,
      surface->h - 10.0,
      0.0, -1.0,
      INITIAL_LENGTH,
      PI / 8,
      BRANCHES);
  SDL_UpdateRect(surface, 0, 0, 0, 0);
}
 
int main(){
  SDL_Surface * screen;
  SDL_Event evt;
 
  SDL_Init(SDL_INIT_VIDEO);
 
  srand((unsigned)time(NULL));
 
  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);
 
  render(screen);
  while(1){
    if (SDL_PollEvent(&evt)){
      if(evt.type == SDL_QUIT) break;
    }
    SDL_Delay(1);
  }
  SDL_Quit();
  return 0;
}